This plugin adds full Express compatibility to Fastify, it exposes the same use function of Express, and it allows you to use any Express middleware or application.
| Note | This plugin should not be used as a long-term solution, it aims to help you have a smooth transition from Express to Fastify, but you should migrate your Express specific code to Fastify over time. |
| Since Express does not support Node.js core HTTP/2 module, this plugin does not support HTTP/2 either. |
npm i @fastify/express
| Plugin version | Fastify version |
|---|---|
>=4.x |
^5.x |
>=2.x <4.x |
^4.x |
^1.x |
^3.x |
^0.x |
^2.x |
Please note that if a Fastify version is out of support, then so are the corresponding versions of this plugin in the table above. See Fastify's LTS policy for more details.
Register the plugin and start using your Express middlewares.
const Fastify = require('fastify')
async function build () {
const fastify = Fastify()
await fastify.register(require('@fastify/express'))
// do you know we also have cors support?
// https://github.com/fastify/fastify-cors
fastify.use(require('cors')())
// express.Application is also accessible
fastify.express.disabled('x-powered-by') // true
return fastify
}
build()
.then(fastify => fastify.listen({ port: 3000 }))
.catch(console.log)You can register an entire Express application and make it work with Fastify. Remember, @fastify/express is just express under the covers and requires the same body parsers as you'd use in express.
// index.js
const fastify = require('fastify')()
const express = require('express')
const router = express.Router()
router.use(function (req, res, next) {
res.setHeader('x-custom', true)
next()
})
router.get('/hello', (req, res) => {
res.status(201)
res.json({ hello: 'world' })
})
router.get('/foo', (req, res) => {
res.status(400)
res.json({ foo: 'bar' })
})
router.patch('/bar', (req, res) => {
if (!req.body || Object.keys(req.body).length === 0) {
res.status(400)
res.json({ msg: 'no req.body'})
} else {
res.status(200)
res.json(req.body)
}
})
router.use('*', (req, res) => {
res.status(404)
res.json({ msg: 'not found'})
})
fastify.register(require('@fastify/express'))
.after(() => {
fastify.use(express.urlencoded({extended: false})) // for Postman x-www-form-urlencoded
fastify.use(express.json())
fastify.use(router)
})
fastify.listen({ port: 3000 }, console.log)Run node index.js to start your server. Then run the following commands to ensure your server is working. Use the optional -v flag in curl for verbose output.
me@computer ~ % curl -X GET http://localhost:3000/hello
{"hello":"world"}%
me@computer ~ % curl -X GET http://localhost:3000/foo
{"foo":"bar"}%
me@computer ~ % curl -X GET http://localhost:3000/bar
{"msg":"not found"}%
me@computer ~ % curl -X PATCH -H 'content-type:application/json' http://localhost:3000/bar
{"msg":"no req.body"}%
me@computer ~ % curl -X PATCH -H 'content-type:application/json' -d '{"foo2":"bar2"}' http://localhost:3000/bar
{"foo2":"bar2"}%The encapsulation works as usual with Fastify, you can register the plugin in a subsystem and your express code will work only inside there, or you can declare the express 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.
As with Fastify hooks, a middleware also runs for the routes of the plugins already registered in the instance where use() is called, for example after await fastify.register(plugin).
Register the plugin in its own subsystem:
const fastify = require('fastify')()
fastify.register(subsystem)
async function subsystem (fastify, opts) {
await fastify.register(require('@fastify/express'))
fastify.use(require('cors')())
}Register a middleware in a specific plugin:
const fastify = require('fastify')()
fastify
.register(require('@fastify/express'))
.register(subsystem)
async function subsystem (fastify, opts) {
fastify.use(require('cors')())
}A middleware registered in a plugin runs only for the requests that Fastify routes to that plugin: its own routes and its own not-found handler. A route that exists only in Express, such as one defined in an Express app or router passed to use(), matches no Fastify route, so Fastify sends the request to the not-found handler of the root instance and the plugin's Express code never runs.
To serve Express routes from a plugin, give the plugin a prefix and its own not-found handler:
const fastify = require('fastify')()
const express = require('express')
const app = express()
app.get('/hello', (req, res) => {
res.json({ hello: 'world' })
})
await fastify.register(require('@fastify/express'))
fastify.register(async function (instance) {
instance.use('/', app)
instance.setNotFoundHandler((request, reply) => {
reply.code(404).send({ message: 'Not found' })
})
}, { prefix: '/legacy' })GET /legacy/hello is answered by Express, and any other URL under /legacy that Express does not handle goes to the plugin's not-found handler.
- Mount the app with
instance.use('/', app), notinstance.use(app): only an explicit path gets the plugin prefix, so withuse(app)Express sees/legacy/helloand the app's/helloroute does not match. - The prefix is required. A plugin without a prefix shares the not-found handler of the root instance, so it cannot set its own when the root (or another plugin without a prefix) already has one. To serve Express routes without a prefix, call
use()on the root instance instead.
Every registered middleware will be run during the onRequest hook phase, so the registration order is important.
Take a look at the Lifecycle documentation page to understand better how every request is executed.
const fastify = require('fastify')()
fastify
.register(require('@fastify/express'))
.register(subsystem)
async function subsystem (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')
})
}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!
const fastify = require('fastify')()
const path = require('node:path')
const serveStatic = require('serve-static')
fastify
.register(require('@fastify/express'))
.register(subsystem)
async function subsystem (fastify, opts) {
// Single path
fastify.use('/css', serveStatic(path.join(__dirname, '/assets')))
// Wildcard path
fastify.use('/css/*', serveStatic(path.join(__dirname, '/assets')))
// Multiple paths
fastify.use(['/css', '/js'], serveStatic(path.join(__dirname, '/assets')))
}Note: In prefixed plugins,
@fastify/expressrewrites string, array, and RegExp mount paths to include the prefix. A RegExp path is matched against the rest of the URL after the prefix, as Express does for a mounted router: Express only runs a RegExp mount whose match starts the path, so the pattern must match from the end of the prefix, whether or not it starts with^, and a^inside a group (e.g.,/(?:^\/a|^\/b)/) also anchors there. Thegandyflags are dropped from RegExp mount paths, since they make matching stateful.
Note: A middleware passed to
use()without a path, such as an ExpressRouter, is not mounted at the prefix of a prefixed plugin: it sees the whole URL, prefix included, sorouter.use('/admin', auth)does not run for/v1/adminin a plugin registered with{ prefix: '/v1' }. To make the paths in the router relative to the prefix, like the routes of the plugin, pass'/'as the path:fastify.use('/', router).
Note: Mount paths use the Express path syntax, which differs from the Fastify route syntax. In a mount path a parameter name ends at the first character that cannot be part of an identifier, while in a Fastify route it ends only at
/,-,.or(. For example,/map/:lat,:lnghas two parameters in a mount path but a single one, namedlat,:lng, in a Fastify route, so a middleware mounted there does not run for/map/anything, which the route matches. Separate parameters with/,-or.in paths used for both.
Note: With
routerOptions.ignoreTrailingSlash,/admin/is routed to the/adminroute, but Express matches mount paths against the URL as sent. A string mount path matches both, but aRegExpmount path anchored with$, such as/^\/admin$/, does not match/admin/, as in Express. End the pattern with(?=\/|$)instead, as in/^\/admin(?=\/|$)/.
Note: With case-insensitive routing (
routerOptions.caseSensitive: false), the request path is lowercased while Express matches path-scoped middleware, to mirror the router. Two consequences: middleware sees the lowercased path inreq.urland in Expressreq.params(the original is kept onreq.originalUrl, and route handlers see the original spelling), so avoid relying on case-sensitive path data in middleware in this mode, for exampleserveStaticon a case-sensitive filesystem; andRegExpmount paths are matched case-insensitively (theiflag is added), as string mount paths are.
It is possible to wrap the Express request object in a Proxy by passing createProxyHandler function to generate the Proxy handler. The function will receive the Fastify request object as the first parameter.
For example, using Proxy to expose something from Fastify request into the Express request.
fastify.decorateRequest('welcomeMessage', 'Hello World');
fastify.register(expressPlugin, {
createProxyHandler: fastifyRequest => ({
get (target, prop) {
if (prop === 'welcomeMessage') {
return fastifyRequest[prop]
}
return target[prop]
}
})
})To use this module with TypeScript, make sure to install @types/express.
You will need to add "types": ["@fastify/express"] to your tsconfig.json file when using require to import the plugin.
Fastify offers some alternatives to the most commonly used middleware:
| Express Middleware | Fastify Plugin |
|---|---|
helmet |
@fastify/helmet |
cors |
@fastify/cors |
serve-static |
@fastify/static |
body-parser library incompatible with fastify-express, when you have fastify routes and any express middlewares.
Any POST requests with body, which body-parser will try to parse, will hang up.
Example application:
const Fastify = require('fastify')
const Express = require('express')
const expressPlugin = require('@fastify/express')
const bodyParser = require('body-parser')
const fastify = Fastify()
const express = Express()
express.use(bodyParser.urlencoded({ extended: false }))
await fastify.register(expressPlugin)
fastify.use(express)
// this route will never reply
fastify.post('/hello', (req, reply) => {
return { hello: 'world' }
})For this case, you need to remove body-parser, install @fastify/formbody and change @fastify/express options:
const Fastify = require('fastify')
const Express = require('express')
const expressPlugin = require('@fastify/express')
const fastifyFormBody = require('@fastify/formbody')
const fastify = Fastify()
const express = Express()
await fastify.register(fastifyFormBody)
await fastify.register(expressPlugin, {
// run express after `@fastify/formbody` logic
expressHook: 'preHandler'
})
fastify.use(express)
// it works!
fastify.post('/hello', (req, reply) => {
return { hello: 'world' }
})Licensed under MIT.
express license