Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork27
Middleware engine for Fastify
License
fastify/middie
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
@fastify/middie is the plugin that adds middleware support on steroids toFastify.
The syntax style is the same asexpress/connect.Does not support the full syntaxmiddleware(err, req, res, next), because error handling is done inside Fastify.
npm i @fastify/middieRegister the plugin and start using your middleware.
constFastify=require('fastify')asyncfunctionbuild(){constfastify=Fastify()awaitfastify.register(require('@fastify/middie'),{hook:'onRequest'// default})// do you know we also have cors support?// https://github.com/fastify/fastify-corsfastify.use(require('cors')())returnfastify}build().then(fastify=>fastify.listen({port:3000})).catch(console.log)
The encapsulation works as usual with Fastify, you can register the plugin in a subsystem and your code will work only inside there, or you can declare the middie plugin top level and register a middleware in a nested plugin, and the middleware will be executed only for the nested routes of the specific plugin.
Register the plugin in its own subsystem:
constfastify=require('fastify')()fastify.register(subsystem)asyncfunctionsubsystem(fastify,opts){awaitfastify.register(require('@fastify/middie'))fastify.use(require('cors')())}
Register a middleware in a specific plugin:
constfastify=require('fastify')()fastify.register(require('@fastify/middie')).register(subsystem)asyncfunctionsubsystem(fastify,opts){fastify.use(require('cors')())}
Every registered middleware will be run during theonRequest hook phase, so the registration order is important.Take a look at theLifecycle documentation page to understand better how every request is executed.
constfastify=require('fastify')()fastify.register(require('@fastify/middie')).register(subsystem)asyncfunctionsubsystem(fastify,opts){fastify.addHook('onRequest',async(req,reply)=>{console.log('first')})fastify.use((req,res,next)=>{console.log('second')next()})fastify.addHook('onRequest',async(req,reply)=>{console.log('third')})}
It is possible to change the Fastify hook that the middleware will be attached to. Supported lifecycle hooks are:
onRequestpreParsingpreValidationpreHandlerpreSerializationonSendonResponseonErroronTimeout
To change the hook, pass ahook option like so:
Note you can accessreq.body from thepreParsing,onError,preSerialization, andonSend lifecycle steps. Take a look at theLifecycle documentation page to see the order of the steps.
constfastify=require('fastify')()fastify.register(require('@fastify/middie'),{hook:'preHandler'}).register(subsystem)asyncfunctionsubsystem(fastify,opts){fastify.addHook('onRequest',async(req,reply)=>{console.log('first')})fastify.use((req,res,next)=>{console.log('third')next()})fastify.addHook('onRequest',async(req,reply)=>{console.log('second')})fastify.addHook('preHandler',async(req,reply)=>{console.log('fourth')})}
If you need to run a middleware only under certain path(s), just pass the path as the first parameter to use and you are done!
constfastify=require('fastify')()constpath=require('node:path')constserveStatic=require('serve-static')fastify.register(require('@fastify/middie')).register(subsystem)asyncfunctionsubsystem(fastify,opts){// Single pathfastify.use('/css',serveStatic(path.join(__dirname,'/assets')))// Wildcard pathfastify.use('/css/*',serveStatic(path.join(__dirname,'/assets')))// Multiple pathsfastify.use(['/css','/js'],serveStatic(path.join(__dirname,'/assets')))}
Middie usespath-to-regexp to convert paths to regular expressions.This might cause potentialReDoS attacks in your applications ifcertain patterns are used. Use it with care.
You can also use the engine itself without the Fastify plugin system.
constMiddie=require('@fastify/middie/engine')consthttp=require('node:http')consthelmet=require('helmet')constcors=require('cors')constmiddie=Middie(_runMiddlewares)middie.use(helmet())middie.use(cors())http.createServer(functionhandler(req,res){middie.run(req,res)}).listen(3000)function_runMiddlewares(err,req,res){if(err){console.log(err)res.end(err)return}// => routing function}
If you need it you can also keep the context of the calling function by callingrun withrun(req, res, this), avoiding closures allocation.
http.createServer(functionhandler(req,res){middie.run(req,res,{context:'object'})}).listen(3000)function_runMiddlewares(err,req,res,ctx){if(err){console.log(err)res.end(err)return}console.log(ctx)}
If you need to run a middleware only under certain path(s), just pass the path as the first parameter touse and you are done!
Note that this does support routes with parameters, e.g./user/:id/comments, but all the matched parameters will be discarded
// Single pathmiddie.use('/public',staticFiles('/assets'))// Multiple middlewaremiddie.use('/public',[cors(),staticFiles('/assets')])// Multiple pathsmiddie.use(['/public','/dist'],staticFiles('/assets'))// Multiple paths and multiple middlewaremiddie.use(['/public','/dist'],[cors(),staticFiles('/assets')])
To guarantee compatibility with Express, adding a prefix usespath-to-regexp to computeaRegExp, which is then used to match every request: it is significantly slower.
To use this module with TypeScript, make sure to install@types/connect.
Fastify offers some alternatives to the most commonly used Express middleware:
| Express Middleware | Fastify Plugin |
|---|---|
helmet | fastify-helmet |
cors | fastify-cors |
serve-static | fastify-static |
This project is kindly sponsored by:
Past sponsors:
Licensed underMIT.
About
Middleware engine for Fastify
Topics
Resources
License
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.