Home

Awesome

@fastify/autoload

CI NPM version neostandard javascript style

Convenience plugin for Fastify that loads all plugins found in a directory and automatically configures routes matching the folder structure.

Installation

npm i @fastify/autoload

Compatibility

Plugin versionFastify version
^6.x^5.x
^5.x^4.x
^2.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 version(s) 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:

const fastify = require('fastify')
const autoload = require('@fastify/autoload')

const app = fastify()

app.register(autoload, {
  dir: path.join(__dirname, 'plugins')
})

app.listen({ port: 3000 })

or with ESM syntax:

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 })

Folder structure:

├── plugins
│   ├── hooked-plugin
│   │   ├── autohooks.mjs
│   │   ├── routes.js
│   │   └── children
│   │       ├── commonjs.cjs
│   │       ├── module.mjs
│   │       └── typescript.ts
│   ├── single-plugin
│   │   ├── index.js
│   │   └── utils.js
│   ├── more-plugins
│   │   ├── commonjs.cjs
│   │   ├── module.mjs
│   │   └── typescript.ts
│   └── another-plugin.js
├── package.json
└── app.js

Global Configuration

Autoload can be customised using the following options:

Override TypeScript detection using an environment variable

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.

It can be used like this:

FASTIFY_AUTOLOAD_TYPESCRIPT=1 node --loader=my-custom-loader index.ts

Plugin Configuration

Each plugin can be individually configured using the following module properties:

License

Licensed under MIT.