Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Middleware engine for Fastify

License

NotificationsYou must be signed in to change notification settings

fastify/middie

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

CINPM versionneostandard javascript style

@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.

Install

npm i @fastify/middie

Usage

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

Encapsulation support

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

Hooks and middleware

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:

  • onRequest
  • preParsing
  • preValidation
  • preHandler
  • preSerialization
  • onSend
  • onResponse
  • onError
  • onTimeout

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

Restrict middleware execution to a certain path(s)

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

⚠️ potential ReDoS attacks

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.

Middie Engine

You can also use the engine itself without the Fastify plugin system.

Usage

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}

Keep the context

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

Restrict middleware execution to a certain path(s)

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.

TypeScript support

To use this module with TypeScript, make sure to install@types/connect.

Middleware alternatives

Fastify offers some alternatives to the most commonly used Express middleware:

Express MiddlewareFastify Plugin
helmetfastify-helmet
corsfastify-cors
serve-staticfastify-static

Acknowledgments

This project is kindly sponsored by:

Past sponsors:

License

Licensed underMIT.


[8]ページ先頭

©2009-2025 Movatter.jp