Middleware

Middlewares are called Plugins in Fastify

You can create your own middlewares by following Fastify's Plugin architecture

You can write these in your /app/index.ts file, or in your middlewares, or in your routes if you wish to apply route level

Route Middlewares

Route middlewares are middleware files that are applied to a group of routes in the api directory

app/
├── api/
│   └── v1/
│       └── accounts-search/
│           └── index.ts
│           └── schema.json
│       └── accounts-update/
│           └── index.ts
│           └── schema.json
│       └── 
│   └── webhooks/
│       └── stripe-webhook/
│           └── index.ts
│       └── 
└── ...other files

From the example above, the middleware.ts file is ONLY applied to the route within that directory.

A minimum implementation of a middleware file is below:

app/api/v1/middleware.ts
export default async function Middleware (instance: FastifyInstance) {
    // `instance` is an instance of FastifyInstance
    // All interfaces available to FastifyInstance is available here
    instance.register(async function anotherPlugin() {});
    
    instance.addHook('onReply', async function (request, reply) {});
}

Be careful with scope

Hooks, plugins, decorators defined in app/api/v1/middleware.ts will not be available to routes defined in app/api/webhooks.

Fastify rules for Plugins apply to this file.

Route middlewares that are available out of the box are discussed below:

CSRF

All POST, PUT, PATCH, and DELETEmethods automatically check the csrf of the incoming requests.

The CSRF is in both the local storage of the browser and cookie. If this does not exist in the request, the request will throw a InvalidCsrfTokenError

References:

https://github.com/madewithnovel/novel/blob/main/packages/novel/lib/csrf.js

https://github.com/madewithnovel/novel/blob/main/packages/novel/errors/invalid-csrf-token.js

Changelog

  • 2024-12-20 - Initial Documentation

Last updated

Was this helpful?