Middleware
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:
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) {});
}
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 DELETE
methods 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?