Home

Awesome

@fastify/autoload

CI NPM version js-standard-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

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 'url'
import { dirname, join } from '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

MIT