### Install @fastify/autoload Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Install the @fastify/autoload package using npm. ```bash npm i @fastify/autoload ``` -------------------------------- ### TypeScript Support with ts-node Source: https://context7.com/fastify/fastify-autoload/llms.txt Example of setting up Fastify with @fastify/autoload to load TypeScript files. Ensure your runtime supports TypeScript or use the FASTIFY_AUTOLOAD_TYPESCRIPT environment variable. ```typescript import fastify from 'fastify' import autoload from '@fastify/autoload' import { join, dirname } from 'node:path' import { fileURLToPath } from 'node:url' const __dirname = dirname(fileURLToPath(import.meta.url)) const app = fastify() app.register(autoload, { dir: join(__dirname, 'routes'), // forceESM: true // add if using ts-node/esm or Vitest }) await app.ready() console.log(app.printRoutes()) ``` -------------------------------- ### Configure Autoload with matchFilter Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Register a plugin with @fastify/autoload, using a matchFilter to control which paths are loaded. This example only loads paths where the second-to-last segment is 'handlers'. ```javascript fastify.register(autoLoad, { dir: path.join(__dirname, 'plugins'), matchFilter: (path) => path.split("/").at(-2) === "handlers" }) ``` -------------------------------- ### Register Autoload Plugin (CommonJS) Source: https://context7.com/fastify/fastify-autoload/llms.txt Basic setup for registering @fastify/autoload in a CommonJS environment. Ensure the 'dir' option points to your plugins directory. ```javascript // app.js (CommonJS) const fastify = require('fastify')() const autoload = require('@fastify/autoload') const { join } = require('node:path') fastify.register(autoload, { dir: join(__dirname, 'plugins') }) fastify.listen({ port: 3000 }, (err) => { if (err) { console.error(err); process.exit(1) } console.log('Server running on http://localhost:3000') }) ``` -------------------------------- ### Register Autoload Plugin (ES Modules) Source: https://context7.com/fastify/fastify-autoload/llms.txt Basic setup for registering @fastify/autoload in an ES Modules environment. Ensure the 'dir' option points to your plugins directory. ```javascript // app.mjs (ES Modules) import fastify from 'fastify' import autoload from '@fastify/autoload' import { fileURLToPath } from 'node:url' import { dirname, join } from 'node:path' const __dirname = dirname(fileURLToPath(import.meta.url)) const app = fastify() app.register(autoload, { dir: join(__dirname, 'plugins') }) await app.listen({ port: 3000 }) ``` -------------------------------- ### Configure Autoload with ignorePattern Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Register a plugin with @fastify/autoload, using an ignorePattern (RegExp) to exclude files or folders. This example ignores any file or folder name that contains 'test' or 'spec' followed by '.js'. ```javascript fastify.register(autoLoad, { dir: path.join(__dirname, 'plugins'), ignorePattern: /^.*(?:test|spec).js$/ }) ``` -------------------------------- ### Configure Autoload with scriptPattern Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Register a plugin with @fastify/autoload, using a scriptPattern (RegExp) to override the default accepted script file extensions. This example specifically targets TypeScript files (.ts, .tsx) that are not type definition files (.d.ts). Use with caution and only with compatible providers. ```javascript fastify.register(autoLoad, { dir: path.join(__dirname, 'plugins'), scriptPattern: /(? path.endsWith('.spec.js') }) ``` -------------------------------- ### Basic Fastify Server with Autoload (CommonJS) Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Set up a Fastify server that automatically loads all plugins from the 'plugins' directory using CommonJS syntax. ```javascript const fastify = require('fastify') const autoload = require('@fastify/autoload') const app = fastify() app.register(autoload, { dir: path.join(__dirname, 'plugins') }) app.listen({ port: 3000 }) ``` -------------------------------- ### Basic Fastify Server with Autoload (ESM) Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Set up a Fastify server that automatically loads all plugins from the 'plugins' directory using ESM syntax. Requires Node.js URL and path modules for directory handling. ```javascript import autoLoad from '@fastify/autoload' import { fileURLToPath } from 'node:url' import { dirname, join } from 'node:path' import fastify from 'fastify' const __filename = fileURLToPath(import.meta.url) const __dirname = dirname(__filename) const app = fastify() app.register(autoLoad, { dir: join(__dirname, 'plugins') }) app.listen({ port: 3000 }) ``` -------------------------------- ### Basic AutoHooks Configuration Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Demonstrates the behavior of autoHooks without cascade or overwrite options. Shows how hooks are applied only within their respective plugin scope. ```bash # app.js { autoHooks: true } $ curl http://localhost:3000/standard-plugin/ {} # no hooks in this folder, so behavior is unchanged $ curl http://localhost:3000/hooked-plugin/ { hookOne: 'yes' } $ curl http://localhost:3000/hooked-plugin/children/old {} $ curl http://localhost:3000/hooked-plugin/children/new {} $ curl http://localhost:3000/hooked-plugin/children/grandchildren/ { hookTwo: 'yes' } ``` -------------------------------- ### Configure Global Plugin Options with `options` Source: https://github.com/fastify/fastify-autoload/blob/main/README.md The `options` object provides global configuration for all registered plugins. Options here override `plugin.autoConfig` and can be combined with `plugin.autoPrefix`. ```javascript // index.js fastify.register(autoLoad, { dir: path.join(__dirname, 'plugins'), options: { prefix: '/defaultPrefix' } }) // /plugins/something.js module.exports = function (fastify, opts, next) { // your plugin } module.exports.autoPrefix = '/something' // /plugins/something.mjs export default function (f, opts, next) { f.get('/', (request, reply) => { reply.send({ something: 'else' }) }) next() } export const autoPrefix = '/prefixed' // routes can now be added to /defaultPrefix/something ``` -------------------------------- ### Enable Dynamic Route Parameters with `routeParams: true` Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Setting `routeParams` to `true` allows folders prefixed with `_` to be interpreted as dynamic route parameters. Use `__` for mixed parameters. ```javascript /* ├── routes ├── __country-__language │   │ └── actions.js └── users ├── _id │ └── actions.js ├── __country-__language │ └── actions.js └── index.js └── app.js */ fastify.register(autoLoad, { dir: path.join(__dirname, 'routes'), routeParams: true // routes/users/_id/actions.js will be loaded with prefix /users/:id // routes/__country-__language/actions.js will be loaded with prefix /:country-:language }) // curl http://localhost:3000/users/index // { userIndex: [ { id: 7, username: 'example' } ] } // curl http://localhost:3000/users/7/details // { user: { id: 7, username: 'example' } } // curl http://localhost:3000/be-nl // { country: 'be', language: 'nl' } ``` -------------------------------- ### Manage Plugin Load Order with fastify-plugin Source: https://context7.com/fastify/fastify-autoload/llms.txt Use `fastify-plugin` with `name` and `dependencies` to ensure plugins are registered in the correct order, regardless of filesystem structure. ```javascript // plugins/db.js const fp = require('fastify-plugin') module.exports = fp(async function (fastify) { fastify.decorate('db', { query: async () => [] }) }, { name: 'db' }) // plugins/users.js — depends on db being available const fp = require('fastify-plugin') module.exports = fp(async function (fastify) { fastify.get('/users', async () => fastify.db.query('SELECT * FROM users')) }, { name: 'users', dependencies: ['db'] // autoload registers 'db' first }) ``` -------------------------------- ### Auto-wrapping Route Configuration Objects Source: https://context7.com/fastify/fastify-autoload/llms.txt Demonstrates how @fastify/autoload can register a route directly from a configuration object exported by a plugin file, eliminating the need for a manual plugin wrapper. ```javascript module.exports = { method: 'GET', url: '/ping', schema: { response: { 200: { type: 'object', properties: { pong: { type: 'string' } } } } }, handler: async (request, reply) => ({ pong: 'pong' }) } ``` -------------------------------- ### Set Per-Plugin Default Options with autoConfig Source: https://context7.com/fastify/fastify-autoload/llms.txt Use `autoConfig` to provide default `opts` for a plugin. Global options take precedence. It can also be a function that receives the parent `fastify` instance. ```javascript // plugins/mailer.js module.exports = async function (fastify, opts) { console.log(opts.host) // 'smtp.example.com' console.log(opts.port) // 587 } module.exports.autoConfig = { host: 'smtp.example.com', port: 587 } // With a callback to access the parent instance: module.exports.autoConfig = (fastify) => ({ host: fastify.config.SMTP_HOST, port: Number(fastify.config.SMTP_PORT) }) // Note: autoConfig.prefix must be set directly on the function, not in the return value module.exports.autoConfig.prefix = '/mailer' ``` -------------------------------- ### Plugin Structure with AutoHooks Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Illustrates a project structure with plugins designed to use autoHooks. Includes CJS and ESM syntax for hook definitions. ```javascript // hooked-plugin/autohooks.js module.exports = async function (app, opts) { app.addHook('onRequest', async (req, reply) => { req.hookOne = yes; }); } ``` ```javascript // hooked-plugin/children/grandchildren/autohooks.mjs export default async function (app, opts) { app.addHook('onRequest', async (req, reply) => { req.hookTwo = yes }) } ``` -------------------------------- ### Configure Plugin Options with autoConfig (CJS) Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Set default options for a plugin using the `autoConfig` property. These options will be passed as the `opts` parameter when the plugin is loaded. ```javascript module.exports = function (fastify, opts, next) { console.log(opts.foo) // 'bar' next() } module.exports.autoConfig = { foo: 'bar' } ``` -------------------------------- ### Autoload with Directory Structure Source: https://context7.com/fastify/fastify-autoload/llms.txt Demonstrates how @fastify/autoload interprets directory structure for plugin registration. Subdirectories are automatically prefixed unless an 'index.js' file is present. ```javascript const fastify = require('fastify')() const autoload = require('@fastify/autoload') const { join } = require('node:path') // Load all plugins from the "routes" directory. // Sub-directories become route prefixes automatically. fastify.register(autoload, { dir: join(__dirname, 'routes') }) fastify.ready(() => { console.log(fastify.printRoutes()) // GET /health // GET /products // GET /products/:id // GET /users }) ``` -------------------------------- ### Configure Plugin Options with autoConfig (ESM) Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Configure plugin options using the `autoConfig` export in ESM. This allows for dynamic configuration based on parent instance properties. ```javascript import plugin from '../lib-plugin.js' export default async function myPlugin (app, options) { app.get('/', async (request, reply) => { return { hello: options.name } }) } export const autoConfig = { name: 'y' } ``` ```javascript export const autoConfig = (fastify) => { return { name: 'y ' + fastify.rootName } } ``` ```javascript export const autoConfig = (fastify) => { return { name: 'y ' + fastify.rootName } } autoConfig.prefix = '/hello' ``` -------------------------------- ### Configure Autoload with custom dirNameRoutePrefix function Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Register a plugin with @fastify/autoload, using a custom function for dirNameRoutePrefix. This allows conditional prefixing based on folder names, or disabling it entirely for specific folders. ```javascript fastify.register(autoLoad, { dir: path.join(__dirname, 'routes'), dirNameRoutePrefix: function rewrite (folderParent, folderName) { if (folderName === 'YELLOW') { return 'yellow-submarine' } if (folderName === 'FoOoO-BaAaR') { return false } return folderName } }) ``` -------------------------------- ### Global Plugin Options with Autoload Source: https://context7.com/fastify/fastify-autoload/llms.txt Applies global options to all loaded plugins. These options override per-plugin 'autoConfig' settings and can be combined with 'autoPrefix'. ```javascript // All plugins under routes/ receive { prefix: '/api/v1', timeout: 5000 } fastify.register(autoload, { dir: join(__dirname, 'routes'), options: { prefix: '/api/v1', timeout: 5000 } }) // plugins/users.js — receives opts.timeout === 5000 module.exports = async function (fastify, opts) { fastify.get('/', async () => ({ timeout: opts.timeout })) // accessible at GET /api/v1/users } ``` -------------------------------- ### Define Plugin Dependencies with fastify-plugin (CJS) Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Ensure correct plugin load order by specifying dependencies using `fastify-plugin`. Plugins with dependencies will only load after their dependencies have been registered. ```javascript // plugins/plugin-a.js const fp = require('fastify-plugin') function plugin (fastify, opts, next) { // plugin a } module.exports = fp(plugin, { name: 'plugin-a', dependencies: ['plugin-b'] }) // plugins/plugin-b.js function plugin (fastify, opts, next) { // plugin b } module.exports = fp(plugin, { name: 'plugin-b' }) ``` -------------------------------- ### Opt Out of Autoloading with autoload = false Source: https://context7.com/fastify/fastify-autoload/llms.txt Set the `autoload` export to `false` to prevent `@fastify/autoload` from registering a file, even if it exists in the scanned directory. ```javascript // plugins/utils.js — utility module, not a route plugin module.exports = function (fastify, opts, next) { // This plugin will NOT be auto-registered next() } module.exports.autoload = false // ESM export default async function (fastify) { /* ... */ } export const autoload = false ``` -------------------------------- ### Dynamic Route Parameters with routeParams Source: https://context7.com/fastify/fastify-autoload/llms.txt Enable `routeParams: true` to translate folder names prefixed with `_` into Fastify route parameters (`:param`). A double-underscore prefix `__` creates mixed route params (`:param` without the preceding slash). ```javascript fastify.register(autoload, { dir: join(__dirname, 'routes'), routeParams: true }) // routes/users/_id/index.js module.exports = async function (fastify, opts) { fastify.get('/', async (request) => { return { userId: request.params.id } // GET /users/42 → { userId: '42' } }) } ``` -------------------------------- ### Per-Plugin Route Prefix with autoPrefix Source: https://context7.com/fastify/fastify-autoload/llms.txt Define a module-level export `autoPrefix` to set a specific route prefix for an individual plugin. This prefix is concatenated with any `options.prefix` if both are present. ```javascript // plugins/auth.js module.exports = async function (fastify, opts) { fastify.post('/login', async (request, reply) => { return { token: 'abc123' } }) } module.exports.autoPrefix = '/auth' // Accessible at POST /auth/login regardless of folder name // ESM equivalent export default async function (fastify, opts) { fastify.post('/login', async () => ({ token: 'abc123' })) } export const autoPrefix = '/auth' ``` -------------------------------- ### AutoHooks with CascadeHooks Enabled Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Shows how hooks are accumulated and applied in ascending order when both autoHooks and cascadeHooks are enabled. Hooks from parent plugins are inherited by child plugins. ```bash # app.js { autoHooks: true, cascadeHooks: true } $ curl http://localhost:3000/hooked-plugin/ { hookOne: 'yes' } $ curl http://localhost:3000/hooked-plugin/children/old { hookOne: 'yes' } $ curl http://localhost:3000/hooked-plugin/children/new { hookOne: 'yes' } $ curl http://localhost:3000/hooked-plugin/children/grandchildren/ { hookOne: 'yes', hookTwo: 'yes' } # hooks are accumulated and applied in ascending order ``` -------------------------------- ### Exclude Files with ignorePattern and ignoreFilter Source: https://context7.com/fastify/fastify-autoload/llms.txt Use `ignorePattern` for simple filename matching and `ignoreFilter` for more complex relative path filtering to exclude specific files or directories from being loaded as plugins. ```javascript fastify.register(autoload, { dir: join(__dirname, 'routes'), // Exclude any file whose name matches the pattern (e.g. *.spec.js, *.test.js) ignorePattern: /^.*\.(spec|test)\.js$/, // Exclude files two directories deep whose parent folder is called "handlers" ignoreFilter: (relativePath) => relativePath.split('/').at(-2) !== 'handlers' }) ``` -------------------------------- ### Configure Autoload with dirNameRoutePrefix disabled Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Register a plugin with @fastify/autoload, disabling the automatic route prefixing based on directory names. This means routes will not be prefixed with their parent folder names. ```javascript fastify.register(autoLoad, { dir: path.join(__dirname, 'routes'), dirNameRoutePrefix: false // lack of prefix will mean no prefix, instead of directory name }) ``` -------------------------------- ### Force ESM Loading with `forceESM` Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Set `forceESM` to `true` to ensure that plugins and hooks are always loaded using `await import`, regardless of their file extension. ```javascript fastify.register(autoLoad, { dir: path.join(__dirname, 'plugins'), forceESM: true }) ``` -------------------------------- ### Force ES Module Loading with forceESM Source: https://context7.com/fastify/fastify-autoload/llms.txt When `forceESM` is set to `true`, all plugins are loaded using dynamic `import()`, irrespective of their file extension or the `package.json` `type` field. This is useful for mixing CJS and ESM or when tools require ESM imports. ```javascript fastify.register(autoload, { dir: join(__dirname, 'routes'), forceESM: true }) ``` -------------------------------- ### Custom Folder-Based Route Prefixing Source: https://context7.com/fastify/fastify-autoload/llms.txt Configures how subdirectory names are used as route prefixes. Supports disabling, custom mapping functions, or skipping folders. ```javascript fastify.register(autoload, { dir: join(__dirname, 'routes'), dirNameRoutePrefix: function rewrite (folderParent, folderName) { // Map internal folder names to public URL segments if (folderName === 'v2_internal') return 'v2' if (folderName === 'LEGACY') return false // no prefix for this folder return folderName // default: use the folder name } }) // Folder structure → Resulting route prefix // routes/v2_internal/users.js → /v2/users // routes/LEGACY/old.js → /old (no extra segment from LEGACY) // routes/products/list.js → /products ``` -------------------------------- ### Limit Directory Traversal with maxDepth Source: https://context7.com/fastify/fastify-autoload/llms.txt Control the maximum nesting level for plugin loading using the `maxDepth` option. Plugins deeper than the specified number of directory levels relative to `dir` will be ignored. ```javascript fastify.register(autoload, { dir: join(__dirname, 'plugins'), maxDepth: 2 // A file at plugins/a/b/c/plugin.js (depth 3) is ignored. // A file at plugins/a/b/plugin.js (depth 2) is loaded. }) ``` -------------------------------- ### Configure `indexPattern` for Plugin Loading Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Use `indexPattern` to specify a custom regex for identifying index files when loading plugins. This overrides the default `index.js` convention. ```javascript fastify.register(autoLoad, { dir: path.join(__dirname, 'plugins'), indexPattern: /^.*routes(?:\.ts|\.js|\.cjs|\.mjs)$/ }) ``` -------------------------------- ### Set Plugin Routing Prefix with autoPrefix (CJS) Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Define a routing prefix for a plugin using the `autoPrefix` property. This prefix will be applied when the plugin is loaded by autoload. ```javascript module.exports = function (fastify, opts, next) { fastify.get('/', (request, reply) => { reply.send({ hello: 'world' }) }) next() } module.exports.autoPrefix = '/something' // when loaded with autoload, this will be exposed as /something ``` -------------------------------- ### Custom Index File Name with indexPattern Source: https://context7.com/fastify/fastify-autoload/llms.txt Override the default `index.js` convention by providing an `indexPattern` RegExp. Files matching this pattern will act as the directory index, causing sibling files to be ignored while still traversing sub-directories. ```javascript fastify.register(autoload, { dir: join(__dirname, 'routes'), // Treat files named "routes.js", "routes.ts", etc. as directory indexes indexPattern: /^routes(?:\.ts|\.js|\.cjs|\.mjs)$/ }) ``` -------------------------------- ### AutoHooks with OverwriteHooks Enabled Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Demonstrates the behavior when autoHooks, cascadeHooks, and overwriteHooks are enabled. Child plugin hooks will overwrite parent hooks if they have the same name. ```bash # app.js { autoHooks: true, cascadeHooks: true, overwriteHooks: true } $ curl http://localhost:3000/hooked-plugin/ { hookOne: 'yes' } $ curl http://localhost:3000/hooked-plugin/children/old { hookOne: 'yes' } $ curl http://localhost:3000/hooked-plugin/children/new { hookOne: 'yes' } $ curl http://localhost:3000/hooked-plugin/children/grandchildren/ { hookTwo: 'yes' } # new autohooks.js takes over ``` -------------------------------- ### Toggle Plugin Loading with autoload (CJS) Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Control whether a plugin is loaded by setting the `autoload` property to `false`. This is useful for conditionally including plugins. ```javascript module.exports = function (fastify, opts, next) { // your plugin } // optional module.exports.autoload = false ``` -------------------------------- ### Enable Automatic Hooks with `autoHooks: true` Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Set `autoHooks` to `true` to apply hooks defined in `autohooks.js` files to plugins found in the same folder. Hooks applied this way are encapsulated with their plugins. ```javascript fastify.register(autoLoad, { dir: path.join(__dirname, 'plugins'), autoHooks: true // apply hooks to routes in this level }) ``` -------------------------------- ### Set Plugin Routing Prefix with autoPrefix (ESM) Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Define a routing prefix for a plugin using the `autoPrefix` export in ESM. This ensures routes within the plugin are correctly prefixed. ```javascript export default async function (app, opts) { app.get('/', (request, reply) => { return { something: 'else' } }) } export const autoPrefix = '/prefixed' ``` -------------------------------- ### Override TypeScript Detection with Environment Variable Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Use the FASTIFY_AUTOLOAD_TYPESCRIPT environment variable to manually enable TypeScript loading when automatic detection fails. This is useful with custom Node.js loaders. ```sh FASTIFY_AUTOLOAD_TYPESCRIPT=1 node --loader=my-custom-loader index.ts ``` -------------------------------- ### Override Plugin Prefix with prefixOverride (CJS) Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Use `prefixOverride` to set a specific prefix for a plugin, overriding any default prefixes defined during autoload registration. Set to an empty string to remove all prefixes. ```javascript // index.js fastify.register(autoLoad, { dir: path.join(__dirname, 'plugins'), options: { prefix: '/defaultPrefix' } }) // /foo/something.js module.exports = function (fastify, opts, next) { // your plugin } module.exports.prefixOverride = '/overriddenPrefix' // this will be exposed as /overriddenPrefix ``` ```javascript // index.js fastify.register(autoLoad, { dir: path.join(__dirname, 'plugins'), options: { prefix: '/defaultPrefix' } }) // /foo/something.js module.exports = function (fastify, opts, next) { // your plugin } // optional module.exports.prefixOverride = '' // routes can now be added without a prefix ``` -------------------------------- ### Include Only Matching Files with matchFilter Source: https://context7.com/fastify/fastify-autoload/llms.txt Use `matchFilter` to specify a filter (string, RegExp, or function) that must be satisfied by a file's relative path for it to be loaded as a plugin. This is the inverse of `ignoreFilter`. ```javascript fastify.register(autoload, { dir: join(__dirname, 'routes'), // Only load files that live inside a folder named "handlers" matchFilter: (path) => path.split('/').at(-2) === 'handlers' }) // routes/users/handlers/get.js ← LOADED // routes/users/validators/get.js ← SKIPPED ``` -------------------------------- ### Automatic Lifecycle Hooks with autoHooks Source: https://context7.com/fastify/fastify-autoload/llms.txt When `autoHooks: true`, files named `autohooks.js` in a directory act as hook files, applying their hooks only to plugins within that same directory. ```javascript // routes/autohooks.js — applied to routes in this folder only module.exports = async function (fastify, opts) { fastify.addHook('onRequest', async (request, reply) => { request.user = await authenticate(request.headers.authorization) }) } // routes/users.js — automatically has access to request.user module.exports = async function (fastify) { fastify.get('/', async (request) => ({ user: request.user })) } // app.js fastify.register(autoload, { dir: join(__dirname, 'routes'), autoHooks: true }) ``` -------------------------------- ### Limit Plugin Loading Depth with `maxDepth` Source: https://github.com/fastify/fastify-autoload/blob/main/README.md The `maxDepth` option limits how deeply nested plugins are loaded. Files nested more than the specified depth will be ignored. ```javascript fastify.register(autoLoad, { dir: path.join(__dirname, 'plugins'), maxDepth: 2 // files in `opts.dir` nested more than 2 directories deep will be ignored. }) ``` -------------------------------- ### Override Plugin Prefix with prefixOverride Source: https://context7.com/fastify/fastify-autoload/llms.txt Use `prefixOverride` to completely replace any automatically derived prefix for a plugin. Set to an empty string to remove all prefixes. ```javascript // plugins/internal/admin.js — always mounted at /admin, ignoring folder location module.exports = async function (fastify, opts) { fastify.get('/dashboard', async () => ({ admin: true })) } module.exports.prefixOverride = '/admin' // GET /admin/dashboard // To strip all prefixes: module.exports.prefixOverride = '' ``` -------------------------------- ### Override Plugin Prefix with prefixOverride (ESM) Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Use the `prefixOverride` export in ESM to set a specific prefix for a plugin, overriding any default prefixes. An empty string will remove all prefixes. ```javascript export default async function (app, opts) { // your plugin } export const prefixOverride = '/overriddenPrefix' ``` -------------------------------- ### Hook Inheritance with cascadeHooks and overwriteHooks Source: https://context7.com/fastify/fastify-autoload/llms.txt Configure hook inheritance using `cascadeHooks` and `overwriteHooks`. `cascadeHooks: true` accumulates parent hooks, while `overwriteHooks: true` resets the cascade at each new `autohooks.js`. ```javascript /* routes/ ├── autohooks.js ← adds hookOne ├── users.js └── admin/ ├── autohooks.js ← adds hookTwo └── dashboard.js */ // With cascadeHooks: true // GET /users → hookOne applied // GET /admin/dashboard → hookOne + hookTwo both applied // With cascadeHooks: true, overwriteHooks: true // GET /admin/dashboard → only hookTwo applied (hookOne is overwritten) fastify.register(autoload, { dir: join(__dirname, 'routes'), autoHooks: true, cascadeHooks: true, overwriteHooks: true }) ``` -------------------------------- ### Customize Auto Hooks Naming with `autoHooksPattern` Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Use `autoHooksPattern` to define a custom regex for identifying auto hook files, overriding the default `autohooks.js` naming convention. ```javascript fastify.register(autoLoad, { dir: path.join(__dirname, 'plugins'), autoHooks: true, autoHooksPattern: /^[_.]?auto_?hooks(?:\.js|\.cjs|\.mjs)$/i }) ``` -------------------------------- ### Disable Plugin Encapsulation with `encapsulate: false` Source: https://github.com/fastify/fastify-autoload/blob/main/README.md Setting `encapsulate` to `false` prevents each loaded plugin from being wrapped with `fastify-plugin`. This is useful for sharing contexts, decorators, or parent contexts between plugins. ```javascript fastify.register(autoLoad, { dir: path.join(__dirname, 'plugins'), encapsulate: false }) ``` -------------------------------- ### Share Context Between Plugins with encapsulate: false Source: https://context7.com/fastify/fastify-autoload/llms.txt Set `encapsulate` to `false` to disable Fastify's encapsulation boundary for loaded plugins. This allows decorators, hooks, and other context items from child plugins to be visible to parent and sibling plugins. ```javascript // plugins/db.js — adds a decorator that should be shared globally const fp = require('fastify-plugin') module.exports = fp(async function (fastify) { fastify.decorate('db', { query: async (sql) => ({ rows: [] }) }) }) // app.js fastify.register(autoload, { dir: join(__dirname, 'plugins'), encapsulate: false // fastify.db is now visible to the whole app }) fastify.ready(() => { console.log(fastify.db) // { query: [AsyncFunction] } }) ``` -------------------------------- ### Cascade Hooks with `cascadeHooks: true` Source: https://github.com/fastify/fastify-autoload/blob/main/README.md When `autoHooks` is enabled, setting `cascadeHooks` to `true` ensures that hooks are applied not only to the current level but also cascaded down to all child plugins. ```javascript fastify.register(autoLoad, { dir: path.join(__dirname, 'plugins'), autoHooks: true, // apply hooks to routes in this level, cascadeHooks: true // continue applying hooks to children, starting at this level }) ``` -------------------------------- ### Overwrite Hooks with `overwriteHooks: true` Source: https://github.com/fastify/fastify-autoload/blob/main/README.md If `cascadeHooks` is active, `overwriteHooks: true` will reset the hook cascade whenever a new `autohooks.js` file is encountered, instead of accumulating hooks. ```javascript fastify.register(autoLoad, { dir: path.join(__dirname, 'plugins'), autoHooks: true, // apply hooks to routes in this level, cascadeHooks: true, // continue applying hooks to children, starting at this level, overwriteHooks: true // re-start hook cascade when a new `autohooks.js` file is found }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.