Convenience plugin for Fastify that loads all plugins found in a directory and automatically configures routes matching the folder structure.
Installation
eomm
behemoth89@gmail.com
npm i @fastify/autoload
Compatibility
Plugin version
Fastify version
>=6.x
^5.x
^5.x
^4.x
>=2.x <5.x
^3.x
^1.x
^2.x
^1.x
^1.x
Please note that if a Fastify version is out of support, then so are the corresponding versions of this plugin
in the table above.
See Fastify's LTS policy for more details.
Example
Fastify server that automatically loads in all plugins from the plugins directory:
Autoload can be customized using the following options:
dir (required)
Base directory containing plugins to be loaded.
Each script file within a directory is treated as a plugin unless the directory contains an index file (e.g. index.js). In which case, only the index file (and the potential sub-directories) will be loaded.
The following script types are supported:
.js (CommonJS or ES modules depending on type field of parent package.json)
.cjs (CommonJS)
.mjs (ES modules)
.ts (TypeScript)
dirNameRoutePrefix (optional) - Default: true
Determines whether routes will be automatically prefixed with the subdirectory name in an autoloaded directory. It can be a sync function that must return a string that will be used as prefix, or it must return false to skip the prefix for the directory.
fastify.register(autoLoad, { dir: path.join(__dirname, 'routes'), dirNameRoutePrefix: false // lack of prefix will mean no prefix, instead of directory name})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 }})
appendAutoPrefix (optional) - Default: false
Controls how autoPrefix from a plugin file is combined with the directory-derived prefix.
false (default): autoPrefix replaces the directory-derived prefix for that plugin.
true: the directory-derived prefix is kept, and autoPrefix is appended after it.
Regex to override the script files accepted by default. You should only use this option with a customization hooksprovider, such as ts-node. Otherwise, widening the acceptance extension here will result in an error.
Limits the depth at which nested plugins are loaded.
fastify.register(autoLoad, { dir: path.join(__dirname, 'plugins'), maxDepth: 2 // files in `opts.dir` nested more than 2 directories deep will be ignored.})
forceESM (optional)
If set to 'true' it always use await import to load plugins or hooks.
If set to false each plugin loaded is wrapped with fastify-plugin. This allows you to share contexts between plugins and the parent context if needed. For example, if you need to share decorators. Read this for more details.
Global options object used for all registered plugins.
Any option specified here will override plugin.autoConfig options specified in the plugin itself.
When setting both options.prefix and plugin.autoPrefix they will be concatenated.
By default, plugin.autoPrefix replaces directory-derived prefixes. Set appendAutoPrefix: true to keep directory prefixes and append plugin.autoPrefix after them.
// index.jsfastify.register(autoLoad, { dir: path.join(__dirname, 'plugins'), options: { prefix: '/defaultPrefix' }})// /plugins/something.jsmodule.exports = function (fastify, opts, next) { // your plugin}module.exports.autoPrefix = '/something'// /plugins/something.mjsexport 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
autoHooks (optional)
Apply hooks from autohooks.js file(s) to plugins found in folder.
Automatic hooks from autohooks files will be encapsulated with plugins. If false, all autohooks.js files will be ignored.
fastify.register(autoLoad, { dir: path.join(__dirname, 'plugins'), autoHooks: true // apply hooks to routes in this level})
If autoHooks is set, all plugins in the folder will be encapsulated
and decorated values will not be exported outside the folder.
autoHooksPattern (optional)
Regex to override the autohooks naming convention.
If using autoHooks, cascade hooks to all children. Ignored if autoHooks is false.
Default behavior of autoHooks is to apply hooks only to the level on which the autohooks.js file is found. Setting cascadeHooks: true will continue applying the hooks to any children.
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 (optional)
If using cascadeHooks, cascade will be reset when a new autohooks.js file is encountered. Ignored if autoHooks is false.
Default behavior of cascadeHooks is to accumulate hooks as new autohooks.js files are discovered and cascade to children. Setting overwriteHooks: true will start a new hook cascade when new autohooks.js files are encountered.
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})
routeParams (optional)
Folders prefixed with _ will be turned into dynamic route parameters. If you want to use mixed route parameters use a double underscore __.
It is possible to override the automatic detection of a TypeScript-capable runtime using the FASTIFY_AUTOLOAD_TYPESCRIPT environment variable. If set to a truthy value Autoload will load .ts files, expecting that node has a TypeScript-capable loader.
This is useful for cases where you want to use Autoload for loading TypeScript files but detecting the TypeScript loader fails because, for example, you are using a custom loader.
plugin.autoPrefix overrides directory-derived prefixes by default. Use the global appendAutoPrefix option to append plugin.autoPrefix to directory prefixes instead.
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
// index.jsfastify.register(autoLoad, { dir: path.join(__dirname, 'plugins'), options: { prefix: '/defaultPrefix' }})// /foo/something.jsmodule.exports = function (fastify, opts, next) { // your plugin}module.exports.prefixOverride = '/overriddenPrefix'// this will be exposed as /overriddenPrefix
Or with ESM syntax:
export default async function (app, opts) { // your plugin}export const prefixOverride = '/overriddenPrefix'
If you have a plugin in the folder you do not want any prefix applied to, you can set prefixOverride = '':
// index.jsfastify.register(autoLoad, { dir: path.join(__dirname, 'plugins'), options: { prefix: '/defaultPrefix' }})// /foo/something.jsmodule.exports = function (fastify, opts, next) { // your plugin}// optionalmodule.exports.prefixOverride = ''// routes can now be added without a prefix
plugin.autoload
Toggle whether the plugin should be loaded.
Example:
module.exports = function (fastify, opts, next) { // your plugin}// optionalmodule.exports.autoload = false
opts.name
Set name of plugin so that it can be referenced as a dependency.
opts.dependencies
Set plugin dependencies to ensure correct load order.
The autohooks functionality provides several options for automatically adding hooks, decorators, etc. to your routes. CJS and ESM autohook formats are supported.
The default behavior of autoHooks: true is to encapsulate the autohooks.js plugin with the contents of the folder containing the file. The cascadeHooks: true option encapsulates the hooks with the current folder contents and all subsequent children, with any additional autohooks.js files being applied cumulatively. The overwriteHooks: true option will restart the cascade any time an autohooks.js file is encountered.