node-fastify 5.8.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.borp.yaml +3 -0
- package/.markdownlint-cli2.yaml +22 -0
- package/.prettierignore +1 -0
- package/GOVERNANCE.md +4 -0
- package/LICENSE +21 -0
- package/PROJECT_CHARTER.md +126 -0
- package/README.md +423 -0
- package/SECURITY.md +220 -0
- package/SPONSORS.md +24 -0
- package/build/build-error-serializer.js +35 -0
- package/build/build-validation.js +169 -0
- package/build/sync-version.js +11 -0
- package/docs/Guides/Benchmarking.md +60 -0
- package/docs/Guides/Database.md +321 -0
- package/docs/Guides/Delay-Accepting-Requests.md +608 -0
- package/docs/Guides/Detecting-When-Clients-Abort.md +172 -0
- package/docs/Guides/Ecosystem.md +726 -0
- package/docs/Guides/Fluent-Schema.md +127 -0
- package/docs/Guides/Getting-Started.md +620 -0
- package/docs/Guides/Index.md +43 -0
- package/docs/Guides/Migration-Guide-V3.md +287 -0
- package/docs/Guides/Migration-Guide-V4.md +267 -0
- package/docs/Guides/Migration-Guide-V5.md +727 -0
- package/docs/Guides/Plugins-Guide.md +520 -0
- package/docs/Guides/Prototype-Poisoning.md +383 -0
- package/docs/Guides/Recommendations.md +378 -0
- package/docs/Guides/Serverless.md +604 -0
- package/docs/Guides/Style-Guide.md +246 -0
- package/docs/Guides/Testing.md +481 -0
- package/docs/Guides/Write-Plugin.md +103 -0
- package/docs/Guides/Write-Type-Provider.md +34 -0
- package/docs/Reference/ContentTypeParser.md +271 -0
- package/docs/Reference/Decorators.md +436 -0
- package/docs/Reference/Encapsulation.md +194 -0
- package/docs/Reference/Errors.md +377 -0
- package/docs/Reference/HTTP2.md +94 -0
- package/docs/Reference/Hooks.md +958 -0
- package/docs/Reference/Index.md +73 -0
- package/docs/Reference/LTS.md +86 -0
- package/docs/Reference/Lifecycle.md +99 -0
- package/docs/Reference/Logging.md +268 -0
- package/docs/Reference/Middleware.md +79 -0
- package/docs/Reference/Plugins.md +245 -0
- package/docs/Reference/Principles.md +73 -0
- package/docs/Reference/Reply.md +1001 -0
- package/docs/Reference/Request.md +295 -0
- package/docs/Reference/Routes.md +802 -0
- package/docs/Reference/Server.md +2389 -0
- package/docs/Reference/Type-Providers.md +256 -0
- package/docs/Reference/TypeScript.md +1729 -0
- package/docs/Reference/Validation-and-Serialization.md +1130 -0
- package/docs/Reference/Warnings.md +58 -0
- package/docs/index.md +24 -0
- package/docs/resources/encapsulation_context.drawio +1 -0
- package/docs/resources/encapsulation_context.svg +3 -0
- package/eslint.config.js +35 -0
- package/examples/asyncawait.js +38 -0
- package/examples/benchmark/body.json +3 -0
- package/examples/benchmark/hooks-benchmark-async-await.js +44 -0
- package/examples/benchmark/hooks-benchmark.js +52 -0
- package/examples/benchmark/parser.js +47 -0
- package/examples/benchmark/simple.js +30 -0
- package/examples/benchmark/webstream.js +27 -0
- package/examples/hooks.js +91 -0
- package/examples/http2.js +39 -0
- package/examples/https.js +38 -0
- package/examples/parser.js +53 -0
- package/examples/plugin.js +12 -0
- package/examples/route-prefix.js +38 -0
- package/examples/shared-schema.js +38 -0
- package/examples/simple-stream.js +20 -0
- package/examples/simple.js +32 -0
- package/examples/simple.mjs +27 -0
- package/examples/typescript-server.ts +79 -0
- package/examples/use-plugin.js +29 -0
- package/fastify.d.ts +253 -0
- package/fastify.js +985 -0
- package/integration/server.js +29 -0
- package/integration/test.sh +23 -0
- package/lib/config-validator.js +1266 -0
- package/lib/content-type-parser.js +413 -0
- package/lib/content-type.js +160 -0
- package/lib/context.js +98 -0
- package/lib/decorate.js +152 -0
- package/lib/error-handler.js +173 -0
- package/lib/error-serializer.js +134 -0
- package/lib/error-status.js +14 -0
- package/lib/errors.js +516 -0
- package/lib/four-oh-four.js +190 -0
- package/lib/handle-request.js +195 -0
- package/lib/head-route.js +45 -0
- package/lib/hooks.js +429 -0
- package/lib/initial-config-validation.js +37 -0
- package/lib/logger-factory.js +136 -0
- package/lib/logger-pino.js +68 -0
- package/lib/noop-set.js +10 -0
- package/lib/plugin-override.js +90 -0
- package/lib/plugin-utils.js +169 -0
- package/lib/promise.js +23 -0
- package/lib/reply.js +1030 -0
- package/lib/req-id-gen-factory.js +52 -0
- package/lib/request.js +391 -0
- package/lib/route.js +686 -0
- package/lib/schema-controller.js +164 -0
- package/lib/schemas.js +207 -0
- package/lib/server.js +441 -0
- package/lib/symbols.js +71 -0
- package/lib/validation.js +280 -0
- package/lib/warnings.js +57 -0
- package/lib/wrap-thenable.js +84 -0
- package/package.json +225 -0
- package/scripts/validate-ecosystem-links.js +179 -0
- package/test/404s.test.js +2035 -0
- package/test/500s.test.js +422 -0
- package/test/allow-unsafe-regex.test.js +92 -0
- package/test/als.test.js +65 -0
- package/test/async-await.test.js +705 -0
- package/test/async-dispose.test.js +20 -0
- package/test/async_hooks.test.js +52 -0
- package/test/body-limit.test.js +224 -0
- package/test/buffer.test.js +74 -0
- package/test/build/error-serializer.test.js +36 -0
- package/test/build/version.test.js +14 -0
- package/test/build-certificate.js +109 -0
- package/test/bundler/README.md +29 -0
- package/test/bundler/esbuild/bundler-test.js +32 -0
- package/test/bundler/esbuild/package.json +10 -0
- package/test/bundler/esbuild/src/fail-plugin-version.js +14 -0
- package/test/bundler/esbuild/src/index.js +9 -0
- package/test/bundler/webpack/bundler-test.js +32 -0
- package/test/bundler/webpack/package.json +11 -0
- package/test/bundler/webpack/src/fail-plugin-version.js +14 -0
- package/test/bundler/webpack/src/index.js +9 -0
- package/test/bundler/webpack/webpack.config.js +15 -0
- package/test/case-insensitive.test.js +102 -0
- package/test/chainable.test.js +40 -0
- package/test/child-logger-factory.test.js +128 -0
- package/test/client-timeout.test.js +38 -0
- package/test/close-pipelining.test.js +78 -0
- package/test/close.test.js +706 -0
- package/test/conditional-pino.test.js +47 -0
- package/test/connection-timeout.test.js +42 -0
- package/test/constrained-routes.test.js +1138 -0
- package/test/content-length.test.js +174 -0
- package/test/content-parser.test.js +739 -0
- package/test/content-type.test.js +181 -0
- package/test/context-config.test.js +164 -0
- package/test/custom-http-server.test.js +118 -0
- package/test/custom-parser-async.test.js +59 -0
- package/test/custom-parser.0.test.js +701 -0
- package/test/custom-parser.1.test.js +266 -0
- package/test/custom-parser.2.test.js +91 -0
- package/test/custom-parser.3.test.js +208 -0
- package/test/custom-parser.4.test.js +218 -0
- package/test/custom-parser.5.test.js +130 -0
- package/test/custom-querystring-parser.test.js +129 -0
- package/test/decorator.test.js +1330 -0
- package/test/delete.test.js +344 -0
- package/test/diagnostics-channel/404.test.js +49 -0
- package/test/diagnostics-channel/async-delay-request.test.js +65 -0
- package/test/diagnostics-channel/async-request.test.js +64 -0
- package/test/diagnostics-channel/error-before-handler.test.js +35 -0
- package/test/diagnostics-channel/error-request.test.js +53 -0
- package/test/diagnostics-channel/error-status.test.js +123 -0
- package/test/diagnostics-channel/init.test.js +50 -0
- package/test/diagnostics-channel/sync-delay-request.test.js +49 -0
- package/test/diagnostics-channel/sync-request-reply.test.js +51 -0
- package/test/diagnostics-channel/sync-request.test.js +54 -0
- package/test/encapsulated-child-logger-factory.test.js +69 -0
- package/test/encapsulated-error-handler.test.js +237 -0
- package/test/esm/errorCodes.test.mjs +10 -0
- package/test/esm/esm.test.mjs +13 -0
- package/test/esm/index.test.js +8 -0
- package/test/esm/named-exports.mjs +14 -0
- package/test/esm/other.mjs +8 -0
- package/test/esm/plugin.mjs +8 -0
- package/test/fastify-instance.test.js +300 -0
- package/test/find-route.test.js +152 -0
- package/test/fluent-schema.test.js +209 -0
- package/test/genReqId.test.js +426 -0
- package/test/handler-context.test.js +45 -0
- package/test/handler-timeout.test.js +367 -0
- package/test/has-route.test.js +88 -0
- package/test/header-overflow.test.js +55 -0
- package/test/helper.js +496 -0
- package/test/hooks-async.test.js +1099 -0
- package/test/hooks.on-listen.test.js +1162 -0
- package/test/hooks.on-ready.test.js +421 -0
- package/test/hooks.test.js +3578 -0
- package/test/http-methods/copy.test.js +35 -0
- package/test/http-methods/custom-http-methods.test.js +114 -0
- package/test/http-methods/get.test.js +412 -0
- package/test/http-methods/head.test.js +263 -0
- package/test/http-methods/lock.test.js +108 -0
- package/test/http-methods/mkcalendar.test.js +143 -0
- package/test/http-methods/mkcol.test.js +35 -0
- package/test/http-methods/move.test.js +42 -0
- package/test/http-methods/propfind.test.js +136 -0
- package/test/http-methods/proppatch.test.js +105 -0
- package/test/http-methods/report.test.js +142 -0
- package/test/http-methods/search.test.js +233 -0
- package/test/http-methods/trace.test.js +21 -0
- package/test/http-methods/unlock.test.js +38 -0
- package/test/http2/closing.test.js +270 -0
- package/test/http2/constraint.test.js +109 -0
- package/test/http2/head.test.js +34 -0
- package/test/http2/plain.test.js +68 -0
- package/test/http2/secure-with-fallback.test.js +113 -0
- package/test/http2/secure.test.js +67 -0
- package/test/http2/unknown-http-method.test.js +34 -0
- package/test/https/custom-https-server.test.js +58 -0
- package/test/https/https.test.js +136 -0
- package/test/imports.test.js +17 -0
- package/test/inject.test.js +502 -0
- package/test/input-validation.js +335 -0
- package/test/internals/all.test.js +38 -0
- package/test/internals/content-type-parser.test.js +111 -0
- package/test/internals/context.test.js +31 -0
- package/test/internals/decorator.test.js +156 -0
- package/test/internals/errors.test.js +982 -0
- package/test/internals/handle-request.test.js +270 -0
- package/test/internals/hook-runner.test.js +449 -0
- package/test/internals/hooks.test.js +96 -0
- package/test/internals/initial-config.test.js +383 -0
- package/test/internals/logger.test.js +163 -0
- package/test/internals/plugin.test.js +170 -0
- package/test/internals/promise.test.js +63 -0
- package/test/internals/reply-serialize.test.js +714 -0
- package/test/internals/reply.test.js +1920 -0
- package/test/internals/req-id-gen-factory.test.js +133 -0
- package/test/internals/request-validate.test.js +1402 -0
- package/test/internals/request.test.js +506 -0
- package/test/internals/schema-controller-perf.test.js +40 -0
- package/test/internals/server.test.js +91 -0
- package/test/internals/validation.test.js +352 -0
- package/test/issue-4959.test.js +118 -0
- package/test/keep-alive-timeout.test.js +42 -0
- package/test/listen.1.test.js +154 -0
- package/test/listen.2.test.js +113 -0
- package/test/listen.3.test.js +83 -0
- package/test/listen.4.test.js +168 -0
- package/test/listen.5.test.js +122 -0
- package/test/logger/instantiation.test.js +341 -0
- package/test/logger/logger-test-utils.js +47 -0
- package/test/logger/logging.test.js +460 -0
- package/test/logger/options.test.js +579 -0
- package/test/logger/request.test.js +292 -0
- package/test/logger/response.test.js +183 -0
- package/test/logger/tap-parallel-not-ok +0 -0
- package/test/max-requests-per-socket.test.js +113 -0
- package/test/middleware.test.js +37 -0
- package/test/noop-set.test.js +19 -0
- package/test/nullable-validation.test.js +187 -0
- package/test/options.error-handler.test.js +5 -0
- package/test/options.test.js +5 -0
- package/test/output-validation.test.js +140 -0
- package/test/patch.error-handler.test.js +5 -0
- package/test/patch.test.js +5 -0
- package/test/plugin.1.test.js +230 -0
- package/test/plugin.2.test.js +314 -0
- package/test/plugin.3.test.js +287 -0
- package/test/plugin.4.test.js +504 -0
- package/test/plugin.helper.js +8 -0
- package/test/plugin.name.display.js +10 -0
- package/test/post-empty-body.test.js +38 -0
- package/test/pretty-print.test.js +366 -0
- package/test/promises.test.js +125 -0
- package/test/proto-poisoning.test.js +145 -0
- package/test/put.error-handler.test.js +5 -0
- package/test/put.test.js +5 -0
- package/test/register.test.js +184 -0
- package/test/reply-code.test.js +148 -0
- package/test/reply-early-hints.test.js +100 -0
- package/test/reply-error.test.js +815 -0
- package/test/reply-trailers.test.js +445 -0
- package/test/reply-web-stream-locked.test.js +37 -0
- package/test/request-error.test.js +624 -0
- package/test/request-header-host.test.js +339 -0
- package/test/request-id.test.js +118 -0
- package/test/request-timeout.test.js +53 -0
- package/test/route-hooks.test.js +635 -0
- package/test/route-prefix.test.js +904 -0
- package/test/route-shorthand.test.js +48 -0
- package/test/route.1.test.js +259 -0
- package/test/route.2.test.js +100 -0
- package/test/route.3.test.js +213 -0
- package/test/route.4.test.js +127 -0
- package/test/route.5.test.js +211 -0
- package/test/route.6.test.js +306 -0
- package/test/route.7.test.js +406 -0
- package/test/route.8.test.js +225 -0
- package/test/router-options.test.js +1108 -0
- package/test/same-shape.test.js +124 -0
- package/test/schema-examples.test.js +661 -0
- package/test/schema-feature.test.js +2198 -0
- package/test/schema-serialization.test.js +1171 -0
- package/test/schema-special-usage.test.js +1348 -0
- package/test/schema-validation.test.js +1572 -0
- package/test/scripts/validate-ecosystem-links.test.js +339 -0
- package/test/serialize-response.test.js +186 -0
- package/test/server.test.js +347 -0
- package/test/set-error-handler.test.js +69 -0
- package/test/skip-reply-send.test.js +317 -0
- package/test/stream-serializers.test.js +40 -0
- package/test/stream.1.test.js +94 -0
- package/test/stream.2.test.js +129 -0
- package/test/stream.3.test.js +198 -0
- package/test/stream.4.test.js +176 -0
- package/test/stream.5.test.js +188 -0
- package/test/sync-routes.test.js +32 -0
- package/test/throw.test.js +359 -0
- package/test/toolkit.js +63 -0
- package/test/trust-proxy.test.js +162 -0
- package/test/type-provider.test.js +22 -0
- package/test/types/content-type-parser.test-d.ts +72 -0
- package/test/types/decorate-request-reply.test-d.ts +18 -0
- package/test/types/dummy-plugin.ts +9 -0
- package/test/types/errors.test-d.ts +90 -0
- package/test/types/fastify.test-d.ts +352 -0
- package/test/types/hooks.test-d.ts +550 -0
- package/test/types/import.ts +2 -0
- package/test/types/instance.test-d.ts +588 -0
- package/test/types/logger.test-d.ts +277 -0
- package/test/types/plugin.test-d.ts +97 -0
- package/test/types/register.test-d.ts +237 -0
- package/test/types/reply.test-d.ts +254 -0
- package/test/types/request.test-d.ts +188 -0
- package/test/types/route.test-d.ts +553 -0
- package/test/types/schema.test-d.ts +135 -0
- package/test/types/serverFactory.test-d.ts +37 -0
- package/test/types/type-provider.test-d.ts +1213 -0
- package/test/types/using.test-d.ts +17 -0
- package/test/upgrade.test.js +52 -0
- package/test/url-rewriting.test.js +122 -0
- package/test/use-semicolon-delimiter.test.js +168 -0
- package/test/validation-error-handling.test.js +900 -0
- package/test/versioned-routes.test.js +603 -0
- package/test/web-api.test.js +616 -0
- package/test/wrap-thenable.test.js +30 -0
- package/types/content-type-parser.d.ts +75 -0
- package/types/context.d.ts +22 -0
- package/types/errors.d.ts +92 -0
- package/types/hooks.d.ts +875 -0
- package/types/instance.d.ts +609 -0
- package/types/logger.d.ts +107 -0
- package/types/plugin.d.ts +44 -0
- package/types/register.d.ts +42 -0
- package/types/reply.d.ts +81 -0
- package/types/request.d.ts +95 -0
- package/types/route.d.ts +199 -0
- package/types/schema.d.ts +61 -0
- package/types/server-factory.d.ts +19 -0
- package/types/type-provider.d.ts +130 -0
- package/types/utils.d.ts +98 -0
|
@@ -0,0 +1,1001 @@
|
|
|
1
|
+
<h1 align="center">Fastify</h1>
|
|
2
|
+
|
|
3
|
+
## Reply
|
|
4
|
+
- [Reply](#reply)
|
|
5
|
+
- [Introduction](#introduction)
|
|
6
|
+
- [.code(statusCode)](#codestatuscode)
|
|
7
|
+
- [.elapsedTime](#elapsedtime)
|
|
8
|
+
- [.statusCode](#statuscode)
|
|
9
|
+
- [.server](#server)
|
|
10
|
+
- [.header(key, value)](#headerkey-value)
|
|
11
|
+
- [.headers(object)](#headersobject)
|
|
12
|
+
- [.getHeader(key)](#getheaderkey)
|
|
13
|
+
- [.getHeaders()](#getheaders)
|
|
14
|
+
- [.removeHeader(key)](#removeheaderkey)
|
|
15
|
+
- [.hasHeader(key)](#hasheaderkey)
|
|
16
|
+
- [.writeEarlyHints(hints, callback)](#writeearlyhintshints-callback)
|
|
17
|
+
- [.trailer(key, function)](#trailerkey-function)
|
|
18
|
+
- [.hasTrailer(key)](#hastrailerkey)
|
|
19
|
+
- [.removeTrailer(key)](#removetrailerkey)
|
|
20
|
+
- [.redirect(dest, [code ,])](#redirectdest--code)
|
|
21
|
+
- [.callNotFound()](#callnotfound)
|
|
22
|
+
- [.type(contentType)](#typecontenttype)
|
|
23
|
+
- [.getSerializationFunction(schema | httpStatus, [contentType])](#getserializationfunctionschema--httpstatus)
|
|
24
|
+
- [.compileSerializationSchema(schema, [httpStatus], [contentType])](#compileserializationschemaschema-httpstatus)
|
|
25
|
+
- [.serializeInput(data, [schema | httpStatus], [httpStatus], [contentType])](#serializeinputdata-schema--httpstatus-httpstatus)
|
|
26
|
+
- [.serializer(func)](#serializerfunc)
|
|
27
|
+
- [.raw](#raw)
|
|
28
|
+
- [.sent](#sent)
|
|
29
|
+
- [.hijack()](#hijack)
|
|
30
|
+
- [.send(data)](#senddata)
|
|
31
|
+
- [Objects](#objects)
|
|
32
|
+
- [Strings](#strings)
|
|
33
|
+
- [Streams](#streams)
|
|
34
|
+
- [Buffers](#buffers)
|
|
35
|
+
- [TypedArrays](#typedarrays)
|
|
36
|
+
- [ReadableStream](#readablestream)
|
|
37
|
+
- [Response](#response)
|
|
38
|
+
- [Errors](#errors)
|
|
39
|
+
- [Type of the final payload](#type-of-the-final-payload)
|
|
40
|
+
- [Async-Await and Promises](#async-await-and-promises)
|
|
41
|
+
- [.then(fulfilled, rejected)](#thenfulfilled-rejected)
|
|
42
|
+
|
|
43
|
+
### Introduction
|
|
44
|
+
<a id="introduction"></a>
|
|
45
|
+
|
|
46
|
+
The second parameter of the handler function is `Reply`. Reply is a core Fastify
|
|
47
|
+
object that exposes the following functions and properties:
|
|
48
|
+
|
|
49
|
+
- `.code(statusCode)` - Sets the status code.
|
|
50
|
+
- `.status(statusCode)` - An alias for `.code(statusCode)`.
|
|
51
|
+
- `.statusCode` - Read and set the HTTP status code.
|
|
52
|
+
- `.elapsedTime` - Returns the amount of time passed
|
|
53
|
+
since the request was received by Fastify.
|
|
54
|
+
- `.server` - A reference to the fastify instance object.
|
|
55
|
+
- `.header(name, value)` - Sets a response header.
|
|
56
|
+
- `.headers(object)` - Sets all the keys of the object as response headers.
|
|
57
|
+
- `.getHeader(name)` - Retrieve value of already set header.
|
|
58
|
+
- `.getHeaders()` - Gets a shallow copy of all current response headers.
|
|
59
|
+
- `.removeHeader(key)` - Remove the value of a previously set header.
|
|
60
|
+
- `.hasHeader(name)` - Determine if a header has been set.
|
|
61
|
+
- `.writeEarlyHints(hints, callback)` - Sends early hints to the user
|
|
62
|
+
while the response is being prepared.
|
|
63
|
+
- `.trailer(key, function)` - Sets a response trailer.
|
|
64
|
+
- `.hasTrailer(key)` - Determine if a trailer has been set.
|
|
65
|
+
- `.removeTrailer(key)` - Remove the value of a previously set trailer.
|
|
66
|
+
- `.type(value)` - Sets the header `Content-Type`.
|
|
67
|
+
- `.redirect(dest, [code,])` - Redirect to the specified URL, the status code is
|
|
68
|
+
optional (defaults to `302`).
|
|
69
|
+
- `.callNotFound()` - Invokes the custom not found handler.
|
|
70
|
+
- `.serialize(payload)` - Serializes the specified payload using the default
|
|
71
|
+
JSON serializer or using the custom serializer (if one is set) and returns the
|
|
72
|
+
serialized payload.
|
|
73
|
+
- `.getSerializationFunction(schema | httpStatus, [contentType])` - Returns the
|
|
74
|
+
serialization function for the specified schema or http status, if any of
|
|
75
|
+
either are set.
|
|
76
|
+
- `.compileSerializationSchema(schema, [httpStatus], [contentType])` - Compiles
|
|
77
|
+
the specified schema and returns a serialization function using the default
|
|
78
|
+
(or customized) `SerializerCompiler`. The optional `httpStatus` is forwarded
|
|
79
|
+
to the `SerializerCompiler` if provided, default to `undefined`.
|
|
80
|
+
- `.serializeInput(data, schema, [,httpStatus], [contentType])` - Serializes
|
|
81
|
+
the specified data using the specified schema and returns the serialized payload.
|
|
82
|
+
If the optional `httpStatus`, and `contentType` are provided, the function
|
|
83
|
+
will use the serializer function given for that specific content type and
|
|
84
|
+
HTTP Status Code. Default to `undefined`.
|
|
85
|
+
- `.serializer(function)` - Sets a custom serializer for the payload.
|
|
86
|
+
- `.send(payload)` - Sends the payload to the user, could be a plain text, a
|
|
87
|
+
buffer, JSON, stream, or an Error object.
|
|
88
|
+
- `.sent` - A boolean value that you can use if you need to know if `send` has
|
|
89
|
+
already been called.
|
|
90
|
+
- `.hijack()` - interrupt the normal request lifecycle.
|
|
91
|
+
- `.raw` - The
|
|
92
|
+
[`http.ServerResponse`](https://nodejs.org/dist/latest-v20.x/docs/api/http.html#http_class_http_serverresponse)
|
|
93
|
+
from Node core.
|
|
94
|
+
- `.log` - The logger instance of the incoming request.
|
|
95
|
+
- `.request` - The incoming request.
|
|
96
|
+
|
|
97
|
+
```js
|
|
98
|
+
fastify.get('/', options, function (request, reply) {
|
|
99
|
+
// Your code
|
|
100
|
+
reply
|
|
101
|
+
.code(200)
|
|
102
|
+
.header('Content-Type', 'application/json; charset=utf-8')
|
|
103
|
+
.send({ hello: 'world' })
|
|
104
|
+
})
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### .code(statusCode)
|
|
108
|
+
<a id="code"></a>
|
|
109
|
+
|
|
110
|
+
If not set via `reply.code`, the resulting `statusCode` will be `200`.
|
|
111
|
+
|
|
112
|
+
### .elapsedTime
|
|
113
|
+
<a id="elapsedTime"></a>
|
|
114
|
+
|
|
115
|
+
Invokes the custom response time getter to calculate the amount of time passed
|
|
116
|
+
since the request was received by Fastify.
|
|
117
|
+
|
|
118
|
+
```js
|
|
119
|
+
const milliseconds = reply.elapsedTime
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
### .statusCode
|
|
123
|
+
<a id="statusCode"></a>
|
|
124
|
+
|
|
125
|
+
This property reads and sets the HTTP status code. It is an alias for
|
|
126
|
+
`reply.code()` when used as a setter.
|
|
127
|
+
```js
|
|
128
|
+
if (reply.statusCode >= 299) {
|
|
129
|
+
reply.statusCode = 500
|
|
130
|
+
}
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
### .server
|
|
134
|
+
<a id="server"></a>
|
|
135
|
+
|
|
136
|
+
The Fastify server instance, scoped to the current [encapsulation
|
|
137
|
+
context](./Encapsulation.md).
|
|
138
|
+
|
|
139
|
+
```js
|
|
140
|
+
fastify.decorate('util', function util () {
|
|
141
|
+
return 'foo'
|
|
142
|
+
})
|
|
143
|
+
|
|
144
|
+
fastify.get('/', async function (req, rep) {
|
|
145
|
+
return rep.server.util() // foo
|
|
146
|
+
})
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
### .header(key, value)
|
|
150
|
+
<a id="header"></a>
|
|
151
|
+
|
|
152
|
+
Sets a response header. If the value is omitted or undefined, it is coerced to
|
|
153
|
+
`''`.
|
|
154
|
+
|
|
155
|
+
> ℹ️ Note:
|
|
156
|
+
> The header's value must be properly encoded using
|
|
157
|
+
> [`encodeURI`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI)
|
|
158
|
+
> or similar modules such as
|
|
159
|
+
> [`encodeurl`](https://www.npmjs.com/package/encodeurl). Invalid characters
|
|
160
|
+
> will result in a 500 `TypeError` response.
|
|
161
|
+
|
|
162
|
+
For more information, see
|
|
163
|
+
[`http.ServerResponse#setHeader`](https://nodejs.org/dist/latest-v20.x/docs/api/http.html#http_response_setheader_name_value).
|
|
164
|
+
|
|
165
|
+
- ### set-cookie
|
|
166
|
+
<a id="set-cookie"></a>
|
|
167
|
+
|
|
168
|
+
- When sending different values as a cookie with `set-cookie` as the key,
|
|
169
|
+
every value will be sent as a cookie instead of replacing the previous
|
|
170
|
+
value.
|
|
171
|
+
|
|
172
|
+
```js
|
|
173
|
+
reply.header('set-cookie', 'foo');
|
|
174
|
+
reply.header('set-cookie', 'bar');
|
|
175
|
+
```
|
|
176
|
+
- The browser will only consider the latest reference of a key for the
|
|
177
|
+
`set-cookie` header. This is done to avoid parsing the `set-cookie` header
|
|
178
|
+
when added to a reply and speeds up the serialization of the reply.
|
|
179
|
+
|
|
180
|
+
- To reset the `set-cookie` header, you need to make an explicit call to
|
|
181
|
+
`reply.removeHeader('set-cookie')`, read more about `.removeHeader(key)`
|
|
182
|
+
[here](#removeheaderkey).
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
### .headers(object)
|
|
187
|
+
<a id="headers"></a>
|
|
188
|
+
|
|
189
|
+
Sets all the keys of the object as response headers.
|
|
190
|
+
[`.header`](#headerkey-value) will be called under the hood.
|
|
191
|
+
```js
|
|
192
|
+
reply.headers({
|
|
193
|
+
'x-foo': 'foo',
|
|
194
|
+
'x-bar': 'bar'
|
|
195
|
+
})
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
### .getHeader(key)
|
|
199
|
+
<a id="getHeader"></a>
|
|
200
|
+
|
|
201
|
+
Retrieves the value of a previously set header.
|
|
202
|
+
```js
|
|
203
|
+
reply.header('x-foo', 'foo') // setHeader: key, value
|
|
204
|
+
reply.getHeader('x-foo') // 'foo'
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
### .getHeaders()
|
|
208
|
+
<a id="getHeaders"></a>
|
|
209
|
+
|
|
210
|
+
Gets a shallow copy of all current response headers, including those set via the
|
|
211
|
+
raw `http.ServerResponse`. Note that headers set via Fastify take precedence
|
|
212
|
+
over those set via `http.ServerResponse`.
|
|
213
|
+
|
|
214
|
+
```js
|
|
215
|
+
reply.header('x-foo', 'foo')
|
|
216
|
+
reply.header('x-bar', 'bar')
|
|
217
|
+
reply.raw.setHeader('x-foo', 'foo2')
|
|
218
|
+
reply.getHeaders() // { 'x-foo': 'foo', 'x-bar': 'bar' }
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
### .removeHeader(key)
|
|
222
|
+
<a id="getHeader"></a>
|
|
223
|
+
|
|
224
|
+
Remove the value of a previously set header.
|
|
225
|
+
```js
|
|
226
|
+
reply.header('x-foo', 'foo')
|
|
227
|
+
reply.removeHeader('x-foo')
|
|
228
|
+
reply.getHeader('x-foo') // undefined
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
### .hasHeader(key)
|
|
232
|
+
<a id="hasHeader"></a>
|
|
233
|
+
|
|
234
|
+
Returns a boolean indicating if the specified header has been set.
|
|
235
|
+
|
|
236
|
+
### .writeEarlyHints(hints, callback)
|
|
237
|
+
<a id="writeEarlyHints"></a>
|
|
238
|
+
|
|
239
|
+
Sends early hints to the client. Early hints allow the client to
|
|
240
|
+
start processing resources before the final response is sent.
|
|
241
|
+
This can improve performance by allowing the client to preload
|
|
242
|
+
or preconnect to resources while the server is still generating the response.
|
|
243
|
+
|
|
244
|
+
The hints parameter is an object containing the early hint key-value pairs.
|
|
245
|
+
|
|
246
|
+
Example:
|
|
247
|
+
|
|
248
|
+
```js
|
|
249
|
+
reply.writeEarlyHints({
|
|
250
|
+
Link: '</styles.css>; rel=preload; as=style'
|
|
251
|
+
});
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
The optional callback parameter is a function that will be called
|
|
255
|
+
once the hint is sent or if an error occurs.
|
|
256
|
+
|
|
257
|
+
### .trailer(key, function)
|
|
258
|
+
<a id="trailer"></a>
|
|
259
|
+
|
|
260
|
+
Sets a response trailer. Trailer is usually used when you need a header that
|
|
261
|
+
requires heavy resources to be sent after the `data`, for example,
|
|
262
|
+
`Server-Timing` and `Etag`. It can ensure the client receives the response data
|
|
263
|
+
as soon as possible.
|
|
264
|
+
|
|
265
|
+
> ℹ️ Note:
|
|
266
|
+
> The header `Transfer-Encoding: chunked` will be added once you use
|
|
267
|
+
> the trailer. It is a hard requirement for using trailer in Node.js.
|
|
268
|
+
|
|
269
|
+
> ℹ️ Note:
|
|
270
|
+
> Any error passed to `done` callback will be ignored. If you are interested
|
|
271
|
+
> in the error, you can turn on `debug` level logging.
|
|
272
|
+
|
|
273
|
+
```js
|
|
274
|
+
reply.trailer('server-timing', function() {
|
|
275
|
+
return 'db;dur=53, app;dur=47.2'
|
|
276
|
+
})
|
|
277
|
+
|
|
278
|
+
const { createHash } = require('node:crypto')
|
|
279
|
+
// trailer function also receive two argument
|
|
280
|
+
// @param {object} reply fastify reply
|
|
281
|
+
// @param {string|Buffer|null} payload payload that already sent, note that it will be null when stream is sent
|
|
282
|
+
// @param {function} done callback to set trailer value
|
|
283
|
+
reply.trailer('content-md5', function(reply, payload, done) {
|
|
284
|
+
const hash = createHash('md5')
|
|
285
|
+
hash.update(payload)
|
|
286
|
+
done(null, hash.digest('hex'))
|
|
287
|
+
})
|
|
288
|
+
|
|
289
|
+
// when you prefer async-await
|
|
290
|
+
reply.trailer('content-md5', async function(reply, payload) {
|
|
291
|
+
const hash = createHash('md5')
|
|
292
|
+
hash.update(payload)
|
|
293
|
+
return hash.digest('hex')
|
|
294
|
+
})
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
### .hasTrailer(key)
|
|
298
|
+
<a id="hasTrailer"></a>
|
|
299
|
+
|
|
300
|
+
Returns a boolean indicating if the specified trailer has been set.
|
|
301
|
+
|
|
302
|
+
### .removeTrailer(key)
|
|
303
|
+
<a id="removeTrailer"></a>
|
|
304
|
+
|
|
305
|
+
Remove the value of a previously set trailer.
|
|
306
|
+
```js
|
|
307
|
+
reply.trailer('server-timing', function() {
|
|
308
|
+
return 'db;dur=53, app;dur=47.2'
|
|
309
|
+
})
|
|
310
|
+
reply.removeTrailer('server-timing')
|
|
311
|
+
reply.getTrailer('server-timing') // undefined
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
### .redirect(dest, [code ,])
|
|
316
|
+
<a id="redirect"></a>
|
|
317
|
+
|
|
318
|
+
Redirects a request to the specified URL, the status code is optional, default
|
|
319
|
+
to `302` (if status code is not already set by calling `code`).
|
|
320
|
+
|
|
321
|
+
> ℹ️ Note:
|
|
322
|
+
> The input URL must be properly encoded using
|
|
323
|
+
> [`encodeURI`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI)
|
|
324
|
+
> or similar modules such as
|
|
325
|
+
> [`encodeurl`](https://www.npmjs.com/package/encodeurl). Invalid URLs will
|
|
326
|
+
> result in a 500 `TypeError` response.
|
|
327
|
+
|
|
328
|
+
Example (no `reply.code()` call) sets status code to `302` and redirects to
|
|
329
|
+
`/home`
|
|
330
|
+
```js
|
|
331
|
+
reply.redirect('/home')
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
Example (no `reply.code()` call) sets status code to `303` and redirects to
|
|
335
|
+
`/home`
|
|
336
|
+
```js
|
|
337
|
+
reply.redirect('/home', 303)
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
Example (`reply.code()` call) sets status code to `303` and redirects to `/home`
|
|
341
|
+
```js
|
|
342
|
+
reply.code(303).redirect('/home')
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
Example (`reply.code()` call) sets status code to `302` and redirects to `/home`
|
|
346
|
+
```js
|
|
347
|
+
reply.code(303).redirect('/home', 302)
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
### .callNotFound()
|
|
351
|
+
<a id="call-not-found"></a>
|
|
352
|
+
|
|
353
|
+
Invokes the custom not found handler. Note that it will only call `preHandler`
|
|
354
|
+
hook specified in [`setNotFoundHandler`](./Server.md#set-not-found-handler).
|
|
355
|
+
|
|
356
|
+
```js
|
|
357
|
+
reply.callNotFound()
|
|
358
|
+
```
|
|
359
|
+
|
|
360
|
+
### .type(contentType)
|
|
361
|
+
<a id="type"></a>
|
|
362
|
+
|
|
363
|
+
Sets the content type for the response. This is a shortcut for
|
|
364
|
+
`reply.header('Content-Type', 'the/type')`.
|
|
365
|
+
|
|
366
|
+
```js
|
|
367
|
+
reply.type('text/html')
|
|
368
|
+
```
|
|
369
|
+
If the `Content-Type` has a JSON subtype, and the charset parameter is not set,
|
|
370
|
+
`utf-8` will be used as the charset by default. For other content types, the
|
|
371
|
+
charset must be set explicitly.
|
|
372
|
+
|
|
373
|
+
### .getSerializationFunction(schema | httpStatus, [contentType])
|
|
374
|
+
<a id="getserializationfunction"></a>
|
|
375
|
+
|
|
376
|
+
By calling this function using a provided `schema` or `httpStatus`,
|
|
377
|
+
and the optional `contentType`, it will return a `serialization` function
|
|
378
|
+
that can be used to serialize diverse inputs. It returns `undefined` if no
|
|
379
|
+
serialization function was found using either of the provided inputs.
|
|
380
|
+
|
|
381
|
+
This heavily depends of the `schema#responses` attached to the route, or
|
|
382
|
+
the serialization functions compiled by using `compileSerializationSchema`.
|
|
383
|
+
|
|
384
|
+
```js
|
|
385
|
+
const serialize = reply
|
|
386
|
+
.getSerializationFunction({
|
|
387
|
+
type: 'object',
|
|
388
|
+
properties: {
|
|
389
|
+
foo: {
|
|
390
|
+
type: 'string'
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
})
|
|
394
|
+
serialize({ foo: 'bar' }) // '{"foo":"bar"}'
|
|
395
|
+
|
|
396
|
+
// or
|
|
397
|
+
|
|
398
|
+
const serialize = reply
|
|
399
|
+
.getSerializationFunction(200)
|
|
400
|
+
serialize({ foo: 'bar' }) // '{"foo":"bar"}'
|
|
401
|
+
|
|
402
|
+
// or
|
|
403
|
+
|
|
404
|
+
const serialize = reply
|
|
405
|
+
.getSerializationFunction(200, 'application/json')
|
|
406
|
+
serialize({ foo: 'bar' }) // '{"foo":"bar"}'
|
|
407
|
+
```
|
|
408
|
+
|
|
409
|
+
See [.compileSerializationSchema(schema, [httpStatus], [contentType])](#compileserializationschema)
|
|
410
|
+
for more information on how to compile serialization schemas.
|
|
411
|
+
|
|
412
|
+
### .compileSerializationSchema(schema, [httpStatus], [contentType])
|
|
413
|
+
<a id="compileserializationschema"></a>
|
|
414
|
+
|
|
415
|
+
This function will compile a serialization schema and
|
|
416
|
+
return a function that can be used to serialize data.
|
|
417
|
+
The function returned (a.k.a. _serialization function_) returned is compiled
|
|
418
|
+
by using the provided `SerializerCompiler`. Also this is cached by using
|
|
419
|
+
a `WeakMap` for reducing compilation calls.
|
|
420
|
+
|
|
421
|
+
The optional parameters `httpStatus` and `contentType`, if provided,
|
|
422
|
+
are forwarded directly to the `SerializerCompiler`, so it can be used
|
|
423
|
+
to compile the serialization function if a custom `SerializerCompiler` is used.
|
|
424
|
+
|
|
425
|
+
This heavily depends of the `schema#responses` attached to the route, or
|
|
426
|
+
the serialization functions compiled by using `compileSerializationSchema`.
|
|
427
|
+
|
|
428
|
+
```js
|
|
429
|
+
const serialize = reply
|
|
430
|
+
.compileSerializationSchema({
|
|
431
|
+
type: 'object',
|
|
432
|
+
properties: {
|
|
433
|
+
foo: {
|
|
434
|
+
type: 'string'
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
})
|
|
438
|
+
serialize({ foo: 'bar' }) // '{"foo":"bar"}'
|
|
439
|
+
|
|
440
|
+
// or
|
|
441
|
+
|
|
442
|
+
const serialize = reply
|
|
443
|
+
.compileSerializationSchema({
|
|
444
|
+
type: 'object',
|
|
445
|
+
properties: {
|
|
446
|
+
foo: {
|
|
447
|
+
type: 'string'
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
}, 200)
|
|
451
|
+
serialize({ foo: 'bar' }) // '{"foo":"bar"}'
|
|
452
|
+
|
|
453
|
+
// or
|
|
454
|
+
|
|
455
|
+
const serialize = reply
|
|
456
|
+
.compileSerializationSchema({
|
|
457
|
+
'3xx': {
|
|
458
|
+
content: {
|
|
459
|
+
'application/json': {
|
|
460
|
+
schema: {
|
|
461
|
+
name: { type: 'string' },
|
|
462
|
+
phone: { type: 'number' }
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
}, '3xx', 'application/json')
|
|
468
|
+
serialize({ name: 'Jone', phone: 201090909090 }) // '{"name":"Jone", "phone":201090909090}'
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
Note that you should be careful when using this function, as it will cache
|
|
472
|
+
the compiled serialization functions based on the schema provided. If the
|
|
473
|
+
schemas provided is mutated or changed, the serialization functions will not
|
|
474
|
+
detect that the schema has been altered and for instance it will reuse the
|
|
475
|
+
previously compiled serialization function based on the reference of the schema
|
|
476
|
+
previously provided.
|
|
477
|
+
|
|
478
|
+
If there's a need to change the properties of a schema, always opt to create
|
|
479
|
+
a totally new object, otherwise the implementation won't benefit from the cache
|
|
480
|
+
mechanism.
|
|
481
|
+
|
|
482
|
+
:Using the following schema as example:
|
|
483
|
+
```js
|
|
484
|
+
const schema1 = {
|
|
485
|
+
type: 'object',
|
|
486
|
+
properties: {
|
|
487
|
+
foo: {
|
|
488
|
+
type: 'string'
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
```
|
|
493
|
+
|
|
494
|
+
*Not*
|
|
495
|
+
```js
|
|
496
|
+
const serialize = reply.compileSerializationSchema(schema1)
|
|
497
|
+
|
|
498
|
+
// Later on...
|
|
499
|
+
schema1.properties.foo.type. = 'integer'
|
|
500
|
+
const newSerialize = reply.compileSerializationSchema(schema1)
|
|
501
|
+
|
|
502
|
+
console.log(newSerialize === serialize) // true
|
|
503
|
+
```
|
|
504
|
+
|
|
505
|
+
*Instead*
|
|
506
|
+
```js
|
|
507
|
+
const serialize = reply.compileSerializationSchema(schema1)
|
|
508
|
+
|
|
509
|
+
// Later on...
|
|
510
|
+
const newSchema = Object.assign({}, schema1)
|
|
511
|
+
newSchema.properties.foo.type = 'integer'
|
|
512
|
+
|
|
513
|
+
const newSerialize = reply.compileSerializationSchema(newSchema)
|
|
514
|
+
|
|
515
|
+
console.log(newSerialize === serialize) // false
|
|
516
|
+
```
|
|
517
|
+
|
|
518
|
+
### .serializeInput(data, [schema | httpStatus], [httpStatus], [contentType])
|
|
519
|
+
<a id="serializeinput"></a>
|
|
520
|
+
|
|
521
|
+
This function will serialize the input data based on the provided schema
|
|
522
|
+
or HTTP status code. If both are provided the `httpStatus` will take precedence.
|
|
523
|
+
|
|
524
|
+
If there is not a serialization function for a given `schema` a new serialization
|
|
525
|
+
function will be compiled, forwarding the `httpStatus` and `contentType` if provided.
|
|
526
|
+
|
|
527
|
+
```js
|
|
528
|
+
reply
|
|
529
|
+
.serializeInput({ foo: 'bar'}, {
|
|
530
|
+
type: 'object',
|
|
531
|
+
properties: {
|
|
532
|
+
foo: {
|
|
533
|
+
type: 'string'
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
}) // '{"foo":"bar"}'
|
|
537
|
+
|
|
538
|
+
// or
|
|
539
|
+
|
|
540
|
+
reply
|
|
541
|
+
.serializeInput({ foo: 'bar'}, {
|
|
542
|
+
type: 'object',
|
|
543
|
+
properties: {
|
|
544
|
+
foo: {
|
|
545
|
+
type: 'string'
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
}, 200) // '{"foo":"bar"}'
|
|
549
|
+
|
|
550
|
+
// or
|
|
551
|
+
|
|
552
|
+
reply
|
|
553
|
+
.serializeInput({ foo: 'bar'}, 200) // '{"foo":"bar"}'
|
|
554
|
+
|
|
555
|
+
// or
|
|
556
|
+
|
|
557
|
+
reply
|
|
558
|
+
.serializeInput({ name: 'Jone', age: 18 }, '200', 'application/vnd.v1+json') // '{"name": "Jone", "age": 18}'
|
|
559
|
+
```
|
|
560
|
+
|
|
561
|
+
See [.compileSerializationSchema(schema, [httpStatus], [contentType])](#compileserializationschema)
|
|
562
|
+
for more information on how to compile serialization schemas.
|
|
563
|
+
|
|
564
|
+
### .serializer(func)
|
|
565
|
+
<a id="serializer"></a>
|
|
566
|
+
|
|
567
|
+
By default, `.send()` will JSON-serialize any value that is not one of `Buffer`,
|
|
568
|
+
`stream`, `string`, `undefined`, or `Error`. If you need to replace the default
|
|
569
|
+
serializer with a custom serializer for a particular request, you can do so with
|
|
570
|
+
the `.serializer()` utility. Be aware that if you are using a custom serializer,
|
|
571
|
+
you must set a custom `'Content-Type'` header.
|
|
572
|
+
|
|
573
|
+
```js
|
|
574
|
+
reply
|
|
575
|
+
.header('Content-Type', 'application/x-protobuf')
|
|
576
|
+
.serializer(protoBuf.serialize)
|
|
577
|
+
```
|
|
578
|
+
|
|
579
|
+
Note that you don't need to use this utility inside a `handler` because Buffers,
|
|
580
|
+
streams, and strings (unless a serializer is set) are considered to already be
|
|
581
|
+
serialized.
|
|
582
|
+
|
|
583
|
+
```js
|
|
584
|
+
reply
|
|
585
|
+
.header('Content-Type', 'application/x-protobuf')
|
|
586
|
+
.send(protoBuf.serialize(data))
|
|
587
|
+
```
|
|
588
|
+
|
|
589
|
+
See [`.send()`](#send) for more information on sending different types of
|
|
590
|
+
values.
|
|
591
|
+
|
|
592
|
+
### .raw
|
|
593
|
+
<a id="raw"></a>
|
|
594
|
+
|
|
595
|
+
This is the
|
|
596
|
+
[`http.ServerResponse`](https://nodejs.org/dist/latest-v20.x/docs/api/http.html#http_class_http_serverresponse)
|
|
597
|
+
from Node core. Whilst you are using the Fastify `Reply` object, the use of
|
|
598
|
+
`Reply.raw` functions is at your own risk as you are skipping all the Fastify
|
|
599
|
+
logic of handling the HTTP response. e.g.:
|
|
600
|
+
|
|
601
|
+
```js
|
|
602
|
+
app.get('/cookie-2', (req, reply) => {
|
|
603
|
+
reply.setCookie('session', 'value', { secure: false }) // this will not be used
|
|
604
|
+
|
|
605
|
+
// in this case we are using only the nodejs http server response object
|
|
606
|
+
reply.raw.writeHead(200, { 'Content-Type': 'text/plain' })
|
|
607
|
+
reply.raw.write('ok')
|
|
608
|
+
reply.raw.end()
|
|
609
|
+
})
|
|
610
|
+
```
|
|
611
|
+
Another example of the misuse of `Reply.raw` is explained in
|
|
612
|
+
[Reply](#getheaders).
|
|
613
|
+
|
|
614
|
+
### .sent
|
|
615
|
+
<a id="sent"></a>
|
|
616
|
+
|
|
617
|
+
As the name suggests, `.sent` is a property to indicate if a response has been
|
|
618
|
+
sent via `reply.send()`. It will also be `true` in case `reply.hijack()` was
|
|
619
|
+
used.
|
|
620
|
+
|
|
621
|
+
In case a route handler is defined as an async function or it returns a promise,
|
|
622
|
+
it is possible to call `reply.hijack()` to indicate that the automatic
|
|
623
|
+
invocation of `reply.send()` once the handler promise resolve should be skipped.
|
|
624
|
+
By calling `reply.hijack()`, an application claims full responsibility for the
|
|
625
|
+
low-level request and response. Moreover, hooks will not be invoked.
|
|
626
|
+
|
|
627
|
+
*Modifying the `.sent` property directly is deprecated. Please use the
|
|
628
|
+
aforementioned `.hijack()` method to achieve the same effect.*
|
|
629
|
+
|
|
630
|
+
### .hijack()
|
|
631
|
+
<a name="hijack"></a>
|
|
632
|
+
|
|
633
|
+
Sometimes you might need to halt the execution of the normal request lifecycle
|
|
634
|
+
and handle sending the response manually.
|
|
635
|
+
|
|
636
|
+
To achieve this, Fastify provides the `reply.hijack()` method that can be called
|
|
637
|
+
during the request lifecycle (At any point before `reply.send()` is called), and
|
|
638
|
+
allows you to prevent Fastify from sending the response, and from running the
|
|
639
|
+
remaining hooks (and user handler if the reply was hijacked before).
|
|
640
|
+
|
|
641
|
+
```js
|
|
642
|
+
app.get('/', (req, reply) => {
|
|
643
|
+
reply.hijack()
|
|
644
|
+
reply.raw.end('hello world')
|
|
645
|
+
|
|
646
|
+
return Promise.resolve('this will be skipped')
|
|
647
|
+
})
|
|
648
|
+
```
|
|
649
|
+
|
|
650
|
+
If `reply.raw` is used to send a response back to the user, the `onResponse`
|
|
651
|
+
hooks will still be executed.
|
|
652
|
+
|
|
653
|
+
### .send(data)
|
|
654
|
+
<a id="send"></a>
|
|
655
|
+
|
|
656
|
+
As the name suggests, `.send()` is the function that sends the payload to the
|
|
657
|
+
end user.
|
|
658
|
+
|
|
659
|
+
#### Objects
|
|
660
|
+
<a id="send-object"></a>
|
|
661
|
+
|
|
662
|
+
As noted above, if you are sending JSON objects, `send` will serialize the
|
|
663
|
+
object with
|
|
664
|
+
[fast-json-stringify](https://www.npmjs.com/package/fast-json-stringify) if you
|
|
665
|
+
set an output schema, otherwise, `JSON.stringify()` will be used.
|
|
666
|
+
```js
|
|
667
|
+
fastify.get('/json', options, function (request, reply) {
|
|
668
|
+
reply.send({ hello: 'world' })
|
|
669
|
+
})
|
|
670
|
+
```
|
|
671
|
+
|
|
672
|
+
#### Strings
|
|
673
|
+
<a id="send-string"></a>
|
|
674
|
+
|
|
675
|
+
If you pass a string to `send` without a `Content-Type`, it will be sent as
|
|
676
|
+
`text/plain; charset=utf-8`. If you set the `Content-Type` header and pass a
|
|
677
|
+
string to `send`, it will be serialized with the custom serializer if one is
|
|
678
|
+
set, otherwise, it will be sent unmodified.
|
|
679
|
+
|
|
680
|
+
> ℹ️ Note:
|
|
681
|
+
> Even when the `Content-Type` header is set to `application/json`,
|
|
682
|
+
> strings are sent unmodified by default. To serialize a string as JSON, you
|
|
683
|
+
> must set a custom serializer:
|
|
684
|
+
|
|
685
|
+
```js
|
|
686
|
+
fastify.get('/json-string', async function (request, reply) {
|
|
687
|
+
reply
|
|
688
|
+
.type('application/json; charset=utf-8')
|
|
689
|
+
.serializer(JSON.stringify)
|
|
690
|
+
.send('Hello') // Returns "Hello" (JSON-encoded string)
|
|
691
|
+
})
|
|
692
|
+
```
|
|
693
|
+
```js
|
|
694
|
+
fastify.get('/json', options, function (request, reply) {
|
|
695
|
+
reply.send('plain string')
|
|
696
|
+
})
|
|
697
|
+
```
|
|
698
|
+
|
|
699
|
+
#### Streams
|
|
700
|
+
<a id="send-streams"></a>
|
|
701
|
+
|
|
702
|
+
If you are sending a stream and you have not set a `'Content-Type'` header,
|
|
703
|
+
*send* will set it to `'application/octet-stream'`.
|
|
704
|
+
|
|
705
|
+
As noted above, streams are considered to be pre-serialized, so they will be
|
|
706
|
+
sent unmodified without response validation.
|
|
707
|
+
|
|
708
|
+
See special note about error handling for streams in
|
|
709
|
+
[`setErrorHandler`](./Server.md#seterrorhandler).
|
|
710
|
+
|
|
711
|
+
```js
|
|
712
|
+
const fs = require('node:fs')
|
|
713
|
+
|
|
714
|
+
fastify.get('/streams', function (request, reply) {
|
|
715
|
+
const stream = fs.createReadStream('some-file', 'utf8')
|
|
716
|
+
reply.header('Content-Type', 'application/octet-stream')
|
|
717
|
+
reply.send(stream)
|
|
718
|
+
})
|
|
719
|
+
```
|
|
720
|
+
When using async-await you will need to return or await the reply object:
|
|
721
|
+
```js
|
|
722
|
+
const fs = require('node:fs')
|
|
723
|
+
|
|
724
|
+
fastify.get('/streams', async function (request, reply) {
|
|
725
|
+
const stream = fs.createReadStream('some-file', 'utf8')
|
|
726
|
+
reply.header('Content-Type', 'application/octet-stream')
|
|
727
|
+
return reply.send(stream)
|
|
728
|
+
})
|
|
729
|
+
```
|
|
730
|
+
|
|
731
|
+
#### Buffers
|
|
732
|
+
<a id="send-buffers"></a>
|
|
733
|
+
|
|
734
|
+
If you are sending a buffer and you have not set a `'Content-Type'` header,
|
|
735
|
+
*send* will set it to `'application/octet-stream'`.
|
|
736
|
+
|
|
737
|
+
As noted above, Buffers are considered to be pre-serialized, so they will be
|
|
738
|
+
sent unmodified without response validation.
|
|
739
|
+
|
|
740
|
+
```js
|
|
741
|
+
const fs = require('node:fs')
|
|
742
|
+
|
|
743
|
+
fastify.get('/streams', function (request, reply) {
|
|
744
|
+
fs.readFile('some-file', (err, fileBuffer) => {
|
|
745
|
+
reply.send(err || fileBuffer)
|
|
746
|
+
})
|
|
747
|
+
})
|
|
748
|
+
```
|
|
749
|
+
|
|
750
|
+
When using async-await you will need to return or await the reply object:
|
|
751
|
+
```js
|
|
752
|
+
const fs = require('node:fs')
|
|
753
|
+
|
|
754
|
+
fastify.get('/streams', async function (request, reply) {
|
|
755
|
+
fs.readFile('some-file', (err, fileBuffer) => {
|
|
756
|
+
reply.send(err || fileBuffer)
|
|
757
|
+
})
|
|
758
|
+
return reply
|
|
759
|
+
})
|
|
760
|
+
```
|
|
761
|
+
|
|
762
|
+
#### TypedArrays
|
|
763
|
+
<a id="send-typedarrays"></a>
|
|
764
|
+
|
|
765
|
+
`send` manages TypedArray like a Buffer, and sets the `'Content-Type'`
|
|
766
|
+
header to `'application/octet-stream'` if not already set.
|
|
767
|
+
|
|
768
|
+
As noted above, TypedArray/Buffers are considered to be pre-serialized, so they
|
|
769
|
+
will be sent unmodified without response validation.
|
|
770
|
+
|
|
771
|
+
```js
|
|
772
|
+
const fs = require('node:fs')
|
|
773
|
+
|
|
774
|
+
fastify.get('/streams', function (request, reply) {
|
|
775
|
+
const typedArray = new Uint16Array(10)
|
|
776
|
+
reply.send(typedArray)
|
|
777
|
+
})
|
|
778
|
+
```
|
|
779
|
+
|
|
780
|
+
#### ReadableStream
|
|
781
|
+
<a id="send-readablestream"></a>
|
|
782
|
+
|
|
783
|
+
`ReadableStream` will be treated as a node stream mentioned above,
|
|
784
|
+
the content is considered to be pre-serialized, so they will be
|
|
785
|
+
sent unmodified without response validation.
|
|
786
|
+
|
|
787
|
+
```js
|
|
788
|
+
const fs = require('node:fs')
|
|
789
|
+
const { ReadableStream } = require('node:stream/web')
|
|
790
|
+
|
|
791
|
+
fastify.get('/streams', function (request, reply) {
|
|
792
|
+
const stream = fs.createReadStream('some-file')
|
|
793
|
+
reply.header('Content-Type', 'application/octet-stream')
|
|
794
|
+
reply.send(ReadableStream.from(stream))
|
|
795
|
+
})
|
|
796
|
+
```
|
|
797
|
+
|
|
798
|
+
#### Response
|
|
799
|
+
<a id="send-response"></a>
|
|
800
|
+
|
|
801
|
+
`Response` allows to manage the reply payload, status code and
|
|
802
|
+
headers in one place. The payload provided inside `Response` is
|
|
803
|
+
considered to be pre-serialized, so they will be sent unmodified
|
|
804
|
+
without response validation.
|
|
805
|
+
|
|
806
|
+
Please be aware when using `Response`, the status code and headers
|
|
807
|
+
will not directly reflect to `reply.statusCode` and `reply.getHeaders()`.
|
|
808
|
+
Such behavior is based on `Response` only allow `readonly` status
|
|
809
|
+
code and headers. The data is not allow to be bi-direction editing,
|
|
810
|
+
and may confuse when checking the `payload` in `onSend` hooks.
|
|
811
|
+
|
|
812
|
+
```js
|
|
813
|
+
const fs = require('node:fs')
|
|
814
|
+
const { ReadableStream } = require('node:stream/web')
|
|
815
|
+
|
|
816
|
+
fastify.get('/streams', function (request, reply) {
|
|
817
|
+
const stream = fs.createReadStream('some-file')
|
|
818
|
+
const readableStream = ReadableStream.from(stream)
|
|
819
|
+
const response = new Response(readableStream, {
|
|
820
|
+
status: 200,
|
|
821
|
+
headers: { 'content-type': 'application/octet-stream' }
|
|
822
|
+
})
|
|
823
|
+
reply.send(response)
|
|
824
|
+
})
|
|
825
|
+
```
|
|
826
|
+
|
|
827
|
+
|
|
828
|
+
#### Errors
|
|
829
|
+
<a id="errors"></a>
|
|
830
|
+
|
|
831
|
+
If you pass to *send* an object that is an instance of *Error*, Fastify will
|
|
832
|
+
automatically create an error structured as the following:
|
|
833
|
+
|
|
834
|
+
```js
|
|
835
|
+
{
|
|
836
|
+
error: String // the HTTP error message
|
|
837
|
+
code: String // the Fastify error code
|
|
838
|
+
message: String // the user error message
|
|
839
|
+
statusCode: Number // the HTTP status code
|
|
840
|
+
}
|
|
841
|
+
```
|
|
842
|
+
|
|
843
|
+
You can add custom properties to the Error object, such as `headers`, that will
|
|
844
|
+
be used to enhance the HTTP response.
|
|
845
|
+
|
|
846
|
+
> ℹ️ Note:
|
|
847
|
+
> If you are passing an error to `send` and the statusCode is less than
|
|
848
|
+
> 400, Fastify will automatically set it at 500.
|
|
849
|
+
|
|
850
|
+
Tip: you can simplify errors by using the
|
|
851
|
+
[`http-errors`](https://npm.im/http-errors) module or
|
|
852
|
+
[`@fastify/sensible`](https://github.com/fastify/fastify-sensible) plugin to
|
|
853
|
+
generate errors:
|
|
854
|
+
|
|
855
|
+
```js
|
|
856
|
+
fastify.get('/', function (request, reply) {
|
|
857
|
+
reply.send(httpErrors.Gone())
|
|
858
|
+
})
|
|
859
|
+
```
|
|
860
|
+
|
|
861
|
+
To customize the JSON error output you can do it by:
|
|
862
|
+
|
|
863
|
+
- setting a response JSON schema for the status code you need
|
|
864
|
+
- add the additional properties to the `Error` instance
|
|
865
|
+
|
|
866
|
+
Notice that if the returned status code is not in the response schema list, the
|
|
867
|
+
default behavior will be applied.
|
|
868
|
+
|
|
869
|
+
```js
|
|
870
|
+
fastify.get('/', {
|
|
871
|
+
schema: {
|
|
872
|
+
response: {
|
|
873
|
+
501: {
|
|
874
|
+
type: 'object',
|
|
875
|
+
properties: {
|
|
876
|
+
statusCode: { type: 'number' },
|
|
877
|
+
code: { type: 'string' },
|
|
878
|
+
error: { type: 'string' },
|
|
879
|
+
message: { type: 'string' },
|
|
880
|
+
time: { type: 'string' }
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
}, function (request, reply) {
|
|
886
|
+
const error = new Error('This endpoint has not been implemented')
|
|
887
|
+
error.time = 'it will be implemented in two weeks'
|
|
888
|
+
reply.code(501).send(error)
|
|
889
|
+
})
|
|
890
|
+
```
|
|
891
|
+
|
|
892
|
+
If you want to customize error handling, check out
|
|
893
|
+
[`setErrorHandler`](./Server.md#seterrorhandler) API.
|
|
894
|
+
|
|
895
|
+
> ℹ️ Note:
|
|
896
|
+
> You are responsible for logging when customizing the error handler.
|
|
897
|
+
|
|
898
|
+
API:
|
|
899
|
+
|
|
900
|
+
```js
|
|
901
|
+
fastify.setErrorHandler(function (error, request, reply) {
|
|
902
|
+
request.log.warn(error)
|
|
903
|
+
const statusCode = error.statusCode >= 400 ? error.statusCode : 500
|
|
904
|
+
reply
|
|
905
|
+
.code(statusCode)
|
|
906
|
+
.type('text/plain')
|
|
907
|
+
.send(statusCode >= 500 ? 'Internal server error' : error.message)
|
|
908
|
+
})
|
|
909
|
+
```
|
|
910
|
+
|
|
911
|
+
Beware that calling `reply.send(error)` in your custom error handler will send
|
|
912
|
+
the error to the default error handler.
|
|
913
|
+
Check out the [Reply Lifecycle](./Lifecycle.md#reply-lifecycle)
|
|
914
|
+
for more information.
|
|
915
|
+
|
|
916
|
+
The not found errors generated by the router will use the
|
|
917
|
+
[`setNotFoundHandler`](./Server.md#setnotfoundhandler)
|
|
918
|
+
|
|
919
|
+
API:
|
|
920
|
+
|
|
921
|
+
```js
|
|
922
|
+
fastify.setNotFoundHandler(function (request, reply) {
|
|
923
|
+
reply
|
|
924
|
+
.code(404)
|
|
925
|
+
.type('text/plain')
|
|
926
|
+
.send('a custom not found')
|
|
927
|
+
})
|
|
928
|
+
```
|
|
929
|
+
|
|
930
|
+
#### Type of the final payload
|
|
931
|
+
<a id="payload-type"></a>
|
|
932
|
+
|
|
933
|
+
The type of the sent payload (after serialization and going through any
|
|
934
|
+
[`onSend` hooks](./Hooks.md#onsend)) must be one of the following types,
|
|
935
|
+
otherwise, an error will be thrown:
|
|
936
|
+
|
|
937
|
+
- `string`
|
|
938
|
+
- `Buffer`
|
|
939
|
+
- `stream`
|
|
940
|
+
- `undefined`
|
|
941
|
+
- `null`
|
|
942
|
+
|
|
943
|
+
#### Async-Await and Promises
|
|
944
|
+
<a id="async-await-promise"></a>
|
|
945
|
+
|
|
946
|
+
Fastify natively handles promises and supports async-await.
|
|
947
|
+
|
|
948
|
+
*Note that in the following examples we are not using reply.send.*
|
|
949
|
+
```js
|
|
950
|
+
const { promisify } = require('node:util')
|
|
951
|
+
const delay = promisify(setTimeout)
|
|
952
|
+
|
|
953
|
+
fastify.get('/promises', options, function (request, reply) {
|
|
954
|
+
return delay(200).then(() => { return { hello: 'world' }})
|
|
955
|
+
})
|
|
956
|
+
|
|
957
|
+
fastify.get('/async-await', options, async function (request, reply) {
|
|
958
|
+
await delay(200)
|
|
959
|
+
return { hello: 'world' }
|
|
960
|
+
})
|
|
961
|
+
```
|
|
962
|
+
|
|
963
|
+
Rejected promises default to a `500` HTTP status code. Reject the promise, or
|
|
964
|
+
`throw` in an `async function`, with an object that has `statusCode` (or
|
|
965
|
+
`status`) and `message` properties to modify the reply.
|
|
966
|
+
|
|
967
|
+
```js
|
|
968
|
+
fastify.get('/teapot', async function (request, reply) {
|
|
969
|
+
const err = new Error()
|
|
970
|
+
err.statusCode = 418
|
|
971
|
+
err.message = 'short and stout'
|
|
972
|
+
throw err
|
|
973
|
+
})
|
|
974
|
+
|
|
975
|
+
fastify.get('/botnet', async function (request, reply) {
|
|
976
|
+
throw { statusCode: 418, message: 'short and stout' }
|
|
977
|
+
// will return to the client the same json
|
|
978
|
+
})
|
|
979
|
+
```
|
|
980
|
+
|
|
981
|
+
If you want to know more please review
|
|
982
|
+
[Routes#async-await](./Routes.md#async-await).
|
|
983
|
+
|
|
984
|
+
### .then(fulfilled, rejected)
|
|
985
|
+
<a id="then"></a>
|
|
986
|
+
|
|
987
|
+
As the name suggests, a `Reply` object can be awaited upon, i.e. `await reply`
|
|
988
|
+
will wait until the reply is sent. The `await` syntax calls the `reply.then()`.
|
|
989
|
+
|
|
990
|
+
`reply.then(fulfilled, rejected)` accepts two parameters:
|
|
991
|
+
|
|
992
|
+
- `fulfilled` will be called when a response has been fully sent,
|
|
993
|
+
- `rejected` will be called if the underlying stream had an error, e.g. the
|
|
994
|
+
socket has been destroyed.
|
|
995
|
+
|
|
996
|
+
For more details, see:
|
|
997
|
+
|
|
998
|
+
- https://github.com/fastify/fastify/issues/1864 for the discussion about this
|
|
999
|
+
feature
|
|
1000
|
+
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
|
|
1001
|
+
for the signature
|