Request

Request

The first parameter of the handler function is Request.

Request is a core Fastify object containing the following fields:

  • query - the parsed querystring, its format is specified by querystringParser
  • body - the request payload, see Content-Type Parser for details on what request payloads Fastify natively parses and how to support other content types
  • params - the params matching the URL
  • headers - the headers getter and setter
  • raw - 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)
  • host - the host of the incoming request (derived from X-Forwarded-Host header when the trustProxy option is enabled). For HTTP/2 compatibility it returns :authority if no host header exists.
  • hostname - the host of the incoming request without the port
  • port - the port that the server is listening on
  • protocol - the protocol of the incoming request (https or http)
  • method - the method of the incoming request
  • url - the URL of the incoming request
  • originalUrl - similar to url, this allows you to access the original url in case of internal re-routing
  • is404 - true if request is being handled by 404 handler, false if it is not
  • socket - the underlying connection of the incoming request
  • context - Deprecated, use request.routeOptions.config instead. A Fastify internal object. You should not use it directly or modify it. It is useful to access one special key:
    • context.config - The route config object.
  • routeOptions - The route option object
    • bodyLimit - either server limit or route limit
    • config - the config object for this route
    • method - the http method for the route
    • url - the path of the URL to match this route
    • handler - the handler for this route
    • attachValidation - attach validationError to request (if there is a schema defined)
    • logLevel - log level defined for this route
    • schema - the JSON schemas definition for this route
    • version - a semver compatible string that defines the version of the endpoint
    • exposeHeadRoute - creates a sibling HEAD route for any GET routes
    • prefixTrailingSlash - string used to determine how to handle passing / as a route with a prefix.
  • .getValidationFunction(schema | httpPart) - Returns a validation function for the specified schema or http part, if any of either are set or cached.
  • .compileValidationSchema(schema, [httpPart]) - Compiles the specified schema and returns a validation function using the default (or customized) ValidationCompiler. The optional httpPart is forwarded to the ValidationCompiler if provided, defaults to null.
  • .validateInput(data, schema | httpPart, [httpPart]) - Validates the specified input by using the specified schema and returns the serialized payload. If the optional httpPart is provided, the function will use the serializer function given for that HTTP Status Code. Defaults to null.

Headers

The request.headers is a getter that returns 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.

Note: For performance reason on not found route, you may see that we will add an extra property Symbol('fastify.RequestAcceptVersion') on the headers.

  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.host)
  12. console.log(request.hostname)
  13. console.log(request.port)
  14. console.log(request.protocol)
  15. console.log(request.url)
  16. console.log(request.routeOptions.method)
  17. console.log(request.routeOptions.bodyLimit)
  18. console.log(request.routeOptions.method)
  19. console.log(request.routeOptions.url)
  20. console.log(request.routeOptions.attachValidation)
  21. console.log(request.routeOptions.logLevel)
  22. console.log(request.routeOptions.version)
  23. console.log(request.routeOptions.exposeHeadRoute)
  24. console.log(request.routeOptions.prefixTrailingSlash)
  25. console.log(request.routeOptions.logLevel)
  26. request.log.info('some info')
  27. })

.getValidationFunction(schema | httpPart)

By calling this function using a provided schema or httpPart, it will return a validation function that can be used to validate diverse inputs. It returns undefined if no serialization function was found using either of the provided inputs.

This function has property errors. Errors encountered during the last validation are assigned to errors

  1. const validate = request
  2. .getValidationFunction({
  3. type: 'object',
  4. properties: {
  5. foo: {
  6. type: 'string'
  7. }
  8. }
  9. })
  10. console.log(validate({ foo: 'bar' })) // true
  11. console.log(validate.errors) // null
  12. // or
  13. const validate = request
  14. .getValidationFunction('body')
  15. console.log(validate({ foo: 0.5 })) // false
  16. console.log(validate.errors) // validation errors

See .compileValidationSchema(schema, [httpStatus]) for more information on how to compile validation function.

.compileValidationSchema(schema, [httpPart])

This function will compile a validation schema and return a function that can be used to validate data. The function returned (a.k.a. validation function) is compiled by using the provided SchemaController#ValidationCompiler. A WeakMap is used to cached this, reducing compilation calls.

The optional parameter httpPart, if provided, is forwarded directly the ValidationCompiler, so it can be used to compile the validation function if a custom ValidationCompiler is provided for the route.

This function has property errors. Errors encountered during the last validation are assigned to errors

  1. const validate = request
  2. .compileValidationSchema({
  3. type: 'object',
  4. properties: {
  5. foo: {
  6. type: 'string'
  7. }
  8. }
  9. })
  10. console.log(validate({ foo: 'bar' })) // true
  11. console.log(validate.errors) // null
  12. // or
  13. const validate = request
  14. .compileValidationSchema({
  15. type: 'object',
  16. properties: {
  17. foo: {
  18. type: 'string'
  19. }
  20. }
  21. }, 200)
  22. console.log(validate({ hello: 'world' })) // false
  23. console.log(validate.errors) // validation errors

Note that you should be careful when using this function, as it will cache the compiled validation functions based on the schema provided. If the schemas provided are mutated or changed, the validation functions will not detect that the schema has been altered and for instance it will reuse the previously compiled validation function, as the cache is based on the reference of the schema (Object) previously provided.

If there is a need to change the properties of a schema, always opt to create a totally new schema (object), otherwise the implementation will not benefit from the cache mechanism.

Using the following schema as an example:

  1. const schema1 = {
  2. type: 'object',
  3. properties: {
  4. foo: {
  5. type: 'string'
  6. }
  7. }
  8. }

Not

  1. const validate = request.compileValidationSchema(schema1)
  2. // Later on...
  3. schema1.properties.foo.type. = 'integer'
  4. const newValidate = request.compileValidationSchema(schema1)
  5. console.log(newValidate === validate) // true

Instead

  1. const validate = request.compileValidationSchema(schema1)
  2. // Later on...
  3. const newSchema = Object.assign({}, schema1)
  4. newSchema.properties.foo.type = 'integer'
  5. const newValidate = request.compileValidationSchema(newSchema)
  6. console.log(newValidate === validate) // false

.validateInput(data, [schema | httpStatus], [httpStatus])

This function will validate the input based on the provided schema, or HTTP part passed. If both are provided, the httpPart parameter will take precedence.

If there is not a validation function for a given schema, a new validation function will be compiled, forwarding the httpPart if provided.

  1. request
  2. .validateInput({ foo: 'bar'}, {
  3. type: 'object',
  4. properties: {
  5. foo: {
  6. type: 'string'
  7. }
  8. }
  9. }) // true
  10. // or
  11. request
  12. .validateInput({ foo: 'bar'}, {
  13. type: 'object',
  14. properties: {
  15. foo: {
  16. type: 'string'
  17. }
  18. }
  19. }, 'body') // true
  20. // or
  21. request
  22. .validateInput({ hello: 'world'}, 'query') // false

See .compileValidationSchema(schema, [httpStatus]) for more information on how to compile validation schemas.