Routes

Routes

The route methods will configure the endpoints of your application. You have two ways to declare a route with Fastify: the shorthand method and the full declaration.

Full declaration

  1. fastify.route(options)

Routes options

  • method: currently it supports GET, HEAD, TRACE, DELETE, OPTIONS, PATCH, PUT and POST. To accept more methods, the addHttpMethod must be used. It could also be an array of methods.

  • url: the path of the URL to match this route (alias: path).

  • schema: an object containing the schemas for the request and response. They need to be in JSON Schema format, check here for more info.

    • body: validates the body of the request if it is a POST, PUT, PATCH, TRACE, SEARCH, PROPFIND, PROPPATCH or LOCK method.
    • querystring or query: validates the querystring. This can be a complete JSON Schema object, with the property type of object and properties object of parameters, or simply the values of what would be contained in the properties object as shown below.
    • params: validates the params.
    • response: filter and generate a schema for the response, setting a schema allows us to have 10-20% more throughput.
  • exposeHeadRoute: creates a sibling HEAD route for any GET routes. Defaults to the value of exposeHeadRoutes instance option. If you want a custom HEAD handler without disabling this option, make sure to define it before the GET route.

  • attachValidation: attach validationError to request, if there is a schema validation error, instead of sending the error to the error handler. The default error format is the Ajv one.

  • onRequest(request, reply, done): a function called as soon as a request is received, it could also be an array of functions.

  • preParsing(request, reply, done): a function called before parsing the request, it could also be an array of functions.

  • preValidation(request, reply, done): a function called after the shared preValidation hooks, useful if you need to perform authentication at route level for example, it could also be an array of functions.

  • preHandler(request, reply, done): a function called just before the request handler, it could also be an array of functions.

  • preSerialization(request, reply, payload, done): a function called just before the serialization, it could also be an array of functions.

  • onSend(request, reply, payload, done): a function called right before a response is sent, it could also be an array of functions.

  • onResponse(request, reply, done): a function called when a response has been sent, so you will not be able to send more data to the client. It could also be an array of functions.

  • onTimeout(request, reply, done): a function called when a request is timed out and the HTTP socket has been hung up.

  • onError(request, reply, error, done): a function called when an Error is thrown or sent to the client by the route handler.

  • handler(request, reply): the function that will handle this request. The Fastify server will be bound to this when the handler is called. Note: using an arrow function will break the binding of this.

  • errorHandler(error, request, reply): a custom error handler for the scope of the request. Overrides the default error global handler, and anything set by setErrorHandler, for requests to the route. To access the default handler, you can access instance.errorHandler. Note that this will point to fastify’s default errorHandler only if a plugin hasn’t overridden it already.

  • childLoggerFactory(logger, binding, opts, rawReq): a custom factory function that will be called to produce a child logger instance for every request. See childLoggerFactory for more info. Overrides the default logger factory, and anything set by setChildLoggerFactory, for requests to the route. To access the default factory, you can access instance.childLoggerFactory. Note that this will point to Fastify’s default childLoggerFactory only if a plugin hasn’t overridden it already.

  • validatorCompiler({ schema, method, url, httpPart }): function that builds schemas for request validations. See the Validation and Serialization documentation.

  • serializerCompiler({ { schema, method, url, httpStatus, contentType } }): function that builds schemas for response serialization. See the Validation and Serialization documentation.

  • schemaErrorFormatter(errors, dataVar): function that formats the errors from the validation compiler. See the Validation and Serialization documentation. Overrides the global schema error formatter handler, and anything set by setSchemaErrorFormatter, for requests to the route.

  • bodyLimit: prevents the default JSON body parser from parsing request bodies larger than this number of bytes. Must be an integer. You may also set this option globally when first creating the Fastify instance with fastify(options). Defaults to 1048576 (1 MiB).

  • logLevel: set log level for this route. See below.

  • logSerializers: set serializers to log for this route.

  • config: object used to store custom configuration.

  • version: a semver compatible string that defined the version of the endpoint. Example.

  • constraints: defines route restrictions based on request properties or values, enabling customized matching using find-my-way constraints. Includes built-in version and host constraints, with support for custom constraint strategies.

  • prefixTrailingSlash: string used to determine how to handle passing / as a route with a prefix.

    • both (default): Will register both /prefix and /prefix/.
    • slash: Will register only /prefix/.
    • no-slash: Will register only /prefix.

    Note: this option does not override ignoreTrailingSlash in Server configuration.

  • request is defined in Request.

  • reply is defined in Reply.

Notice: The documentation of onRequest, preParsing, preValidation, preHandler, preSerialization, onSend, and onResponse are described in more detail in Hooks. Additionally, to send a response before the request is handled by the handler please refer to Respond to a request from a hook.

Example:

  1. fastify.route({
  2. method: 'GET',
  3. url: '/',
  4. schema: {
  5. querystring: {
  6. name: { type: 'string' },
  7. excitement: { type: 'integer' }
  8. },
  9. response: {
  10. 200: {
  11. type: 'object',
  12. properties: {
  13. hello: { type: 'string' }
  14. }
  15. }
  16. }
  17. },
  18. handler: function (request, reply) {
  19. reply.send({ hello: 'world' })
  20. }
  21. })

Shorthand declaration

The above route declaration is more Hapi-like, but if you prefer an Express/Restify approach, we support it as well:

fastify.get(path, [options], handler)

fastify.head(path, [options], handler)

fastify.post(path, [options], handler)

fastify.put(path, [options], handler)

fastify.delete(path, [options], handler)

fastify.options(path, [options], handler)

fastify.patch(path, [options], handler)

Example:

  1. const opts = {
  2. schema: {
  3. response: {
  4. 200: {
  5. type: 'object',
  6. properties: {
  7. hello: { type: 'string' }
  8. }
  9. }
  10. }
  11. }
  12. }
  13. fastify.get('/', opts, (request, reply) => {
  14. reply.send({ hello: 'world' })
  15. })

fastify.all(path, [options], handler) will add the same handler to all the supported methods.

The handler may also be supplied via the options object:

  1. const opts = {
  2. schema: {
  3. response: {
  4. 200: {
  5. type: 'object',
  6. properties: {
  7. hello: { type: 'string' }
  8. }
  9. }
  10. }
  11. },
  12. handler: function (request, reply) {
  13. reply.send({ hello: 'world' })
  14. }
  15. }
  16. fastify.get('/', opts)

Note: if the handler is specified in both the options and as the third parameter to the shortcut method then throws a duplicate handler error.

Url building

Fastify supports both static and dynamic URLs.

To register a parametric path, use the colon before the parameter name. For wildcard, use the star. Remember that static routes are always checked before parametric and wildcard.

  1. // parametric
  2. fastify.get('/example/:userId', function (request, reply) {
  3. // curl ${app-url}/example/12345
  4. // userId === '12345'
  5. const { userId } = request.params;
  6. // your code here
  7. })
  8. fastify.get('/example/:userId/:secretToken', function (request, reply) {
  9. // curl ${app-url}/example/12345/abc.zHi
  10. // userId === '12345'
  11. // secretToken === 'abc.zHi'
  12. const { userId, secretToken } = request.params;
  13. // your code here
  14. })
  15. // wildcard
  16. fastify.get('/example/*', function (request, reply) {})

Regular expression routes are supported as well, but be aware that you have to escape slashes. Take note that RegExp is also very expensive in terms of performance!

  1. // parametric with regexp
  2. fastify.get('/example/:file(^\\d+).png', function (request, reply) {
  3. // curl ${app-url}/example/12345.png
  4. // file === '12345'
  5. const { file } = request.params;
  6. // your code here
  7. })

It is possible to define more than one parameter within the same couple of slash (“/“). Such as:

  1. fastify.get('/example/near/:lat-:lng/radius/:r', function (request, reply) {
  2. // curl ${app-url}/example/near/15°N-30°E/radius/20
  3. // lat === "15°N"
  4. // lng === "30°E"
  5. // r ==="20"
  6. const { lat, lng, r } = request.params;
  7. // your code here
  8. })

Remember in this case to use the dash (“-“) as parameters separator.

Finally, it is possible to have multiple parameters with RegExp:

  1. fastify.get('/example/at/:hour(^\\d{2})h:minute(^\\d{2})m', function (request, reply) {
  2. // curl ${app-url}/example/at/08h24m
  3. // hour === "08"
  4. // minute === "24"
  5. const { hour, minute } = request.params;
  6. // your code here
  7. })

In this case as parameter separator it is possible to use whatever character is not matched by the regular expression.

The last parameter can be made optional if you add a question mark (“?”) to the end of the parameters name.

  1. fastify.get('/example/posts/:id?', function (request, reply) {
  2. const { id } = request.params;
  3. // your code here
  4. })

In this case you can request /example/posts as well as /example/posts/1. The optional param will be undefined if not specified.

Having a route with multiple parameters may negatively affect performance, so prefer a single parameter approach whenever possible, especially on routes that are on the hot path of your application. If you are interested in how we handle the routing, check out find-my-way.

If you want a path containing a colon without declaring a parameter, use a double colon. For example:

  1. fastify.post('/name::verb') // will be interpreted as /name:verb

Async Await

Are you an async/await user? We have you covered!

  1. fastify.get('/', options, async function (request, reply) {
  2. var data = await getData()
  3. var processed = await processData(data)
  4. return processed
  5. })

As you can see, we are not calling reply.send to send back the data to the user. You just need to return the body and you are done!

If you need it you can also send back the data to the user with reply.send. In this case do not forget to return reply or await reply in your async handler or you will introduce a race condition in certain situations.

  1. fastify.get('/', options, async function (request, reply) {
  2. var data = await getData()
  3. var processed = await processData(data)
  4. return reply.send(processed)
  5. })

If the route is wrapping a callback-based API that will call reply.send() outside of the promise chain, it is possible to await reply:

  1. fastify.get('/', options, async function (request, reply) {
  2. setImmediate(() => {
  3. reply.send({ hello: 'world' })
  4. })
  5. await reply
  6. })

Returning reply also works:

  1. fastify.get('/', options, async function (request, reply) {
  2. setImmediate(() => {
  3. reply.send({ hello: 'world' })
  4. })
  5. return reply
  6. })

Warning:

  • When using both return value and reply.send(value) at the same time, the first one that happens takes precedence, the second value will be discarded, and a warn log will also be emitted because you tried to send a response twice.
  • Calling reply.send() outside of the promise is possible but requires special attention. For more details read promise-resolution.
  • You cannot return undefined. For more details read promise-resolution.

Promise resolution

If your handler is an async function or returns a promise, you should be aware of the special behavior that is necessary to support the callback and promise control-flow. When the handler’s promise is resolved, the reply will be automatically sent with its value unless you explicitly await or return reply in your handler.

  1. If you want to use async/await or promises but respond with a value with reply.send:
    • Do return reply / await reply.
    • Do not forget to call reply.send.
  2. If you want to use async/await or promises:
    • Do not use reply.send.
    • Do return the value that you want to send.

In this way, we can support both callback-style and async-await, with the minimum trade-off. Despite so much freedom we highly recommend going with only one style because error handling should be handled in a consistent way within your application.

Notice: Every async function returns a promise by itself.

Route Prefixing

Sometimes you need to maintain two or more different versions of the same API; a classic approach is to prefix all the routes with the API version number, /v1/user for example. Fastify offers you a fast and smart way to create different versions of the same API without changing all the route names by hand, route prefixing. Let’s see how it works:

  1. // server.js
  2. const fastify = require('fastify')()
  3. fastify.register(require('./routes/v1/users'), { prefix: '/v1' })
  4. fastify.register(require('./routes/v2/users'), { prefix: '/v2' })
  5. fastify.listen({ port: 3000 })
  1. // routes/v1/users.js
  2. module.exports = function (fastify, opts, done) {
  3. fastify.get('/user', handler_v1)
  4. done()
  5. }
  1. // routes/v2/users.js
  2. module.exports = function (fastify, opts, done) {
  3. fastify.get('/user', handler_v2)
  4. done()
  5. }

Fastify will not complain because you are using the same name for two different routes, because at compilation time it will handle the prefix automatically (this also means that the performance will not be affected at all!).

Now your clients will have access to the following routes:

  • /v1/user
  • /v2/user

You can do this as many times as you want, it also works for nested register, and route parameters are supported as well.

In case you want to use prefix for all of your routes, you can put them inside a plugin:

  1. const fastify = require('fastify')()
  2. const route = {
  3. method: 'POST',
  4. url: '/login',
  5. handler: () => {},
  6. schema: {},
  7. }
  8. fastify.register(function (app, _, done) {
  9. app.get('/users', () => {})
  10. app.route(route)
  11. done()
  12. }, { prefix: '/v1' }) // global route prefix
  13. await fastify.listen({ port: 3000 })

Route Prefixing and fastify-plugin

Be aware that if you use fastify-plugin for wrapping your routes, this option will not work. You can still make it work by wrapping a plugin in a plugin, e. g.:

  1. const fp = require('fastify-plugin')
  2. const routes = require('./lib/routes')
  3. module.exports = fp(async function (app, opts) {
  4. app.register(routes, {
  5. prefix: '/v1',
  6. })
  7. }, {
  8. name: 'my-routes'
  9. })

Handling of / route inside prefixed plugins

The / route has different behavior depending on if the prefix ends with / or not. As an example, if we consider a prefix /something/, adding a / route will only match /something/. If we consider a prefix /something, adding a / route will match both /something and /something/.

See the prefixTrailingSlash route option above to change this behavior.

Custom Log Level

You might need different log levels in your routes; Fastify achieves this in a very straightforward way.

You just need to pass the option logLevel to the plugin option or the route option with the value that you need.

Be aware that if you set the logLevel at plugin level, also the setNotFoundHandler and setErrorHandler will be affected.

  1. // server.js
  2. const fastify = require('fastify')({ logger: true })
  3. fastify.register(require('./routes/user'), { logLevel: 'warn' })
  4. fastify.register(require('./routes/events'), { logLevel: 'debug' })
  5. fastify.listen({ port: 3000 })

Or you can directly pass it to a route:

  1. fastify.get('/', { logLevel: 'warn' }, (request, reply) => {
  2. reply.send({ hello: 'world' })
  3. })

Remember that the custom log level is applied only to the routes, and not to the global Fastify Logger, accessible with fastify.log

Custom Log Serializer

In some contexts, you may need to log a large object but it could be a waste of resources for some routes. In this case, you can define custom serializers and attach them in the right context!

  1. const fastify = require('fastify')({ logger: true })
  2. fastify.register(require('./routes/user'), {
  3. logSerializers: {
  4. user: (value) => `My serializer one - ${value.name}`
  5. }
  6. })
  7. fastify.register(require('./routes/events'), {
  8. logSerializers: {
  9. user: (value) => `My serializer two - ${value.name} ${value.surname}`
  10. }
  11. })
  12. fastify.listen({ port: 3000 })

You can inherit serializers by context:

  1. const fastify = Fastify({
  2. logger: {
  3. level: 'info',
  4. serializers: {
  5. user (req) {
  6. return {
  7. method: req.method,
  8. url: req.url,
  9. headers: req.headers,
  10. host: req.host,
  11. remoteAddress: req.ip,
  12. remotePort: req.socket.remotePort
  13. }
  14. }
  15. }
  16. }
  17. })
  18. fastify.register(context1, {
  19. logSerializers: {
  20. user: value => `My serializer father - ${value}`
  21. }
  22. })
  23. async function context1 (fastify, opts) {
  24. fastify.get('/', (req, reply) => {
  25. req.log.info({ user: 'call father serializer', key: 'another key' })
  26. // shows: { user: 'My serializer father - call father serializer', key: 'another key' }
  27. reply.send({})
  28. })
  29. }
  30. fastify.listen({ port: 3000 })

Config

Registering a new handler, you can pass a configuration object to it and retrieve it in the handler.

  1. // server.js
  2. const fastify = require('fastify')()
  3. function handler (req, reply) {
  4. reply.send(reply.routeOptions.config.output)
  5. }
  6. fastify.get('/en', { config: { output: 'hello world!' } }, handler)
  7. fastify.get('/it', { config: { output: 'ciao mondo!' } }, handler)
  8. fastify.listen({ port: 3000 })

Constraints

Fastify supports constraining routes to match only certain requests based on some property of the request, like the Host header, or any other value via find-my-way constraints. Constraints are specified in the constraints property of the route options. Fastify has two built-in constraints ready for use: the version constraint and the host constraint, and you can add your own custom constraint strategies to inspect other parts of a request to decide if a route should be executed for a request.

Version Constraints

You can provide a version key in the constraints option to a route. Versioned routes allow you to declare multiple handlers for the same HTTP route path, which will then be matched according to each request’s Accept-Version header. The Accept-Version header value should follow the semver specification, and routes should be declared with exact semver versions for matching.

Fastify will require a request Accept-Version header to be set if the route has a version set, and will prefer a versioned route to a non-versioned route for the same path. Advanced version ranges and pre-releases currently are not supported.

Be aware that using this feature will cause a degradation of the overall performances of the router.

  1. fastify.route({
  2. method: 'GET',
  3. url: '/',
  4. constraints: { version: '1.2.0' },
  5. handler: function (request, reply) {
  6. reply.send({ hello: 'world' })
  7. }
  8. })
  9. fastify.inject({
  10. method: 'GET',
  11. url: '/',
  12. headers: {
  13. 'Accept-Version': '1.x' // it could also be '1.2.0' or '1.2.x'
  14. }
  15. }, (err, res) => {
  16. // { hello: 'world' }
  17. })

⚠ Security Notice

Remember to set a Vary header in your responses with the value you are using for defining the versioning (e.g.: 'Accept-Version'), to prevent cache poisoning attacks. You can also configure this as part of your Proxy/CDN.

  1. const append = require('vary').append
  2. fastify.addHook('onSend', (req, reply, payload, done) => {
  3. if (req.headers['accept-version']) { // or the custom header you are using
  4. let value = reply.getHeader('Vary') || ''
  5. const header = Array.isArray(value) ? value.join(', ') : String(value)
  6. if ((value = append(header, 'Accept-Version'))) { // or the custom header you are using
  7. reply.header('Vary', value)
  8. }
  9. }
  10. done()
  11. })

If you declare multiple versions with the same major or minor, Fastify will always choose the highest compatible with the Accept-Version header value.

If the request will not have the Accept-Version header, a 404 error will be returned.

It is possible to define a custom version matching logic. This can be done through the constraints configuration when creating a Fastify server instance.

Host Constraints

You can provide a host key in the constraints route option for to limit that route to only be matched for certain values of the request Host header. host constraint values can be specified as strings for exact matches or RegExps for arbitrary host matching.

  1. fastify.route({
  2. method: 'GET',
  3. url: '/',
  4. constraints: { host: 'auth.fastify.dev' },
  5. handler: function (request, reply) {
  6. reply.send('hello world from auth.fastify.dev')
  7. }
  8. })
  9. fastify.inject({
  10. method: 'GET',
  11. url: '/',
  12. headers: {
  13. 'Host': 'example.com'
  14. }
  15. }, (err, res) => {
  16. // 404 because the host doesn't match the constraint
  17. })
  18. fastify.inject({
  19. method: 'GET',
  20. url: '/',
  21. headers: {
  22. 'Host': 'auth.fastify.dev'
  23. }
  24. }, (err, res) => {
  25. // => 'hello world from auth.fastify.dev'
  26. })

RegExp host constraints can also be specified allowing constraining to hosts matching wildcard subdomains (or any other pattern):

  1. fastify.route({
  2. method: 'GET',
  3. url: '/',
  4. constraints: { host: /.*\.fastify\.dev/ }, // will match any subdomain of fastify.dev
  5. handler: function (request, reply) {
  6. reply.send('hello world from ' + request.headers.host)
  7. }
  8. })

Asynchronous Custom Constraints

Custom constraints can be provided and the constraint criteria can be fetched from another source such as database. The use of asynchronous custom constraints should be a last resort as it impacts router performance.

  1. function databaseOperation(field, done) {
  2. done(null, field)
  3. }
  4. const secret = {
  5. // strategy name for referencing in the route handler `constraints` options
  6. name: 'secret',
  7. // storage factory for storing routes in the find-my-way route tree
  8. storage: function () {
  9. let handlers = {}
  10. return {
  11. get: (type) => { return handlers[type] || null },
  12. set: (type, store) => { handlers[type] = store }
  13. }
  14. },
  15. // function to get the value of the constraint from each incoming request
  16. deriveConstraint: (req, ctx, done) => {
  17. databaseOperation(req.headers['secret'], done)
  18. },
  19. // optional flag marking if handlers without constraints can match requests that have a value for this constraint
  20. mustMatchWhenDerived: true
  21. }

⚠ Security Notice

When using with asynchronous constraint. It is highly recommend never return error inside the callback. If the error is not preventable, it is recommended to provide a custom frameworkErrors handler to deal with it. Otherwise, you route selection may break or expose sensitive information to attackers.

  1. const Fastify = require('fastify')
  2. const fastify = Fastify({
  3. frameworkErrors: function (err, res, res) {
  4. if (err instanceof Fastify.errorCodes.FST_ERR_ASYNC_CONSTRAINT) {
  5. res.code(400)
  6. return res.send("Invalid header provided")
  7. } else {
  8. res.send(err)
  9. }
  10. }
  11. })