Request

The first parameter of the handler function is Request.
Request is a core Fastify object containing the following fields:

  • query - the parsed querystring
  • body - the body
  • params - the params matching the URL
  • headers - the headers getter and setter
  • raw - the incoming HTTP request from Node core
  • req (deprecated, use .raw instead) - the incoming HTTP request from Node core
  • server - The Fastify server instance, scoped to the current encapsulation context
  • id - the request id
  • log - the logger instance of the incoming request
  • ip - the IP address of the incoming request
  • ips - an array of the IP addresses, ordered from closest to furthest, in the X-Forwarded-For header of the incoming request (only when the trustProxy option is enabled)
  • hostname - the hostname of the incoming request (derived from X-Forwarded-Host header when the trustProxy option is enabled)
  • protocol - the protocol of the incoming request (https or http)
  • method - the method of the incoming request
  • url - the url of the incoming request
  • routerMethod - the method defined for the router that is handling the request
  • routerPath - the path pattern defined for the router that is handling the request
  • is404 - true if request is being handled by 404 handler, false if it is not
  • connection - Deprecated, use socket instead. The underlying connection of the incoming request.
  • socket - the underlying connection of the incoming request
  • context - A Fastify internal object. You should not use it directly or modify it. It is usefull to access one special key:
    • context.config - The route config object.

Headers

The request.headers is a getter that return an Object with the headers of the incoming request. You can set custom headers like this:

  1. request.headers = {
  2. 'foo': 'bar',
  3. 'baz': 'qux'
  4. }

This operation will add to the request headers the new values that can be read calling request.headers.bar. Moreover, you can still access the standard request’s headers with the request.raw.headers property.

  1. fastify.post('/:params', options, function (request, reply) {
  2. console.log(request.body)
  3. console.log(request.query)
  4. console.log(request.params)
  5. console.log(request.headers)
  6. console.log(request.raw)
  7. console.log(request.server)
  8. console.log(request.id)
  9. console.log(request.ip)
  10. console.log(request.ips)
  11. console.log(request.hostname)
  12. console.log(request.protocol)
  13. console.log(request.url)
  14. console.log(request.routerMethod)
  15. console.log(request.routerPath)
  16. request.log.info('some info')
  17. })