status
stringclasses
1 value
repo_name
stringlengths
9
24
repo_url
stringlengths
28
43
issue_id
int64
1
104k
updated_files
stringlengths
8
1.76k
title
stringlengths
4
369
body
stringlengths
0
254k
βŒ€
issue_url
stringlengths
37
56
pull_url
stringlengths
37
54
before_fix_sha
stringlengths
40
40
after_fix_sha
stringlengths
40
40
report_datetime
unknown
language
stringclasses
5 values
commit_datetime
unknown
closed
fastify/fastify
https://github.com/fastify/fastify
4,122
["docs/Reference/TypeScript.md"]
Plugins must be imported at the top to propagate the types
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 3.29.1 ### Plugin version 6.1.0 ### Node.js version 16.15.0 ### Operating system Linux ### Operating system version (i.e. 20.04, 11.3, 10) Debian 11.3 ### Description typescript throw error when trying to add description or summary to endpoints: ``` fastify.post<{ Body: MyBody}>( '/generate', { schema: { description: 'my beautiful description', // <-- type error body: myBody, }, }, handler, ); ``` ![image](https://user-images.githubusercontent.com/11459632/178043760-8594471a-323f-4653-ab45-eec4dba28781.png) This is supported according to [`@fastify/swagger`](https://github.com/fastify/fastify-swagger): ![image](https://user-images.githubusercontent.com/11459632/178044184-daf342e4-bce6-49a1-a7b0-4383961fa2bc.png) Also, if I'm ignore the error with `// @ts-ignore` it's working correctly and the swagger is valid ### Steps to Reproduce Almost identical to `@fastify/swagger` example. 1. save the below code to a file (`a.ts`) 2. run `npx tsc --noEmit a.ts` ``` import fastify from 'fastify'; const server = fastify(); (async () => { await server.register(require('@fastify/swagger'), { routePrefix: '/documentation', swagger: { info: { title: 'Test swagger', description: 'Testing the Fastify swagger API', version: '0.1.0' }, externalDocs: { url: 'https://swagger.io', description: 'Find more info here' }, host: 'localhost', schemes: ['http'], consumes: ['application/json'], produces: ['application/json'], tags: [ { name: 'user', description: 'User related end-points' }, { name: 'code', description: 'Code related end-points' } ], definitions: { User: { type: 'object', required: ['id', 'email'], properties: { id: { type: 'string', format: 'uuid' }, firstName: { type: 'string' }, lastName: { type: 'string' }, email: {type: 'string', format: 'email' } } } }, securityDefinitions: { apiKey: { type: 'apiKey', name: 'apiKey', in: 'header' } } }, uiConfig: { docExpansion: 'full', deepLinking: false }, uiHooks: { onRequest: function (request, reply, next) { next() }, preHandler: function (request, reply, next) { next() } }, staticCSP: true, transformStaticCSP: (header) => header, exposeRoute: true }) server.put('/some-route/:id', { schema: { description: 'post some data', tags: ['user', 'code'], summary: 'qwerty', params: { type: 'object', properties: { id: { type: 'string', description: 'user id' } } }, body: { type: 'object', properties: { hello: { type: 'string' }, obj: { type: 'object', properties: { some: { type: 'string' } } } } }, response: { 201: { description: 'Successful response', type: 'object', properties: { hello: { type: 'string' } } }, default: { description: 'Default response', type: 'object', properties: { foo: { type: 'string' } } } }, security: [ { "apiKey": [] } ] } }, (req, reply) => {}) await server.ready() server.swagger() })(); ``` ### Expected Behavior no type error
https://github.com/fastify/fastify/issues/4122
https://github.com/fastify/fastify/pull/4126
cf091f72e562655dafce7951cd34a9f092c99bd5
d45bcb6b3a3cb412a7b7799a34fe34867f1df854
"2022-07-08T18:07:29Z"
javascript
"2022-07-11T07:39:33Z"
closed
fastify/fastify
https://github.com/fastify/fastify
4,120
["test/types/hooks.test-d.ts", "test/types/request.test-d.ts", "test/types/type-provider.test-d.ts", "types/hooks.d.ts", "types/instance.d.ts", "types/request.d.ts", "types/route.d.ts", "types/type-provider.d.ts"]
Typescript: Type Provider information gets lost with onRequest
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 4.2.0 ### Plugin version _No response_ ### Node.js version 16.13.0 ### Operating system macOS ### Operating system version (i.e. 20.04, 11.3, 10) n/a ### Description I've added the new type providers from Fastify 4 to my project to avoid the redundant, cluttered generics. My project makes use of β€œonRequest” hooks which check a custom authentication in different endpoints. Example: ```typescript // simplified for demo purposes -- this is used in various endpoints const authenticateHook: onRequestAsyncHookHandler<any, any, any, any, any, any, any, any, any> = () => { return Promise.resolve(); }; // example copied from https://www.fastify.io/docs/latest/Reference/Type-Providers/#typebox server.get('/route', { schema: { querystring: Type.Object({ foo: Type.Number(), bar: Type.String() }) }, onRequest: authenticateHook }, (request, reply) => { // type Query = { foo: number, bar: string } const { foo, bar } = request.query // NOT type safe when adding `onRequest` :-( }) ``` The problem: After adding the `onRequest` hook, the type safety gets totally lost and e.g. request.query is `unknown`. I've been trying various workarounds (e.g. handling through all these generics), however I didn't really get to a clean, let alone, scalable solution. ### Steps to Reproduce See snippet. ### Expected Behavior I'd expect the type information to be preserved.
https://github.com/fastify/fastify/issues/4120
https://github.com/fastify/fastify/pull/4123
0ca63a0819a154023c4de14e2723578a2b3f0961
f5a392bfea204062202f3e29cc8531cab0234035
"2022-07-08T13:56:13Z"
javascript
"2022-07-21T16:34:58Z"
closed
fastify/fastify
https://github.com/fastify/fastify
4,110
["test/types/instance.test-d.ts", "types/.eslintrc.json", "types/instance.d.ts"]
Figure out what to do with typed decorators
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the issue has not already been raised ### Issue When [this PR](https://github.com/fastify/fastify/pull/3203) was merged to main in [this commit](https://github.com/fastify/fastify/commit/d37d8997dd22f4ace29a29320ac50a43ec98731f#diff-f86d0644c15a00c507413e99f283c1f856275409929539a74b8196a42da25018), it also removed all the changes made in [this PR](https://github.com/fastify/fastify/pull/2981) Ideally AFAIC PR 2981 would be re-added. This might be a bit problematic since #3203 hijacked the first generic slot for all `decorate*` functions, so re-adding it would be a breaking change. Also this means that since typed decorators wasn't actually added in v4, the feature isn't and cannot be used by anyone. There's few options I can think of: 1. Re-add typed decorators as a supplement to 'this types' even if it's a (very small) breaking change 2. Add typed decorators to `decorate*` functions in fastify v5 3. Introduce `typedDecorate*` functions that do the same as `decorate*` but with type checking 4. Forget that typed decorators can even exist and ignore this issue There's also this tiny documentation change that should probably be removed now: https://github.com/fastify/fastify/pull/2981/files#diff-c2db295d2a99e431bb24ac08c3953353dbb702f62b48587aa2cd76a0b78e0dbf
https://github.com/fastify/fastify/issues/4110
https://github.com/fastify/fastify/pull/4111
e698ab739255454929eb0051c4d5cba40c3a16ca
20263a1bf8c8195d4692c634ecba86baa918b2d5
"2022-07-04T10:21:10Z"
javascript
"2022-07-09T08:30:10Z"
closed
fastify/fastify
https://github.com/fastify/fastify
4,107
["package.json", "test/schema-validation.test.js"]
`only` method is not working as expected
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 4.2.0 ### Plugin version 3.1.0 ### Node.js version 17.8.0 ### Operating system macOS ### Operating system version (i.e. 20.04, 11.3, 10) 12.1 ### Description Creating multiple schemas out of existing one using the `only` method is creating conflictions when used with different `http` methods. For instance, If two schemas for `POST` and `PATCH` is extracted from base schema using `only` keyword then only one of them is getting applied to both routes (first route in the file is taking precedence) ### Steps to Reproduce Below are examples of schemas and routes. **Base schema** ``` const UserSchema = Schema.object() .id('http://mydomain.com/user') .title('User schema') .description('Contains all user fields') .prop('id', Schema.integer()) .prop('username', Schema.string().minLength(4)) .prop('firstName', Schema.string().minLength(1)) .prop('lastName', Schema.string().minLength(1)) .prop('fullName', Schema.string().minLength(1)) .prop('email', Schema.string()) .prop('password', Schema.string().minLength(6)) .prop('bio', Schema.string()); ``` **Schema for POST method** (_All fields are required_) ``` const UserCreateSchema = UserSchema.only([ 'username', 'firstName', 'lastName', 'email', 'bio', 'password', 'password_confirm', ]).required([ 'username', 'firstName', 'lastName', 'email', 'bio', 'password', ]); ``` **Schema for PATCH method** (_Only fields mentioned in patch schema is modifiable and none of them are required._) ``` const UserPatchSchema = UserSchema.only([ 'firstName', 'lastName', 'bio', ]); ``` ## 1. Routes ``` app.post('/user', { schema: { body: UserCreateSchema, }, handler: {CREATE HANDLER}, }); app.patch('/user/:id', { schema: { body: UserPatchSchema, }, handler: {PATCH HANDLER}, }); ``` As in above snippet, when `app.post` is declared first then `UserCreateSchema` is getting applied to both `POST` & `PATCH` routes. And if we revert the order of routes like below then `UserPatchSchema` is getting applied to both routes ignoring rules defined in `UserCreateSchema` for `POST` ## 2. Routes ``` app.patch('/user/:id', { schema: { body: UserPatchSchema, }, handler: {PATCH HANDLER}, }); app.post('/user', { schema: { body: UserCreateSchema, }, handler: {CREATE HANDLER}, }); ``` ### Expected Behavior Ideally, schemas created using `only` keyword should work independently without conflictions.
https://github.com/fastify/fastify/issues/4107
https://github.com/fastify/fastify/pull/4109
69df0e39fa5886fcd8d5411c590a429e16a2c3ae
b48f608dcd3e8f41981b3929003b9e9c47b5f1cd
"2022-07-03T07:49:21Z"
javascript
"2022-07-04T08:35:21Z"
closed
fastify/fastify
https://github.com/fastify/fastify
4,093
["test/types/fastify.test-d.ts", "test/validation-error-handling.test.js", "types/schema.d.ts"]
`schemaErrorFormatter` uses an insufficient validation type
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 4.2.0 ### Plugin version _No response_ ### Node.js version 16.15.1 ### Operating system Linux ### Operating system version (i.e. 20.04, 11.3, 10) Irrelevant ### Description The `FastifySchemaValidationError` type used for the `schemaErrorFormatter` callback has a small subset of the fields available from the full Ajv validation error object. https://github.com/fastify/fastify/blob/8fccc461c090b488598831b74bc837d5c5d2b9a9/types/schema.d.ts#L25-L28 This is the proper object: https://github.com/fastify/fastify/blob/8fccc461c090b488598831b74bc837d5c5d2b9a9/fastify.d.ts#L178-L190 ### Steps to Reproduce ```typescript import Fastify from "fastify"; const fastify = Fastify({ schemaErrorFormatter: (errors, dataVar) => { const [error] = errors; const path = (error.instancePath ?? "") .replace("/", ".") .replace(/\/(\d)/, "[$1]"); let { message } = error; if (error.keyword === "enum") { const values = error.params.allowedValues as string[]; message += `: ${values.join(", ")}`; } return new Error(`${dataVar}${path} ${message.replace(/"/g, "'")}`); } }); ``` ```typescript test.ts:12:13 - error TS2339: Property 'keyword' does not exist on type 'FastifySchemaValidationError'. 12 if (error.keyword === "enum") { ~~~~~~~ test.ts:13:25 - error TS2339: Property 'params' does not exist on type 'FastifySchemaValidationError'. 13 const values = error.params.allowedValues as string[]; ``` Workaround: ```typescript import Fastify, { ValidationResult } from "fastify"; const fastify = Fastify({ schemaErrorFormatter: (errors, dataVar) => { const [error] = errors as unknown as ValidationResult[]; const path = (error.instancePath ?? "") .replace("/", ".") .replace(/\/(\d)/, "[$1]"); let { message } = error; if (error.keyword === "enum") { const values = error.params.allowedValues as string[]; message += `: ${values.join(", ")}`; } return new Error(`${dataVar}${path} ${message.replace(/"/g, "'")}`); } });_ ``` ### Expected Behavior Compiles, resulting in pretty errors like this: `body.roles[0] must be equal to one of the allowed values: internal, owner, admin, communicator` `body.roles must NOT have more than 1 items` `querystring.ownerId must NOT have fewer than 28 characters`
https://github.com/fastify/fastify/issues/4093
https://github.com/fastify/fastify/pull/4094
42cf476a3f24091e1974d977e310c04da5edc9de
c5ac1833b2ab1904da5330ada8a64120d4c1e8a7
"2022-06-29T11:53:14Z"
javascript
"2022-07-01T07:19:34Z"
closed
fastify/fastify
https://github.com/fastify/fastify
4,088
["test/types/request.test-d.ts", "test/types/type-provider.test-d.ts", "types/route.d.ts"]
Return type not correctly set with type providers
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 4.1.0 ### Plugin version _No response_ ### Node.js version 16.14.0 ### Operating system Windows ### Operating system version (i.e. 20.04, 11.3, 10) 11 ### Description Return types aren't being checked correctly when inferred by a type provider. ### Steps to Reproduce ```ts import fastify, { FastifyTypeProvider } from "fastify" interface ExampleTypeProvider extends FastifyTypeProvider { output: string // everything is typed as a string } fastify().withTypeProvider<ExampleTypeProvider>().get("/", { schema: { response: "string" } as const }, (_, res) => { res.send({ foo: 555 }) // this makes typescript complain return { foo: 555 } // this does not }) ``` ### Expected Behavior I expect `return { foo: 555 }` to error, because it's not `return "some string"` or the like.
https://github.com/fastify/fastify/issues/4088
https://github.com/fastify/fastify/pull/4089
6a4b34cb402b87c48b3ce5a88f361369da87077d
5856a46ec41f17bf1e2cae43d2e3add21049b5c2
"2022-06-25T17:02:23Z"
javascript
"2022-06-26T22:19:57Z"
closed
fastify/fastify
https://github.com/fastify/fastify
4,085
["docs/Guides/Migration-Guide-V4.md"]
Hook onRoute doesn't work correct inside registered plugin
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 4.1.0 ### Plugin version _No response_ ### Node.js version 16.15.1 ### Operating system Linux ### Operating system version (i.e. 20.04, 11.3, 10) Ubuntu 22.04 LTS ### Description If the onRoute hook is in the main application code, then callback is called for all routes. And extraneous HEAD routes appear. If the onRoute hook is placed inside the plugin, then the callback is called only for the HEAD routes. But registration of such a HEAD route did not occur. ### Steps to Reproduce Example: ```javascript const fastify = Fastify({ logger: true }); fastify.addHook('onRoute', (routeOptions) => { const { path, method } = routeOptions; console.log({ path, method }); }); fastify.get('/', (req, reply) => { reply.send('index'); }); // Output: // { path: '/', method: 'GET' } // { path: '/', method: 'HEAD' } ``` Example with hook inside plugin: ```javascript const fastify = Fastify({ logger: true }); fastify.register((instance, opts, done) => { instance.addHook('onRoute', (routeOptions) => { const { path, method } = routeOptions; console.log({ path, method }); }); done(); }); fastify.get('/', (req, reply) => { reply.send('index'); }); // Output: // Empty output ``` Example with using fastify-plugin ```javascript import fp from 'fastify-plugin'; const fastify = Fastify({ logger: true }); fastify.register(fp((instance, opts, done) => { instance.addHook('onRoute', (routeOptions) => { const { path, method } = routeOptions; console.log({ path, method }); }); done(); })); fastify.get('/', (req, reply) => { reply.send('index'); }); // Output: // { path: '/', method: 'HEAD' } // No GET route ``` ### Expected Behavior Inside the plugin, the hook should have a route `{ path: '/', method: 'GET' }` and should not have a HEAD route. When using a hook outside the plugin, there should also be only one GET route. This behavior was in fastify version 3.29.0.
https://github.com/fastify/fastify/issues/4085
https://github.com/fastify/fastify/pull/4091
977dec0371c275dda0ec6f1f8cba731c5ca4b563
4eea272182ce4360677a1c2509184ce71d22ae7a
"2022-06-24T11:33:36Z"
javascript
"2022-06-28T10:08:22Z"
closed
fastify/fastify
https://github.com/fastify/fastify
4,063
["test/types/request.test-d.ts", "types/type-provider.d.ts"]
TypeScript reports errors when union type passed as Body to RouteGeneric since Fastify 4
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 4.1.0 ### Plugin version _No response_ ### Node.js version 18.x ### Operating system macOS ### Operating system version (i.e. 20.04, 11.3, 10) 12.3 ### Description Hi, I came across the following problem after updating to 4.x. `Body` property of request gets resolved to `unknown` instead of `{ filters?: { ids: string[] } } | null`. Use-case: we have some routes that optionally accept body using ajv's `anyOf` keyword. It used to work in Fastify 3. Fastify 4: ![image](https://user-images.githubusercontent.com/1452141/174833671-158068b3-7ac9-492d-9dbf-4187b6d3dcbd.png) vs. Fastify 3: ![image](https://user-images.githubusercontent.com/1452141/174833367-31be37c0-699b-41cf-8441-9981666071f7.png) ### Steps to Reproduce This snippet can be used to reproduce the problem: ``` import { fastify } from 'fastify'; const app = fastify(); app.route<{ Body: { filters?: { ids: string[] } } | null; }>({ method: 'DELETE', url: '/entities', schema: {}, // omitted for clarity async handler(request, reply) { const filters = request.body?.filters; }, }); ``` ### Expected Behavior `body` type gets resolved to `{ filters?: { ids: string[] } } | null` instead of unknown.
https://github.com/fastify/fastify/issues/4063
https://github.com/fastify/fastify/pull/4076
7e6dca0d89c7d29b6b77dd6fb96fee5fc23ad73d
4d1fb5f8b77a47f2fb24cd18dfc0972eb6a4a14c
"2022-06-21T15:07:41Z"
javascript
"2022-06-24T18:21:47Z"
closed
fastify/fastify
https://github.com/fastify/fastify
4,045
["docs/Reference/TypeScript.md", "fastify.d.ts", "test/types/fastify.test-d.ts"]
Fastify ValidationResult type and AJV v8 ErrorObject mismatch
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 4 ### Plugin version _No response_ ### Node.js version 16 ### Operating system Linux ### Operating system version (i.e. 20.04, 11.3, 10) 20 ### Description AJV error object is like this, ```ts export interface ErrorObject<K extends string = string, P = Record<string, any>, S = unknown> { keyword: K instancePath: string schemaPath: string params: P // Added to validation errors of "propertyNames" keyword schema propertyName?: string // Excluded if option `messages` set to false. message?: string // These are added with the `verbose` option. schema?: S parentSchema?: AnySchemaObject data?: unknown } ``` Fastify type is like this, ```ts export interface ValidationResult { keyword: string; dataPath: string; schemaPath: string; params: Record<string, string | string[]>; message: string; } ``` In version 3 of Fastify (and the AJV version it used), AJV errors were directly assignable to ValidationResult type and vice verca. But in v4 the types mismatch. looks like AJV no longer has the `dataPath` key. It was changed [here](https://github.com/ajv-validator/ajv/commit/242631a8fb5c8b3d196d79333c8956c0ab5675ea). ### Steps to Reproduce Try this in v3 and v4 projects. ```ts import { ValidationResult } from 'fastify' import { ErrorObject } from 'ajv' const foo = {} as ErrorObject const bar = {} as ValidationResult const baz: ErrorObject = bar const bass: ValidationResult = foo ``` ### Expected Behavior Edit: Maybe fastify is internally converting the ErrorObject to a ValidationError. In that case, it wouldn't be an issuue. But it maybe the case that, fastify is not handling this new ErrorObject properly.
https://github.com/fastify/fastify/issues/4045
https://github.com/fastify/fastify/pull/4070
1398d38139bf785e5f83b9ece42dc78206e9e0b7
81f28ce452bc813c6e3d7ab29319111c86a332b2
"2022-06-19T13:31:57Z"
javascript
"2022-06-22T12:58:06Z"
closed
fastify/fastify
https://github.com/fastify/fastify
4,044
["lib/context.js", "lib/route.js", "lib/symbols.js", "test/hooks.test.js", "test/pretty-print.test.js"]
onRoute hook executed for endpoint declared before registering it
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 4.0.3 ### Plugin version _No response_ ### Node.js version 18 ### Operating system macOS ### Operating system version (i.e. 20.04, 11.3, 10) latest ### Description When the `onRoute` hook is registered after a GET handler, it is executed for the HEAD route only. ### Steps to Reproduce ``` const fastify = require('fastify') const app = fastify() app.addHook('onRoute', function inspector(routeOptions) { console.log('before ' + routeOptions.method) }) app.get('/', function (request, reply) { }) app.addHook('onRoute', function inspector(routeOptions) { console.log('after ' + routeOptions.method) }) app.ready() ``` Prints: ``` before GET before HEAD after HEAD ``` ### Expected Behavior I think the after hook should not be executed. It should print: ``` before GET before HEAD ```
https://github.com/fastify/fastify/issues/4044
https://github.com/fastify/fastify/pull/4052
bd1f99cb09409d9566aa5e6a9d670f592801f655
5bf0f4fd4ea5f6ab56ab7dba1de24455a128a0bd
"2022-06-19T13:02:28Z"
javascript
"2022-06-23T17:25:39Z"
closed
fastify/fastify
https://github.com/fastify/fastify
4,032
["test/types/register.test-d.ts", "types/register.d.ts"]
FastifyRegister type does not propagate type provider generic to plugin type
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 4.x.x ### Plugin version _No response_ ### Node.js version 16.x ### Operating system macOS ### Operating system version (i.e. 20.04, 11.3, 10) 11.6 ### Description The `FastifyRegister` type (of `fastify.register` function) has this interface: ```ts export interface FastifyRegister<T = void> { <Options extends FastifyPluginOptions>( plugin: FastifyPluginCallback<Options>, opts?: FastifyRegisterOptions<Options> ): T; <Options extends FastifyPluginOptions>( plugin: FastifyPluginAsync<Options>, opts?: FastifyRegisterOptions<Options> ): T; <Options extends FastifyPluginOptions>( plugin: FastifyPluginCallback<Options> | FastifyPluginAsync<Options> | Promise<{ default: FastifyPluginCallback<Options> }> | Promise<{ default: FastifyPluginAsync<Options> }>, opts?: FastifyRegisterOptions<Options> ): T; } ``` This passes through the `Options` to the `plugin` but not the other arguments (`Server` and `TypeProvider`) which results in an error like this: ``` No overload matches this call. Overload 1 of 3, '(plugin: FastifyPluginCallback<Record<never, never>, http.Server, FastifyTypeProviderDefault>, opts?: FastifyRegisterOptions<Record<never, never>> | undefined): FastifyInstance<...> & PromiseLike<...>', gave the following error. Argument of type 'FastifyPluginAsync<Record<never, never>, http.Server, TypeBoxTypeProvider>' is not assignable to parameter of type 'FastifyPluginCallback<Record<never, never>, http.Server, FastifyTypeProviderDefault>'. Types of parameters 'instance' and 'instance' are incompatible. Type 'FastifyInstance<http.Server, http.IncomingMessage, http.ServerResponse, FastifyLoggerInstance, FastifyTypeProviderDefault>' is not assignable to type 'FastifyInstance<http.Server, http.IncomingMessage, http.ServerResponse, FastifyLoggerInstance, TypeBoxTypeProvider>'. The types returned by 'after()' are incompatible between these types. Type 'FastifyInstance<http.Server, http.IncomingMessage, http.ServerResponse, FastifyLoggerInstance, FastifyTypeProviderDefault> & PromiseLike<undefined>' is not assignable to type 'FastifyInstance<http.Server, http.IncomingMessage, http.ServerResponse, FastifyLoggerInstance, TypeBoxTypeProvider> & PromiseLike<undefined>'. Type 'FastifyInstance<http.Server, http.IncomingMessage, http.ServerResponse, FastifyLoggerInstance, FastifyTypeProviderDefault> & PromiseLike<undefined>' is not assignable to type 'FastifyInstance<http.Server, http.IncomingMessage, http.ServerResponse, FastifyLoggerInstance, TypeBoxTypeProvider>'. Types of property 'register' are incompatible. Type 'FastifyRegister<FastifyInstance<http.Server, http.IncomingMessage, http.ServerResponse, FastifyLoggerInstance, FastifyTypeProviderDefault> & PromiseLike<undefined>>' is not assignable to type 'FastifyRegister<FastifyInstance<http.Server, http.IncomingMessage, http.ServerResponse, FastifyLoggerInstance, TypeBoxTypeProvider> & PromiseLike<undefined>>'. Type 'FastifyInstance<http.Server, http.IncomingMessage, http.ServerResponse, FastifyLoggerInstance, FastifyTypeProviderDefault> & PromiseLike<undefined>' is not assignable to type 'FastifyInstance<http.Server, http.IncomingMessage, http.ServerResponse, FastifyLoggerInstance, TypeBoxTypeProvider> & PromiseLike<undefined>'. Type 'FastifyInstance<http.Server, http.IncomingMessage, http.ServerResponse, FastifyLoggerInstance, FastifyTypeProviderDefault> & PromiseLike<undefined>' is not assignable to type 'FastifyInstance<http.Server, http.IncomingMessage, http.ServerResponse, FastifyLoggerInstance, TypeBoxTypeProvider>'. The types of 'addSchema(...).get' are incompatible between these types. Type 'RouteShorthandMethod<http.Server, http.IncomingMessage, http.ServerResponse, FastifyTypeProviderDefault>' is not assignable to type 'RouteShorthandMethod<http.Server, http.IncomingMessage, http.ServerResponse, TypeBoxTypeProvider>'. Type 'FastifyTypeProviderDefault' is not assignable to type 'TypeBoxTypeProvider'. Overload 2 of 3, '(plugin: FastifyPluginAsync<Record<never, never>, http.Server, FastifyTypeProviderDefault>, opts?: FastifyRegisterOptions<Record<never, never>> | undefined): FastifyInstance<...> & PromiseLike<...>', gave the following error. Argument of type 'FastifyPluginAsync<Record<never, never>, http.Server, TypeBoxTypeProvider>' is not assignable to parameter of type 'FastifyPluginAsync<Record<never, never>, http.Server, FastifyTypeProviderDefault>'. Types of parameters 'instance' and 'instance' are incompatible. Type 'FastifyInstance<http.Server, http.IncomingMessage, http.ServerResponse, FastifyLoggerInstance, FastifyTypeProviderDefault>' is not assignable to type 'FastifyInstance<http.Server, http.IncomingMessage, http.ServerResponse, FastifyLoggerInstance, TypeBoxTypeProvider>'. Overload 3 of 3, '(plugin: FastifyPluginCallback<Record<never, never>, http.Server, FastifyTypeProviderDefault> | FastifyPluginAsync<Record<never, never>, http.Server, FastifyTypeProviderDefault> | Promise<...> | Promise<...>, opts?: FastifyRegisterOptions<...> | undefined): FastifyInstance<...> & PromiseLike<...>', gave the following error. Argument of type 'FastifyPluginAsync<Record<never, never>, http.Server, TypeBoxTypeProvider>' is not assignable to parameter of type 'FastifyPluginCallback<Record<never, never>, http.Server, FastifyTypeProviderDefault> | FastifyPluginAsync<Record<never, never>, http.Server, FastifyTypeProviderDefault> | Promise<...> | Promise<...>'. Type 'FastifyPluginAsync<Record<never, never>, http.Server, TypeBoxTypeProvider>' is not assignable to type 'FastifyPluginAsync<Record<never, never>, http.Server, FastifyTypeProviderDefault>'. ``` ### Steps to Reproduce See https://github.com/stefee/fastify-issue-repro-4032/blob/main/index.ts ### Expected Behavior No type error.
https://github.com/fastify/fastify/issues/4032
https://github.com/fastify/fastify/pull/4034
cbd643fced116d1e51b6603130477cc000371f15
45c8564e6cff193763c4fe0616d103405e353e18
"2022-06-17T12:55:42Z"
javascript
"2022-06-19T10:12:30Z"
closed
fastify/fastify
https://github.com/fastify/fastify
4,031
[".eslintrc"]
Can fastify exclude .eslintrc in the publish package?
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the issue has not already been raised ### Issue fastify includes `.eslintrc` in its publish package, which is the following: ``` { "extends": "standard" } ``` This cause a error pop-up in VSCode everytime when I try to check the types of fastify. > ESLint: Failed to load config "standard" to extend from. I do not use `standard` and do not have it installed. However, `.eslintrc` in the package has higher priority than the workspace ESLint config. So, when I try to inspect the TypeScript definition, ESLint will throw an error. Can fastify exclude `.eslintrc` in the publish package? It does not cause any errors in real code but it is annoying. I also think fastify should only include the necessary files in its package which contains build scripts, documentation and tests.
https://github.com/fastify/fastify/issues/4031
https://github.com/fastify/fastify/pull/4038
45c8564e6cff193763c4fe0616d103405e353e18
2324549996241a3f79de3eefb6898344dfbca1f2
"2022-06-17T06:45:59Z"
javascript
"2022-06-19T10:21:19Z"
closed
fastify/fastify
https://github.com/fastify/fastify
4,018
["lib/wrapThenable.js", "test/stream.test.js"]
Stream replies not working when async preHandler hook is defined.
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 4.0.0 ### Plugin version _No response_ ### Node.js version 16.0.0 ### Operating system Mac OS ### Operating system version (i.e. 20.04, 11.3, 10) 11.6.5 ### Description When defining an async preHandler, all routes with an async handler returning a stream stop working. In the example below you will notice that after calling /notworking the response body is empty and the console shows an error. Error [ERR_STREAM_WRITE_AFTER_END]: write after end at new NodeError (node:internal/errors:372:5) at write_ (node:_http_outgoing:748:11) at ServerResponse.write (node:_http_outgoing:707:15) at Readable.ondata (node:internal/streams/readable:754:22) at Readable.emit (node:events:527:28) at Readable.read (node:internal/streams/readable:527:10) at flow (node:internal/streams/readable:1011:34) at emitReadable_ (node:internal/streams/readable:592:3) at processTicksAndRejections ### Steps to Reproduce ```js import fastify from "fastify"; import { Readable } from 'stream' const api = fastify({ logger: true }) api.addHook('preHandler', async () => { console.log("do async stuff") }) api.post('/notworking', async (req, reply) => { const s = new Readable(); s.push('not working'); s.push(null); reply.send(s); }); api.post('/working', function (req, reply) { const s = new Readable(); s.push('working'); s.push(null); reply.send(s); }); api.listen({ port: 3000 }, (err, address) => { if (err) throw err console.log("listen") }); ``` ### Expected Behavior The stream is returned as normal.
https://github.com/fastify/fastify/issues/4018
https://github.com/fastify/fastify/pull/4021
3ebbe27441e3b1c4b77e59f14b40f4062d1a8780
ea6272ec5d66d8d3caa5b9c2be0989cd52adb732
"2022-06-14T20:22:56Z"
javascript
"2022-06-15T16:51:11Z"
closed
fastify/fastify
https://github.com/fastify/fastify
4,007
["lib/server.js", "test/listen.test.js"]
Server will also listen on a random port when calling app.listen({path: 'foo.sock'})
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 4.0.2 ### Plugin version _No response_ ### Node.js version 16.15.1 ### Operating system macOS ### Operating system version (i.e. 20.04, 11.3, 10) 12.4 ### Description If I pass to `listen` only a `path` to listen on, the server will also listen on a random port. I think this happens due to this code here: https://github.com/fastify/fastify/blob/78adc9cc76f26ad2461d15103452f64487d806df/lib/server.js#L297-L299 P.S. I got a deprecation warning even for `app.listen(option, (err) => { ... })` which AFAIK should not be deprecated. ### Steps to Reproduce ```js const Fastify = require('fastify'); const app = Fastify({logger: true}); app.listen({ path: 'foo.sock' }); ``` ### Expected Behavior It only listens on `path`.
https://github.com/fastify/fastify/issues/4007
https://github.com/fastify/fastify/pull/4011
b66cf20b70570c5a80908c065d8935bc3039f820
50d1e586a0c395ab8d58dac770f74561cf06c522
"2022-06-13T12:40:50Z"
javascript
"2022-06-14T18:36:54Z"
closed
fastify/fastify
https://github.com/fastify/fastify
4,006
[".github/workflows/integration.yml", "integration/server.js", "integration/test.sh"]
Add integration CI step
> This IS an issue in fastify. #3996 introduced a **production dependency** on fast-json-stringify (see [these lines](https://github.com/fastify/fastify/pull/3996/files#diff-f6017ca412ba95771e5839b4b2cbd40b2d5cdd11d698991016945639ba54b6b5R6-R7)), and more to that, to a **specific version** (4.0.1) of that library. Thank you for linking to the actual code. We _**definitely**_ want to add direct dependencies to the dependencies list. I think we really need a CI step that does: 1. `pnpm install --production` or `npm install --legacy-deps --legacy-peer-deps` 2. `node some_basic_server.js` 3. `curl /several_endpoints` That should catch these cases in the future as neither of the options in step one will install the transitive dependency in such a fashion that Fastify itself will have access to it. _Originally posted by @jsumners in https://github.com/fastify/fastify/issues/3998#issuecomment-1153824043_
https://github.com/fastify/fastify/issues/4006
https://github.com/fastify/fastify/pull/4075
5bf0f4fd4ea5f6ab56ab7dba1de24455a128a0bd
7e6dca0d89c7d29b6b77dd6fb96fee5fc23ad73d
"2022-06-13T11:56:58Z"
javascript
"2022-06-24T18:05:49Z"
closed
fastify/fastify
https://github.com/fastify/fastify
4,048
["docs/Reference/Validation-and-Serialization.md", "lib/handleRequest.js", "lib/validation.js", "test/reply-error.test.js", "test/schema-feature.test.js", "test/validation-error-handling.test.js"]
Additional error logging when using setErrorHandler
Hi all, I recently upgraded from fastify version 3.26.0 to 4.0.1 and now have an issue with the setErrorHandler method. My setErrorHandler is implemented like this ```javascript fastify.setErrorHandler(function (error, request, reply) { // some custom logging operations reply.send(error); } ``` In the previous version 3.26.0, the application did just my custom-defined logging and then returned a well-formed json like this: ```json { "message": "Error intentionally triggered", "error": "Internal Server Error", "statusCode": 500 } ``` Since the 4.0.1 version, there is now an additional error logging done by fastify, which I can not turn off. I narrowed the issue down to following statement: ```javascript // Problematic part in the code reply.send(error); ``` ```bash # Excerpt of the additional logging err: { "type": "Error", "message": "The error message", "stack": Error: The error message ... ``` My observation: If I send the "complete" error object, the additional logging occurs, but when I just send parts of the error (e.g. the error message) the additional logging is gone: ```javascript reply.send(error.message); ``` Is there a way to turn off the additional logging, when returning the "full" error object? I want to use the "full" object, since I also need the statusCode and the error in the reply message like this: ```javascript { "message": "Error intentionally triggered", "error": "Internal Server Error", "statusCode": 500 } ``` As a workaround, I tried to construct this object myself, but I don't understand, how I can access the actual error statusCode to send it back, for example like this: ```javascript reply.send({ "message": error.message "error": error.error "statusCode": error.statusCode }) ``` The property "error.statusCode" is undefined on the error object, so I guess there must be another way to access it somehow. Help would be really appreciated here :-)
https://github.com/fastify/fastify/issues/4048
https://github.com/fastify/fastify/pull/4061
7c8f74b6a0a065e60ab7e91b503252991b0e9475
4bf4af639505083ae59c75c1cda19acdc47bb3f0
"2022-06-13T01:15:41Z"
javascript
"2022-06-21T17:52:40Z"
closed
fastify/fastify
https://github.com/fastify/fastify
4,002
["docs/Reference/Server.md", "fastify.d.ts", "test/types/instance.test-d.ts", "types/schema.d.ts"]
Documentation and type defs mismatch schemaController bucket factory implementation
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the issue has not already been raised ### Issue https://www.fastify.io/docs/latest/Reference/Server/#schemacontroller In the above docs `addSchema` is mentioned as a method of the bucket. According to the latest version of `schema-controller.js`, it is `add`. In addition, line 147 of fastify.d.ts mentions `addSchema` . Whereas the current implementation is more like, ``` schemaController?: { bucket?: (parentSchemas?: unknown) => { add(schema: unknown): void; getSchema(schemaId: string): void; getSchemas(): Record<string, unknown>; }; ``` Checked both version 3.29 and 4.0, issue is present.
https://github.com/fastify/fastify/issues/4002
https://github.com/fastify/fastify/pull/4022
44589bedd478252965d4924c628b0ccd11b4bb47
09d7e2486baa9657e2b8d76309f0ccee1df18cbe
"2022-06-12T18:13:00Z"
javascript
"2022-06-19T12:41:42Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,998
["package.json"]
[4.0.1] Cannot find module fast-json-stringify/serializer
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the regression has not already been reported ### Last working version 4.0.0 ### Stopped working in version 4.0.1 ### Node.js version 18.3.0 ### Operating system Linux ### Operating system version (i.e. 20.04, 11.3, 10) Docker ### πŸ’₯ Regression Report following error when starting my application: ``` node:internal/modules/cjs/loader:939 const err = new Error(message); ^ Error: Cannot find module 'fast-json-stringify/serializer' Require stack: - /app/node_modules/fastify/lib/error-serializer.js - /app/node_modules/fastify/lib/error-handler.js - /app/node_modules/fastify/lib/reply.js - /app/node_modules/fastify/fastify.js at Module._resolveFilename (node:internal/modules/cjs/loader:939:15) at Module._load (node:internal/modules/cjs/loader:780:27) at Module.require (node:internal/modules/cjs/loader:1005:19) at require (node:internal/modules/cjs/helpers:102:18) at Object.<anonymous> (/app/node_modules/fastify/lib/error-serializer.js:6:20) at Module._compile (node:internal/modules/cjs/loader:1105:14) at Module._extensions..js (node:internal/modules/cjs/loader:1159:10) at Module.load (node:internal/modules/cjs/loader:981:32) at Module._load (node:internal/modules/cjs/loader:827:12) at Module.require (node:internal/modules/cjs/loader:1005:19) { code: 'MODULE_NOT_FOUND', requireStack: [ '/app/node_modules/fastify/lib/error-serializer.js', '/app/node_modules/fastify/lib/error-handler.js', '/app/node_modules/fastify/lib/reply.js', '/app/node_modules/fastify/fastify.js' ] } ``` ### Steps to Reproduce Use simple hello world: ```js import Fastify from 'fastify' const fastify = Fastify({ logger: true, }) fastify.get('/', async (request, reply) => { return { hello: 'world' } }) await fastify.listen({ port: 3000 }) ``` and start it using `node app.js` ### Expected Behavior _No response_
https://github.com/fastify/fastify/issues/3998
https://github.com/fastify/fastify/pull/4004
6a19e43b3e3df3280008e7571393992164e0b7ab
c60862875e2ed3dea04439e769982e5f1743ce2d
"2022-06-11T06:17:06Z"
javascript
"2022-06-13T09:53:48Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,995
["build/build-error-serializer.js", "lib/error-serializer.js", "package.json"]
SyntaxError: Illegal return statement
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 4.0.0 ### Plugin version _No response_ ### Node.js version 16.x ### Operating system macOS ### Operating system version (i.e. 20.04, 11.3, 10) 12.4 ### Description It seems that the generated file `error-serializer.js`is not valid Javascript. The last line of the file is a return statement outside of a function. ``` SyntaxError: Illegal return statement at Object.../../node_modules/fastify/lib/error-serializer.js [...] ``` Manually commenting the last line allow to launch even with Webpack. When I run my code using ts-node, no error is done. When the project is bundled with Webpack, one way or another, the whole code is evaluated, and the SyntaxError is thrown by node... I definitly have no idea why Webpack is evaluating this code so soon (I'm not familiar enough with its "magic"), but anyway, returning outside of a function is no valid JS and this Error could be thrown later in the code I guess... ### Steps to Reproduce Main script ```typescript import fastify from 'fastify'; (async () => { console.log('Start CLI !'); const fast = fastify({ logger: true }); await fast.listen({ port: 15987 }); })(); ```` Webpack config (both ts-loader or swc-loader throw the error) ```typescript const config: Configuration = { mode: 'development', target: 'node16', entry: './main.ts', context: FOLDER, module: { rules: [ { test: /\.ts$/, exclude: /(node_modules)/, use: { loader: 'swc-loader', options: { jsc: { parser: { syntax: 'typescript', }, target: 'es2016', }, }, }, }, // { // test: /\.ts$/, // exclude: /(node_modules)/, // use: { // loader: 'ts-loader', // }, // }, ], }, resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx'], }, }; ``` ### Expected Behavior No error 0:-)
https://github.com/fastify/fastify/issues/3995
https://github.com/fastify/fastify/pull/3996
9e21d2829ad611dd57aec22eccb202ed39cf4f6f
cf46dea8b21fbc2ecac94f56a6119d399b11167a
"2022-06-10T19:25:34Z"
javascript
"2022-06-10T22:01:13Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,994
["lib/reply.js", "test/404s.test.js", "test/internals/reply.test.js"]
[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the regression has not already been reported ### Last working version 3.29.0 ### Stopped working in version 4.0.0 ### Node.js version 18.2.0 ### Operating system Linux ### Operating system version (i.e. 20.04, 11.3, 10) Node.js running in Docker in an continuous integration environment ### πŸ’₯ Regression Report Since the update to `fastify` `v4.0.0` we receive randomly: ```sh Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at onSendEnd (/builds/my/project/node_modules/fastify/lib/reply.js:493:7) at onSendHook (/builds/my/project/node_modules/fastify/lib/reply.js:427:5) at fallbackErrorHandler (/builds/my/project/node_modules/fastify/lib/error-handler.js:124:3) at handleError (/builds/my/project/node_modules/fastify/lib/error-handler.js:54:5) at onErrorHook (/builds/my/project/node_modules/fastify/lib/reply.js:594:5) at _Reply.Reply.send (/builds/my/project/node_modules/fastify/lib/reply.js:119:5) at defaultErrorHandler (/builds/my/project/node_modules/fastify/lib/error-handler.js:85:9) at handleError (/builds/my/project/node_modules/fastify/lib/error-handler.js:58:18) at onErrorHook (/builds/my/project/node_modules/fastify/lib/reply.js:594:5) at _Reply.Reply.send (/builds/my/project/node_modules/fastify/lib/reply.js:119:5) at /builds/my/project/node_modules/fastify/lib/wrapThenable.js:23:15 ``` Sometimes it works ~~sometimes~~ most of the time not so I guess this is some kind of timing issue or race condition. All of our route handlers looks like this ```ts { async handler(_request, reply) { return reply.type('application/json').send({ foo: 'bar', }); }, method: 'GET' }; ``` or ```ts { async handler(request, reply) { await delay(3000); // simulate slow responses return reply.type('application/json').headers({ my: 'header' }).send({ foo: 'bar' }); }, method: 'GET' } ``` ### Steps to Reproduce Unfortunately I don't have any steps or repository to reproduce the issue. Our CI jobs are failing mostly all the time because of this. Locally I cannot reproduce the issue (I guess because my machine has more power and is faster) ### Expected Behavior _No response_
https://github.com/fastify/fastify/issues/3994
https://github.com/fastify/fastify/pull/4037
2324549996241a3f79de3eefb6898344dfbca1f2
44589bedd478252965d4924c628b0ccd11b4bb47
"2022-06-10T12:59:14Z"
javascript
"2022-06-19T12:12:21Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,980
["docs/Reference/Plugins.md", "docs/Reference/Routes.md"]
App-level version prefixing
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the feature has not already been requested ### πŸš€ Feature Proposal Support defining endpoint prefix globally for the whole app. I'm not sure whether per-route prefix should override or append the global one, open to opinions. If this is approved, I'll send a PR. ### Motivation Sometimes it is convenient to version whole application as a bundle (e. g. when you are routing across different app versions for backwards compatibility reason on a reverse proxy level), and do not handle versioning in a granular fashion per-route. ### Example ``` const fastify = require('fastify')({ globalPrefix: '/v1' }) ```
https://github.com/fastify/fastify/issues/3980
https://github.com/fastify/fastify/pull/3985
df3c9c314fdad6c7f99663b6bdd46fc663107c34
8ebb5b507e79906a7530c510594218de42fdc3e0
"2022-06-09T10:14:25Z"
javascript
"2022-06-10T13:08:32Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,977
["docs/Reference/Server.md", "lib/route.js", "lib/warnings.js", "test/default-route.test.js"]
`setDefaultRoute` should have the same signature as `setNotFoundHandler`
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the issue has not already been raised ### Issue The `setDefaultRoute` method takes a function of the signature `(RawRequest, RawReply) =>`. This is unlike all the other handlers, such as `setNotFoundHandler`, which expects a function like `(FastifyRequest, FastifyReply) =>`. This can lead to subtle bugs, as the input parameters have slightly different properties. **If possible, please fix this before releasing Fastify 4.** It would be a shame if this breaking change had to wait until Fastify 5. --- For context, my app passes the same handler to both `setDefaultRoute` and `setNotFoundHandler`: ```js app.setDefaultRoute(serveIndexHtmlHandler) app.setNotFoundHandler(serveIndexHtmlHandler) ``` All that each of these do is serve a static `index.html` file. Upon reading other issues in this repo, I perhaps don't need `setDefaultRoute` at all in my case; but if my app _did_ want a certain HTML file returned for `/` and a separate error HTML file returned for 404 routes, I would still need both (I think). The handler was initially implemented like this: ```js const serveIndexHtmlHandler = (request, reply) => { reply.sendFile('index.html') } ``` This works fine for `setNotFoundHandler`, but not `setDefaultRoute`, because `RawMessage` lacks the `sendFile` method. This took a substantial amount of debugging to discover.
https://github.com/fastify/fastify/issues/3977
https://github.com/fastify/fastify/pull/4480
dbef64289e0812749ed44f89658609c49fa0d696
fc81c707b819894bd84a903e5bbd23ec121e5a7b
"2022-06-08T16:38:41Z"
javascript
"2022-12-27T19:53:07Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,953
["lib/request.js", "test/decorator.test.js"]
Function decorators on request undefined in encapsulated context with other function decorators
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the regression has not already been reported ### Last working version 3.29.0 ### Stopped working in version 4.0.0-rc3 ### Node.js version 16 ### Operating system macOS ### Operating system version (i.e. 20.04, 11.3, 10) 12.3.1 ### πŸ’₯ Regression Report When using `decorateRequest` to add a function to request objects, this function isn't accessible in encapsulated contexts as soon as another function is added in the encapsulated context with `decorateRequest`. ### Steps to Reproduce A sample project demonstrating the issue: https://github.com/ocadoret/fastify-4-decorateRequest-issue ### Expected Behavior The function should be available in every encapsulated contexts.
https://github.com/fastify/fastify/issues/3953
https://github.com/fastify/fastify/pull/3954
846666e9dd95fda3f4a8242c4917c53955a523c1
bdcfd60f39b9299c6b74e0e14aa8e482e1cf630b
"2022-05-30T20:12:29Z"
javascript
"2022-05-31T07:59:56Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,951
["test/types/type-provider.test-d.ts", "types/type-provider.d.ts"]
Makes `FastifyTypeProviderDefault` output extendable globally
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the issue has not already been raised ### Issue From my TypeScript knowledge, if there was a way to override the `output` property type of `FastifyProviderDefault` ( https://github.com/fastify/fastify/blob/main/types/type-provider.d.ts#L15), we would be able to define our default Type Provider without requiring `fastify.withTypeProvider` everywhere. The issue here is the type being `unknown`, so I can't do this : ```ts import { TSchema, Static } from '@sinclair/typebox' declare module 'fastify' { interface FastifyTypeProviderDefault { output: this['input'] extends TSchema ? Static<this['input']> : never } } ``` It throws the following error : ``` Subsequent property declarations must have the same type. Property 'output' must be of type 'unknown', but here has type 'this["input"] extends TSchema ? Static<this["input"]> : never' ``` As `FastifyProviderDefault` is used everywhere in Fastify v4, just defining the `output` type of it in a declaration file would make TypeScript make the Type provider we want work everywhere out of the box, and I think it would be a good DX.
https://github.com/fastify/fastify/issues/3951
https://github.com/fastify/fastify/pull/3952
fa6cab8be1cdb838a03e0cd5d6c5a3b21f2eae40
9cbbd45f105260619e00aeb0b28ba772ea1f1e7e
"2022-05-30T17:40:54Z"
javascript
"2022-05-31T16:53:20Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,923
["test/types/route.test-d.ts", "types/route.d.ts", "types/type-provider.d.ts"]
[TypeScript] Allow returning `Reply` from handlers
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the feature has not already been requested ### πŸš€ Feature Proposal Currently, a handler is allowed to return `void | Promise<RouteGeneric['Reply'] | void> `, see https://github.com/fastify/fastify/blob/8a2b226d99c4a7d54a538bdbbb905a4fbbada6fa/types/route.d.ts#L66 This means that in an async handler, we can do this: ```js app.get('/', async (request, reply) => { const result = await someWork(); if (result) { return reply.status(201).send(); } return reply.send(); }); ``` However, if we remove the `async-await`, this is now a type error. The solution is to move the `return` to its own line, but ideally returning the `Reply` object would be allowed both wrapped in a `Promise` and not. (another workaround is `return Promise.resolve(reply.status(201).send())` which is even weirder). --- It seems to me this was considered in v4, but not acted upon (yet? πŸ˜€): https://github.com/fastify/fastify/blob/21682826ff3248268dfcdac65246658694ecac59/types/type-provider.d.ts#L95-L99 ### Motivation Being able to return `Reply` from synchronous handlers makes for more concise code, and would be consistent with asynchronous handlers. ### Example See "Feature Proposal"
https://github.com/fastify/fastify/issues/3923
https://github.com/fastify/fastify/pull/3941
1d5ede34f1a678746a5f917db0aa053c8c138bf7
4789f782a3afc0662229fcdaa2dbd0ad25ef390f
"2022-05-23T08:04:58Z"
javascript
"2022-05-29T07:49:38Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,919
["test/types/instance.test-d.ts", "types/instance.d.ts"]
Incorrect typings for getDefaultRoute
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 3.27.1 ### Plugin version _No response_ ### Node.js version 16.9 ### Operating system Linux ### Operating system version (i.e. 20.04, 11.3, 10) Arch with kernel 5.17.9 ### Description `FastifyInstance.getDefaultRoute` is incorrectly typed as a field of `DefaultRoute<RawRequest, RawReply>`, it should be a method with that same return type. ### Steps to Reproduce Try to use `getDefaultRoute` in typescript code; Typescript will warn about two required parameters (request and response) and the code will fail to compile. ### Expected Behavior The method is typed as having no parameters and returning a function that has the aforementioned two.
https://github.com/fastify/fastify/issues/3919
https://github.com/fastify/fastify/pull/3920
e92f7907f4cbcb12cfacd4d96978037b8d21b3d4
2ac0a666a8ef8eb4b8b79b38935265864238995f
"2022-05-21T19:11:39Z"
javascript
"2022-05-22T16:03:25Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,911
["docs/Reference/Server.md"]
What is the defaultRoute?
<!-- Before you submit a question we recommend you first look at our issue section (https://github.com/fastify/help/issues) to see if your question has already been answered. **Please read this entire template before posting any issue. If you ignore these instructions and post an issue here that does not follow the instructions, your issue might be closed, locked, and assigned the `missing discussion` label.** --> ## πŸ’¬ Question here I met the [getDefaultRoute](https://www.fastify.io/docs/latest/Reference/Server/#getdefaultroute) and [setDefaultRoute](https://www.fastify.io/docs/latest/Reference/Server/#setdefaultroute) methods in the documentation, but I didn't find a description of what it is anywhere. Could you explain what it is?
https://github.com/fastify/fastify/issues/3911
https://github.com/fastify/fastify/pull/3917
ad0d31a4c6d513abc9ef061cd0c950046b3d81b2
4862e772689101bb98569ec66bbee9fb9752b19d
"2022-05-16T09:31:57Z"
javascript
"2022-05-21T21:45:29Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,893
["docs/Reference/Routes.md", "fastify.js", "lib/route.js", "lib/server.js", "test/internals/server.test.js", "test/unsupported-httpversion.test.js"]
http2 request to a http1 fastify server hits "default handler for 404 did not catch this, this is likely a fastify bug"
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 3.29.0 ### Plugin version _No response_ ### Node.js version 14.19.2 ### Operating system macOS ### Operating system version (i.e. 20.04, 11.3, 10) 12.3 ### Description This issue has dogged me for as long as I've used fastify across OS's, node versions, and fastify versions. This message is logged as a warning many times a day: "the default handler for 404 did not catch this, this is likely a fastify bug, please report it" This particular issue relates to making an http2 request against a http1 fastify server with presumed prior knowledge of an http2 server. In my case, it is a bot/scanner causing these requests and log entries and I have no control over them. However, this is a larger issue in that fastify responds regardless of http version used. (Which http versions does fastify support?) ### Steps to Reproduce server: ```js 'use strict' const fastify = require('fastify')({ logger: true, http2: false }) fastify.get('/', function (request, reply) { reply.code(200).send({ hello: 'world' }) }) fastify.listen(3000) ``` run this: `curl --http2-prior-knowledge -vvvv http://127.0.0.1:3000/` additionally, fastify will respond with http/1.1 regardless of the request version: ``` telnet 127.0.0.1 3000 GET / HTTP/0.9 # note that HTTP/9.9 also has same result # result is hello world json ``` it's possible this is a node bug but i don't have the time atm to research. ### Expected Behavior http2 requests to an http1 server should not lead to warning log entries. it seems like maybe fastify should respond with [505](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/505)? though i'm not sure... currently, it just closes the connection, which might be right. also -- unsupported http versions should be ignored/rejected. fastify will send an http1.1 response to any request for any http version >= 0.0 and <= 9.9
https://github.com/fastify/fastify/issues/3893
https://github.com/fastify/fastify/pull/3912
42e8e843e08797356f8f457e0dcb263cc8912707
ad0d31a4c6d513abc9ef061cd0c950046b3d81b2
"2022-05-09T21:09:12Z"
javascript
"2022-05-21T18:09:07Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,883
[".github/workflows/ci.yml", "README.md", "docs/Guides/Write-Plugin.md"]
Replace Snyk webhook with GitHub's own dependency review action
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the issue has not already been raised ### Issue When opening a PR in Fastify repos a Snyk webhook is triggered, which checks if the PR has added any vulnerable dependencies: ![image](https://user-images.githubusercontent.com/43814140/167102430-dc1f936a-0702-4210-9dd8-924b46f4868f.png) GitHub have introduced their [own GitHub Action](https://github.com/actions/dependency-review-action) that does the same thing. With this we can remove the Snyk webhook from https://github.com/fastify/fastify/settings/hooks, and it'd be nice to get rid of another third-party dependency that may go down and cause issues, like how we removed Coveralls for similar reasons.
https://github.com/fastify/fastify/issues/3883
https://github.com/fastify/fastify/pull/3884
0e01f7f4a4fd38fde443f34c569437c28ec584ee
3abb3c67a6d8acd49e913edbb314a8875073ab4c
"2022-05-06T09:20:52Z"
javascript
"2022-05-08T06:38:32Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,720
[".github/workflows/ci.yml", "README.md", "package.json"]
Drop Coveralls?
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the issue has not already been raised ### Issue I don't think Coveralls is checking things correctly. When we look at the CI results for commit https://github.com/fastify/fastify/pull/3712/commits/5a77a6b9a93d0b1e1c830a8c9bce997b2bcc7646 we can see that Coveralls is suggesting coverage remains at 100% for all OSes, but `tap` is saying otherwise: https://coveralls.io/jobs/94867280 ![fastify - Vivaldi 2022-02-20 18-57-15](https://user-images.githubusercontent.com/321201/154870207-1abffa81-21bf-4d6e-b6a6-7297c8ba1437.png) https://github.com/fastify/fastify/runs/5267302531?check_suite_focus=true ![fastify - Vivaldi 2022-02-20 18-58-03](https://user-images.githubusercontent.com/321201/154870226-abfc2622-d256-4933-b3cb-5f476dfa44c1.png) With #3717 and #3719, we will have coverage reports attached to the GitHub Actions panel itself. We'd have to download the artifacts to inspect what coverage is missing, instead of browsing a hosted website (Coveralls), but at least it'd be consistent and accurate(?).
https://github.com/fastify/fastify/issues/3720
https://github.com/fastify/fastify/pull/3722
5db8c3973d9a26fe3888f918f99e9cf313e03ef8
16c38a9423b1a608099219e1e900b2f63f01739b
"2022-02-21T00:00:02Z"
javascript
"2022-02-21T20:05:04Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,709
["package.json", "test/schema-special-usage.test.js"]
pnpm tests broken for v4
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version mian branch / v4 ### Plugin version _No response_ ### Node.js version v16 ### Operating system Linux ### Operating system version (i.e. 20.04, 11.3, 10) gituhb actions ### Description Our pnpm tests are failing https://github.com/fastify/fastify/runs/5249770711?check_suite_focus=true. ### Steps to Reproduce Check Github actions ### Expected Behavior _No response_
https://github.com/fastify/fastify/issues/3709
https://github.com/fastify/fastify/pull/3714
3cbc1ed99fde956314b100dec17b2d23ffeb37da
91edc1f4060af02fffc9d76543b0521f7b8913be
"2022-02-18T15:59:43Z"
javascript
"2022-02-19T17:39:05Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,702
["lib/handleRequest.js", "test/404s.test.js"]
Not found handler not called when request HTTP method is not supported
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 3.27.1 ### Plugin version _No response_ ### Node.js version 16.13.1 ### Operating system macOS ### Operating system version (i.e. 20.04, 11.3, 10) 11.6.3 ### Description When handling a request that uses an HTTP method that Fastify does not support (e.g. `PURGE`), Fastify responds with a 404, but this response is hard to customize because: 1. The handler set with `setNotFoundHandler` is not called 2. The handler set with `setErrorHandler` _is_ called, but the error passed in does not have a `statusCode` property, nor `name: "FastifyError"` etc, so it's not reliably distinguishable from an unhandled error from somewhere else. https://github.com/fastify/fastify/blob/9b1877626bb345f3a4746d678bc56b0bb23b7f2a/lib/handleRequest.js#L57-L58 If possible, calling the notFoundHandler seems like the most intuitive approach to me. Otherwise I think calling `reply.send(new FST_ERR_NOT_FOUND())` instead of a plain `Error` would be acceptable. Let me know if I can clarify anything. Thank you! ### Steps to Reproduce Say I want a plain text response instead of JSON: ```js const fastify = require('fastify')(); fastify.setNotFoundHandler((request, reply) => { reply.status(404).send("Resource not found"); }); fastify.setErrorHandler((error, request, reply) => { reply.status(error.statusCode || 500).send(error.message); }); fastify.listen(3000); ``` ```sh curl -vX PURGE localhost:3000 ``` ### Expected Behavior Response status: 404 Response body: `Resource not found`
https://github.com/fastify/fastify/issues/3702
https://github.com/fastify/fastify/pull/3705
b4ea2e92bda4a421b7d836a742bf61c17d9c7570
21682826ff3248268dfcdac65246658694ecac59
"2022-02-15T00:40:02Z"
javascript
"2022-02-17T21:58:32Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,691
[".github/workflows/package-manager-ci.yml"]
`package-manager-ci` is currently failing
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the issue has not already been raised ### Issue Since this PR #3682, `package-manager-ci` GitHub Action is failing. It fails because ESLint v8 requires Node.js >= 12.22.0, and it is running on Node.js v10 (so that would naturally be fixed by #3482). This is a tracking issue so we can fix this. Several comments : - Is it necessary to run linting multiple times depending on the Node.js version? It might be better to run linting only once using maybe Node.js `lts/*` version. - This issue could be avoided if we would ran that action also on PRs not only for `main` branch as it is currently the case: https://github.com/fastify/fastify/blob/8a4a9b09bdf01ed26b7c9732ad25bcfdac4f5ec1/.github/workflows/package-manager-ci.yml#L3-L6 - Just because of curiosity, is it necessary to test depending on the `package-manager`, is `fastify` work differently across different package managers?
https://github.com/fastify/fastify/issues/3691
https://github.com/fastify/fastify/pull/3692
8a4a9b09bdf01ed26b7c9732ad25bcfdac4f5ec1
36d20ae414e7bcf0b83cfc653fd902cb70e81138
"2022-02-08T11:33:59Z"
javascript
"2022-02-08T16:58:35Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,626
["test/custom-parser.test.js"]
test (ci): `custom-parser.test.js` is randomly failing with a 503 Service Unavailable
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the issue has not already been raised ### Issue Hello. Following this https://github.com/fastify/fastify/pull/3622#issuecomment-1013895770 - [Failed CI Run Log](https://github.com/fastify/fastify/runs/4833023509?check_suite_focus=true#step:6:1720). This test is randomly failing on fastify CI runs returning a 503 HTTP Status code instead of the expected 200 at line 1381. https://github.com/fastify/fastify/blob/ee795d3c61fdd87f75562bd5a977286cd01dea58/test/custom-parser.test.js#L1317-L1386 Possible fix: https://github.com/darkgl0w/fastify/commit/e8a138c27a11c9ed6d5db2cd4b6645e966e2bb61 Switching from `simple-get` to `await fastify.inject`, using `teardown()` to close the server, and making use of an `async/await` tap callback seems to solve the issue (needs to be confirmed by a couple runs on fastify CI).
https://github.com/fastify/fastify/issues/3626
https://github.com/fastify/fastify/pull/3627
4d870895b4c732718119b278648e48ce01b5e23b
dd7de59d933005db2206b500d511ca5c57bea5c4
"2022-01-16T18:34:04Z"
javascript
"2022-01-17T13:07:50Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,625
["docs/Reference/Request.md", "fastify.js", "lib/route.js", "lib/symbols.js", "test/versioned-routes.test.js"]
Accept-Version is always undefined
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 3.25.3 ### Plugin version _No response_ ### Node.js version 16.13.1 ### Operating system Linux ### Operating system version (i.e. 20.04, 11.3, 10) Ubuntu 20.04.3 LTS ### Description I don't want to use [constraints](https://www.fastify.io/docs/latest/Reference/Routes/#constraints). ### Steps to Reproduce ```js const fastify = require('fastify') const server = fastify() server.addHook('onRequest', async (req, reply) => { console.log(req.headers) }) server.listen(8080) ``` ```sh curl \ --header 'Accept-Version: 1.0' \ http://localhost:8080 ``` ``` { host: 'localhost:8080', 'user-agent': 'curl/7.68.0', accept: '*/*', 'accept-version': undefined } ``` ### Expected Behavior ``` { host: 'localhost:8080', 'user-agent': 'curl/7.68.0', accept: '*/*', 'accept-version': '1.0' } ```
https://github.com/fastify/fastify/issues/3625
https://github.com/fastify/fastify/pull/3630
afdd647c88422c5214297ff3156da078ab9819f1
4d870895b4c732718119b278648e48ce01b5e23b
"2022-01-16T16:00:40Z"
javascript
"2022-01-17T08:23:04Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,621
[".github/workflows/ci.yml", "package.json"]
CI: run lint once
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the feature has not already been requested ### πŸš€ Feature Proposal Refactor the package.json scripts and the CI to run the linter only once. (now it runs for every node version and OS) This will: - speed up a bit the pipeline - improve the readability ### Motivation This output is confusing: ![image](https://user-images.githubusercontent.com/11404065/149630306-8b7bbbda-0b3f-4623-8bc2-c1d1115c2813.png) ### Example _No response_
https://github.com/fastify/fastify/issues/3621
https://github.com/fastify/fastify/pull/3623
93fe532986b96ae28a087b2ec385a8abb16cce55
ae3320de7fd9ba2e6d68349c89f28de643b49f16
"2022-01-15T16:52:33Z"
javascript
"2022-01-16T14:17:40Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,620
["test/404s.test.js", "test/types/hooks.test-d.ts", "types/hooks.d.ts"]
A change in Fastify hook types broke our hooks
<!-- Before you submit a question we recommend you first look at our issue section (https://github.com/fastify/help/issues) to see if your question has already been answered. **Please read this entire template before posting any issue. If you ignore these instructions and post an issue here that does not follow the instructions, your issue might be closed, locked, and assigned the `missing discussion` label.** --> ## πŸ’¬ A change in Fastify hook types broke our hooks When upgrading Fastify we encountered strange problems with our `preHandler`-hooks. Narrowing down, the problem was introduced when upgrading from 3.18.0 to 3.18.1, and more specifically it was this change: https://github.com/fastify/fastify/pull/3143/files Given a custom hook ```ts // A hook that does nothing, just to demonstrate the issue with the types const myHook: preHandlerAsyncHookHandler< RawServerBase, RawRequestDefaultExpression<RawServerBase>, RawReplyDefaultExpression<RawServerBase>, {} > = async (_req, _res) => undefined; ``` and using it like this ```ts interface TestRoute extends RouteGenericInterface { readonly Reply: { ok: boolean }; } const testRoutes: FastifyPluginAsync = (instance) => { instance.addHook("preHandler", myHook); instance.route<TestRoute>({ method: "GET", url: "/", handler: async (_req, res) => res.send({ ok: true }), }); return Promise.resolve(); }; ``` we get this error ``` src/testRoutes.ts:27:20 - error TS2769: No overload matches this call. The last overload gave the following error. Argument of type '"preHandler"' is not assignable to parameter of type '"onClose"'. 27 instance.addHook("preHandler", myHook); ~~~~~~~~~~~~ node_modules/fastify/types/instance.d.ts:307:3 307 addHook( ~~~~~~~~ 308 name: 'onClose', ~~~~~~~~~~~~~~~~~~~~ 309 hook: onCloseHookHandler<RawServer, RawRequest, RawReply, Logger> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 310 ): FastifyInstance<RawServer, RawRequest, RawReply, Logger>; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The last overload is declared here. ``` I set up a minimal project demonstrating just this issue: https://github.com/anttti/fastify-types Just run `yarn && yarn build` to see the error. What are we doing wrong? ## Your Environment - *node version*: 14.15.4 - *fastify version*: 3.18.1 and onwards - *os*: Mac, but issue seems to be platform independent
https://github.com/fastify/fastify/issues/3620
https://github.com/fastify/fastify/pull/3622
dd7de59d933005db2206b500d511ca5c57bea5c4
b0b0a7a2dc8578a54294241fd512197cac55dff8
"2022-01-14T10:52:24Z"
javascript
"2022-01-17T18:55:56Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,610
["docs/Guides/Prototype-Poisoning.md"]
Update prototype poisoning doc
I think you should remove all the non-technical relevant stuff and instead of the strong attribution, simply replace it with "Based on the article ... by Eran Hammer". I'm giving you full permission to use this text as you find useful. Don't be shy to change it. _Originally posted by @hueniverse in https://github.com/fastify/fastify/issues/3609#issuecomment-1009638148_
https://github.com/fastify/fastify/issues/3610
https://github.com/fastify/fastify/pull/4651
0042248c3a1665a1e2ebc60b34c8bab7c2710518
831500088f5ba48f02129db2fc822946d40597ff
"2022-01-11T13:27:30Z"
javascript
"2023-04-19T07:58:57Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,589
["lib/reply.js", "test/internals/handleRequest.test.js", "test/internals/reply.test.js"]
Remove .writableEnded fallback for Node v12
https://github.com/fastify/fastify/blob/c56828bcfb7bccdfb00cdd7af890435e62c9a57b/lib/reply.js#L70-L78 should become ```js // We are checking whether reply was hijacked or the response has ended. return (this[kReplyHijacked] || this.raw.writableEnded) === true ``` and tests adjusted/removed. https://github.com/fastify/fastify/blob/c56828bcfb7bccdfb00cdd7af890435e62c9a57b/test/internals/reply.test.js#L1804-L1818 _Originally posted by @sergiz in https://github.com/fastify/fastify/issues/3532#issuecomment-1001109950_
https://github.com/fastify/fastify/issues/3589
https://github.com/fastify/fastify/pull/3590
50d49831837eca283903f3f481570a01d8cc92d5
7dbfbe1fa8d7597297d6677a13b748924f097aeb
"2022-01-03T15:42:01Z"
javascript
"2022-01-03T19:30:24Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,570
["lib/contentTypeParser.js", "test/als.test.js"]
Async context is broken for POST requests when its created inside 'onRequest' hook
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 3.25.1 ### Plugin version 5.3.0 ### Node.js version 16.10 ### Operating system macOS ### Operating system version (i.e. 20.04, 11.3, 10) 12.0 ### Description When `next` handler is executed inside `AsyncLocalStorage`, the context gets lost for requests with payload. Post request without a payload will work fine. Originally discovered in nestjs project, connected issue: https://github.com/nestjs/nest/issues/8837 Note that I had similar issues with express middlewares too and they were caused by the middleware being registered too early, before the body parser. Not sure how that works in fastify, but I would say here the issue will be very similar. ### Steps to Reproduce storage.ts ```ts import { AsyncLocalStorage } from 'async_hooks'; export const storage = new AsyncLocalStorage<any>(); export const state = { counter: 0 }; ``` main.ts ``` const fastify = Fastify({ logger: true }); await fastify.register(middie); fastify.use((req: any, res: any, next: any) => { const id = state.counter++; console.log('In Middleware with id ' + id); storage.run({ id }, next); }); fastify.get('/', function (request, reply) { const id = storage.getStore()?.id; console.log('get', id); reply.send({ id }); }); fastify.post('/', function (request, reply) { const id = storage.getStore()?.id; console.log('post', id); reply.send({ id }); }); ``` minimal repro here: https://github.com/B4nan/fastify-middie-als ``` yarn yarn start # get request works fine, will print the context ID as a response curl localhost:3000 # fails to get the ID from ALS if there is actual payload curl -d '{}' -H 'Content-Type: application/json' localhost:3000 # without the payload it will work fine (even for post request) curl -X POST localhost:3000 ``` ### Expected Behavior The async context should not be broken, requests with payload should work the same as those without it in this manner.
https://github.com/fastify/fastify/issues/3570
https://github.com/fastify/fastify/pull/3571
006bd09a1559c00fab519d2104e672bf640ff282
fa432f0a1a8c9ab7366d1b16b7d332ad03b12ef8
"2021-12-22T13:00:47Z"
javascript
"2021-12-23T11:40:52Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,563
[".github/workflows/website.yml"]
Add website build "on release" to website.yml workflow
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the feature has not already been requested ### πŸš€ Feature Proposal I think as part of the current workflow, we could add a website build as suggested in the title everytime something in `docs` has been changed. ### Motivation Keep in sync the `docs` with the website ### Example _No response_
https://github.com/fastify/fastify/issues/3563
https://github.com/fastify/fastify/pull/3572
89192faa13d4b30d90cc4960812b0c5e74d69f62
006bd09a1559c00fab519d2104e672bf640ff282
"2021-12-21T12:44:15Z"
javascript
"2021-12-23T09:39:58Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,558
["lib/decorate.js", "test/decorator.test.js"]
Regression in 3.25.0 for dependency checking`decorateReply`
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the regression has not already been reported ### Last working version 3.24.1 ### Stopped working in version 3.25.0 ### Node.js version 16.x ### Operating system macOS ### Operating system version (i.e. 20.04, 11.3, 10) 11.6.2 ### πŸ’₯ Regression Report I've got error after upgrade to 3.25.0 from 3.24.0: ```json { "name": "FastifyError", "code": "FST_ERR_DEC_MISSING_DEPENDENCY", "message": "The decorator is missing dependency 'clearCookie'." } ``` I think that depend on https://github.com/fastify/fastify/pull/3527 ### Steps to Reproduce - Example 3.24.0 https://codesandbox.io/s/fastify-3-24-ljjyx?file=/src/build.js - Example 3.25.0 https://codesandbox.io/s/fastify-3-25-t7kzn?file=/src/build.js ```js const fastify = require("fastify"); const fastifyPlugin = require("fastify-plugin") const authPlugin = fastifyPlugin(async (instance) => { instance.decorateReply( "clearAuthCookie", function clearAuthCookie() { this.log.debug("Call reply.clearAuthCookie [getter]"); return true; }, ["clearCookie"] ) }, { name: 'auth', dependencies: ['fastify-cookie'], }) function build(opts) { const app = fastify(opts); app.register(require("fastify-cookie")); app.register(authPlugin); app.get("/", async (request, reply) => { return { hello: "world" }; }); return app; } ``` ### Expected Behavior _No response_
https://github.com/fastify/fastify/issues/3558
https://github.com/fastify/fastify/pull/3560
6cdbbd3cd0aa75c8c2811a90e5923753ae77bea1
a1c9cee010559da4985448d303dbe51be1c231d4
"2021-12-21T05:46:28Z"
javascript
"2021-12-21T10:23:41Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,502
["README.md", "docs/Middleware.md", "docs/Migration-Guide-V4.md", "fastify.js", "lib/errors.js", "test/middleware.test.js"]
Remove app.use()
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the feature has not already been requested ### πŸš€ Feature Proposal I think we should be removing `app.use()` in the `next` release, i.e. https://github.com/fastify/fastify/blob/a17482959d4a4a9fab31926d0443ecd13d078c99/fastify.js#L327-L330. ### Motivation We should not be encouraging people to use middlewares. Both `middie` and `fastify-express` will still be there and maintained. ### Example _No response_
https://github.com/fastify/fastify/issues/3502
https://github.com/fastify/fastify/pull/3506
6975c8f772ae0f439f4382add15e1ef96c805f08
e488a09fd1044ee3446925a8f368bb701725604c
"2021-11-29T15:49:56Z"
javascript
"2021-12-04T11:37:36Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,500
["docs/Ecosystem.md"]
`middie` missing from ecosystem docs
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the issue has not already been raised ### Issue Should [middie](https://github.com/fastify/middie) be included in the core section?
https://github.com/fastify/fastify/issues/3500
https://github.com/fastify/fastify/pull/3501
89aa2c0c4712651ac30a61ec87b2c05abbc3d0c2
d45be0d7dfe4221ce8e31bb636039832afb29a9b
"2021-11-29T15:05:00Z"
javascript
"2021-11-29T15:54:39Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,461
["lib/logger.js", "test/logger.test.js"]
Clear error reporting?
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the feature has not already been requested ### πŸš€ Feature Proposal I feel that a clearer error reporting system would be helpful, especially in routing and logging. ### Motivation I once tried logging a subset of the `req` object, not understanding the serializer. Then I got an error saying `cannot get property 'accept-version' of undefined`. Errors like this make it hard for beginner developers to use. ### Example Code: ```node ... fastify.setErrorHandler(async (err, req, res) => { req.log.error({ req: { method: req.method, url: req.url } }); ... }); ... ``` Current error: ``` Cannot get property 'accept-version' of undefined. ``` Proposed error: ``` Invalid request in serializer. ``` Or something similar.
https://github.com/fastify/fastify/issues/3461
https://github.com/fastify/fastify/pull/3465
9814c3828ff020a90bcb364cea06d2cee5f4b1bc
f97cdfb79e4067b6a75784667c0e4b7b9fceb8bb
"2021-11-19T00:22:14Z"
javascript
"2021-11-19T12:58:43Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,448
["test/types/instance.test-d.ts", "types/instance.d.ts"]
Instance listen method definition - callback's Error should be nullable
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 3.22.0 ### Plugin version _No response_ ### Node.js version 14.18.1 ### Operating system Linux ### Operating system version (i.e. 20.04, 11.3, 10) Ubuntu 20.04.3 LTS ### Description After registering a new [FastifyInstance](https://github.com/fastify/fastify/blob/ea0e90137406db6e601c13c312ede4aeefb03235/types/instance.d.ts#L22) we usually use the `listen` method to start receiving requests. The `listen` method definition is declaring the callback's `error` as a non nullable `Error` type but instead when we spin up the server without any problem, that error is null. Actual `listen` method ts definition: ```ts listen(port: number | string, address: string, backlog: number, callback: (err: Error, address: string) => void): void; listen(port: number | string, address: string, callback: (err: Error, address: string) => void): void; listen(port: number | string, callback: (err: Error, address: string) => void): void; listen(port: number | string, address?: string, backlog?: number): Promise<string>; listen(opts: { port: number; host?: string; backlog?: number }, callback: (err: Error, address: string) => void): void; listen(opts: { port: number; host?: string; backlog?: number }): Promise<string>; ``` The major problem is that the linter (eslint) with the rule [@typescript-eslint/no-unnecessary-condition](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-unnecessary-condition.md) will incur in an error because is expecting an `Error` and should never be null. ### Steps to Reproduce Enabling the typescript linter rule: ```json { "parser": "@typescript-eslint/parser", "parserOptions": { "project": "./tsconfig.json", "ecmaVersion": 12, "sourceType": "module" }, "ignorePatterns": ["build/*"], "plugins": ["@typescript-eslint"], "extends": [ "standard", "plugin:@typescript-eslint/recommended", "plugin:@typescript-eslint/recommended-requiring-type-checking", "prettier" ], "rules": { "@typescript-eslint/no-unnecessary-condition": "error", } } ``` ```ts server.listen(port, host, (err, address) => { if (err) { // Unnecessary conditional, value is always truthy.eslint@typescript-eslint/no-unnecessary-condition server.log.error(err); process.exit(); } console.log(`Server listening at ${address}`); }); ``` ### Expected Behavior I think the definition should declare the callbacks `error` as nullable to respect the real `listen` method behavior and avoiding using workarounds to make the linter be successful.
https://github.com/fastify/fastify/issues/3448
https://github.com/fastify/fastify/pull/3449
5b6b583cd4db573a6134c280963b1f7d6e22128d
f15c557ae1b44e8bad40d2789a8e2e9c67e7c013
"2021-11-16T09:09:53Z"
javascript
"2021-11-16T18:46:11Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,430
["lib/reply.js", "lib/symbols.js", "test/internals/reply.test.js"]
Calling Reply.getResponseTime() multiple times results in different times
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 3.22.0 ### Plugin version _No response_ ### Node.js version 14.18.1 ### Operating system macOS ### Operating system version (i.e. 20.04, 11.3, 10) 11.6.1 ### Description Calling Reply.getResponseTime() multiple times results in different values. Optimally the response time should be set at some point and the function simply return that value. ### Steps to Reproduce The function uses Date.now() to calculate the value every time it is called. ### Expected Behavior The response time should be the same for one requests independent of when you are calling the getResponseTime function.
https://github.com/fastify/fastify/issues/3430
https://github.com/fastify/fastify/pull/3431
9a6dd4de685d1a55e63e731408ad1087da252250
acc8c22d0099b11315df71c22e4bea08bda9177c
"2021-11-11T09:19:22Z"
javascript
"2021-11-12T21:08:28Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,421
["docs/Type-Providers.md"]
Typebox example from documentation throws error strict mode: unknown keyword: "kind"
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 4.0.0 ### Plugin version _No response_ ### Node.js version 14.x ### Operating system Linux ### Operating system version (i.e. 20.04, 11.3, 10) 5.10.70 ### Description Hi, I'm trying to use the new Type Providers example from. https://github.com/fastify/fastify/blob/next/docs/Type-Providers.md ### Steps to Reproduce ``` ts server.get( '/route', { schema: { querystring: Type.Object({ foo: Type.Number(), bar: Type.String(), }), }, }, (request, reply) => { // type Query = { foo: number, bar: string } const { foo, bar } = request.query; // type safe! }, ) ``` This will throw the following error: ``` (node:425517) UnhandledPromiseRejectionWarning: FastifyError: Failed building the validation schema for GET: /route, due to error strict mode: unknown keyword: "kind" at Boot.<anonymous> (/fastify-objection-starter/node_modules/fastify/lib/route.js:276:21) ``` The error can be fixed by adding `Type.Strict()`. ``` ts server.get( '/route', { schema: { querystring: Type.Strict( Type.Object({ foo: Type.Number(), bar: Type.String(), }), ), }, }, (request, reply) => { // type Query = { foo: number, bar: string } const { foo, bar } = request.query; // type safe! }, ) ``` The issue is caused by `kind: Symbol(ObjectKind)` when omitting `Type.Strict(...)` ``` ts { kind: Symbol(ObjectKind), type: 'object', properties: { foo: { kind: Symbol(NumberKind), type: 'number' }, bar: { kind: Symbol(StringKind), type: 'string' } }, required: [ 'foo', 'bar' ] } ``` ### Expected Behavior I'm not sure what the expected behavior is. Updating documentation to use `Type.Strict(...)` could be a solution or perhaps there is also a option that strict mode ignores the `Symbol(ObjectKind)` property. cc @sinclairzx81
https://github.com/fastify/fastify/issues/3421
https://github.com/fastify/fastify/pull/3437
2965a38df7a7c3c6708494c05840e548d9ab148f
795e83a710abee5e4c0351e34e8d743b1de44078
"2021-11-05T13:51:08Z"
javascript
"2021-11-13T10:25:42Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,419
["lib/logger.js", "test/internals/logger.test.js"]
The server crashes if the socket is undefined and try to access attributes
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 3.22.1 ### Plugin version _No response_ ### Node.js version 14.15.1 ### Operating system Linux ### Operating system version (i.e. 20.04, 11.3, 10) Docker image node:14 ### Description The app restart randomly with this error: ``` Cannot read property 'remoteAddress' of null stack TypeError: Cannot read property 'remoteAddress' of null at _Request.get (/home/app/node_modules/fastify/lib/request.js:161:26) at Object.asReqValue [as req] (/home/app/node_modules/fastify/lib/logger.js:55:26) at Pino.asJson (/home/app/node_modules/pino/lib/tools.js:118:50) at Pino.write (/home/app/node_modules/pino/lib/proto.js:202:28) at Pino.LOG [as error] (/home/app/node_modules/pino/lib/tools.js:55:21) at defaultErrorHandler (/home/app/node_modules/fastify/fastify.js:81:15) at handleError (/home/app/node_modules/fastify/lib/reply.js:553:20) at onErrorHook (/home/app/node_modules/fastify/lib/reply.js:524:5) at _Reply.Reply.send (/home/app/node_modules/fastify/lib/reply.js:128:5) at onErrorDefault (/home/app/node_modules/fastify-reply-from/index.js:209:9) ``` Checking the code it seems that the `socket`Β attribute of the request is `undefined` and fails when try to log the error in this accessor: ``` ip: { get () { return this.socket.remoteAddress } }, ``` ### Steps to Reproduce I couldn't find a way to reproduce the issue. It happens only inside a docker pod in a Kubernetes infrastructure. ### Expected Behavior _No response_
https://github.com/fastify/fastify/issues/3419
https://github.com/fastify/fastify/pull/3422
53fe09f6664776330054a968237f04701ecdc6b7
692fe4f8e083c2509de67c1813a52b18f62df4d9
"2021-11-04T15:49:26Z"
javascript
"2021-11-07T17:24:22Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,409
["docs/Reply.md"]
Document special case for setting 'set-cookie' header
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the issue has not already been raised ### Issue This issue is to confirm the existing behavior is intended and if so, a request to better document the behavior. Fastify's docs for `reply.header(key, value)` are quite concise and only say the following: >Sets a response header. If the value is omitted or undefined, it is coerced to `''`. >For more information, see [`http.ServerResponse#setHeader`](https://nodejs.org/dist/latest-v14.x/docs/api/http.html#http_response_setheader_name_value). If you click through to the official Node.js docs, you'll see this excerpt: >If this header already exists in the to-be-sent headers, its value will be replaced. This led me to believe the following code would only send a single cookie with a key of `blueberry`: ``` res.header('set-cookie', 'apple=1'); res.header('set-cookie', 'blueberry=2'); ``` But in fact, both cookies are sent. To clarify, I actually prefer Fastify's behavior, but it definitely confused me because I had code like the following, and it was duplicating headers, and even though i read and reread the docs, I didn't realize what was happening until I actually looked at Fastify's code. ``` res.header('set-cookie', [ ...(res.getHeader('set-cookie') ?? []), cookie.serialize(/* my really awesome cookie */), ]); ``` Relevant Fastify source code: https://github.com/fastify/fastify/blob/main/lib/reply.js#L237 If this is intended behavior, I can try to send a PR later this week to add a one-liner to the docs calling out `set-cookie` having special behavior.
https://github.com/fastify/fastify/issues/3409
https://github.com/fastify/fastify/pull/3470
b55ec60047171c2c94753a08f01521464bff998e
1552f7df18231670ae8572a99e1151064b80ae8f
"2021-10-31T21:28:15Z"
javascript
"2021-11-21T10:44:55Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,408
["package.json", "test/http2/constraint.test.js"]
Host Constraints not working when http2 enabled
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 3.22.1 ### Plugin version _No response_ ### Node.js version 16.13.0 ### Operating system macOS ### Operating system version (i.e. 20.04, 11.3, 10) 21.0.1 ### Description Host constraints will give a 404 error regardless of domain used, when http2 is turned on. Using the inject method as described in the [documentation](https://www.fastify.io/docs/latest/Routes/) seems to work, but when I try the URL in the browser it doesn't. Turning off http2 fixes the problem. Possibly related to [this](https://github.com/fastify/fastify/issues/2112)? ### Steps to Reproduce 1. Enable http2. 2. Use host constraints as described in the documentation like this: `fastify.route({ method: 'GET', url: '/test', constraints: { host: 'my.testdomain.co' }, handler: function (request, reply) { reply.send('hello world from my.testdomain.co') } })` 3. Try to access 'https://my.testdomain.co/test' in a browser. (inject code mentioned in documentation works, but browser doesn't) ### Expected Behavior When entering 'https://my.testdomain.co/test' in my browser I expect to see the message 'hello world from my.testdomain.co'.
https://github.com/fastify/fastify/issues/3408
https://github.com/fastify/fastify/pull/3504
627f7bde9a5d483f68b765668ea4fe964ab41cbf
b2e9b7843742029547d8f6ba3a3078c48dce7caa
"2021-10-31T18:55:21Z"
javascript
"2021-12-16T11:13:22Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,405
["build/build-validation.js", "docs/Server.md", "fastify.d.ts", "fastify.js", "lib/configValidator.js", "lib/server.js", "test/internals/initialConfig.test.js", "test/requestTimeout.test.js"]
Provide requestTimeout feature
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the feature has not already been requested ### πŸš€ Feature Proposal Didn't find description in docs how to set `requestTimeout`, which will limit the time for each request. I think it is important to add this. I can send a PR later today if you accept this proposal. ### Motivation There is vulnerability in Node that can be fixed be setting `requestTimeout` to > 0 https://nodejs.org/en/blog/vulnerability/september-2020-security-releases/ context: https://github.com/nodejs/node/issues/40493#issuecomment-954659850 ### Example https://nodejs.org/api/http.html#serverrequesttimeout
https://github.com/fastify/fastify/issues/3405
https://github.com/fastify/fastify/pull/3407
eed0121f35eafc99deccded945cec1c10f8954c0
9e4b7cc12c4beff53d08d6512d6347920a1f9842
"2021-10-31T10:06:45Z"
javascript
"2021-10-31T18:52:12Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,403
["docs/Reference/Type-Providers.md", "docs/Reference/TypeScript.md"]
Include type provider to Typescript section
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the issue has not already been raised ### Issue The PR https://github.com/fastify/fastify/pull/3398 added a new feature in typescript that's `Type Providers`. We should add a link in `Typescript.md` to point to `Type-Providers.md` or even merge both documents as suggested here: https://github.com/fastify/fastify/pull/3398#discussion_r739515269
https://github.com/fastify/fastify/issues/3403
https://github.com/fastify/fastify/pull/3853
2c3aa4fd379a40389271c005383b9d444f32fcd4
118f435788169f256661341814bb60b24f497e89
"2021-10-30T12:54:41Z"
javascript
"2022-05-04T16:28:51Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,399
["package.json", "test/404s.test.js", "test/custom-parser.test.js", "test/hooks.test.js", "test/route.test.js", "test/router-options.test.js"]
Update find-my-way for v4
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the feature has not already been requested ### πŸš€ Feature Proposal Update! ### Motivation _No response_ ### Example _No response_
https://github.com/fastify/fastify/issues/3399
https://github.com/fastify/fastify/pull/3515
e488a09fd1044ee3446925a8f368bb701725604c
b045c7ea9bbc2e31f4af0e55ead857162e935998
"2021-10-28T13:32:15Z"
javascript
"2021-12-09T08:40:37Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,389
["docs/Getting-Started.md", "docs/Request.md"]
Improve getting started documentation to include req.body
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the feature has not already been requested ### πŸš€ Feature Proposal Improved our documentation so it’s immediate for newcomers that the case described in https://github.com/fastify/fastify/discussions/3388 is not needed at all. ### Motivation _No response_ ### Example _No response_
https://github.com/fastify/fastify/issues/3389
https://github.com/fastify/fastify/pull/3436
acc8c22d0099b11315df71c22e4bea08bda9177c
cdc3c690ab7bbecdf5b18bae68f9684deb982641
"2021-10-22T09:44:58Z"
javascript
"2021-11-13T07:23:42Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,377
[".github/workflows/ci.yml", "test/bundler/esbuild/bundler-test.js", "test/bundler/esbuild/package.json", "test/bundler/esbuild/src/fail-plugin-version.js", "test/bundler/esbuild/src/index.js", "test/bundler/webpack/bundler-test.js", "test/bundler/webpack/src/fail-plugin-version.js", "test/bundler/webpack/src/index.js"]
ci: Add esbuild in package pipeline
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the issue has not already been raised ### Issue Following: https://github.com/fastify/fastify/issues/3371 Would be nice to have `esbuild` in the CI for bundlers.
https://github.com/fastify/fastify/issues/3377
https://github.com/fastify/fastify/pull/3616
670e7d6310e627f94f352c96ef9ba333f295acc6
93fe532986b96ae28a087b2ec385a8abb16cce55
"2021-10-17T08:52:48Z"
javascript
"2022-01-13T12:37:58Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,332
["lib/pluginUtils.js", "test/decorator.test.js", "test/internals/plugin.test.js"]
Decorator assertion broken in 3.21.2 & 3.21.3
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 3.21.2 and 3.21.3 ### Plugin version _No response_ ### Node.js version 14.17.6 ### Operating system macOS ### Operating system version (i.e. 20.04, 11.3, 10) 11.6 ### Description Using decorator assertions broke in what I assume was #3317. `AssertionError [ERR_ASSERTION]: The decorator 'someThing' required by 'custom-plugin-two' is not present in Request` ### Steps to Reproduce ```js const fastify = require('fastify'); const fp = require('fastify-plugin'); const plugin1 = fp( async (instance) => { instance.decorateRequest('someThing', null); instance.addHook('onRequest', async (request, reply) => { request.someThing = 'hello'; }); }, { name: 'custom-plugin-one', fastify: '3.x', } ); const plugin2 = fp( async () => { // nothing }, { name: 'custom-plugin-two', fastify: '3.x', dependencies: ['custom-plugin-one'], decorators: { request: ['someThing'], }, } ); const app = fastify(); app.register(plugin1); app.register(plugin2); app.listen(0).then( () => { console.log('no error!'); process.exit(0); }, (error) => { console.error('Got error', error); process.exit(1); } ); ``` Using 3.21.1 this works fine, but 3.21.2 and 3.21.3 throws an assertion error ### Expected Behavior No error
https://github.com/fastify/fastify/issues/3332
https://github.com/fastify/fastify/pull/3333
36f4b67b5940d89d12f1eefc733bbd0d7f5e1afb
7979e9cf32132f97acd5e506e77571f4caa38dbc
"2021-09-22T09:34:47Z"
javascript
"2021-09-22T12:57:22Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,331
["docs/Reference/Routes.md", "docs/Reference/Server.md"]
ignoreTrailingSlash doesn't work with wildcard routes
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 3.21.1 ### Plugin version 4.2.3 ### Node.js version 14.17.6 ### Operating system macOS ### Operating system version (i.e. 20.04, 11.3, 10) 11.6 ### Description I want to listen on all routes under `/app` including `/app` and `/app/anything`. I want to serve the same html file for any of these routes. ```js fastify.get( "/app/*, { exposeHeadRoute: true, prefixTrailingSlash: 'slash', }, (_req, reply) => { reply.sendFile("index.html", path.resolve("./public", p.path.replace("/", ""))); }, ); ``` This works for `/app/` and `/app/:anything`. I originally tried to setup a redirect then from `/app` => `/app/` but because I had `ignoreTrailingSlash` enabled this created an infinite loop. Basically the `/app` didn't match `/app/` but for some reason `/app/` did match `/app` even though the redirect was configured with `prefixTrailingSlash: "no-slash"`. My guess was that this was being caused by `ignoreTrailingSlash` being applied to the redirect but not the initial catch all. Disabling `ignoreTrailingSlash` did fix my redirect. But I'd rather not have to redirect, I'd rather just have `/app` currectly resolve as a 200. I then tried: ```js fastify.get( "/app*, // all the smae ``` This correctly resolves everything: `/app`, `/app/`, and `/app/:anything`. ### Steps to Reproduce I think above covers this. Let me know if you need more info. ### Expected Behavior I'd expect `/app/*` to resolve `/app`, `/app/`, and `/app/:anything` when `ignoreTrailingSlash: true` and only `/app/`, and `/app/:anything` when `ignoreTrailingSlash: false` .
https://github.com/fastify/fastify/issues/3331
https://github.com/fastify/fastify/pull/3846
2ab497bc21aaa85e3d05092e9013fe4a4d589e68
031ef2efe85390668d4a291294112fb4ceeb629b
"2021-09-21T21:39:48Z"
javascript
"2022-04-23T07:28:33Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,323
["lib/decorate.js", "test/decorator.test.js", "test/same-shape.test.js"]
[Bug] Registering multiple named instances of this module fail.
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version 3.21.2 ### Plugin version 3.6.0 ### Node.js version 14.17.6 ### Operating system Linux ### Operating system version (i.e. 20.04, 11.3, 10) ArchLinux (kernel 5.14.5-arch1-1) ### Description Since https://github.com/fastify/fastify/pull/3317 was merged in Fastify it's impossible to register multiple named instances of the package. This error is thrown at the start: ``` [...]/node_modules/fastify/lib/decorate.js:40 throw new FST_ERR_DEC_ALREADY_PRESENT(name) ^ FastifyError [Error]: The decorator 'pg' has already been added! [...] ``` I am currently investigating the code to clearly identify the faulty part and submit a fix PR. I suspect that this is due to https://github.com/fastify/fastify-postgres/pull/76 as the code rely on a mutable request.pg object (https://www.fastify.io/docs/latest/Decorators/#decoraterequestname-value-dependencies). I think we should adopt the same request decoration strategy as the one used for `fastify-jwt` (https://github.com/fastify/fastify-jwt/pull/175). WDYT can I go for a fix PR adopting this decoration strategy knowing that this will be a breaking change ? ### Steps to Reproduce ```js 'use strict'; const fastify = require('fastify'); const server = fastify(); server.register(require('fastify-postgres'), { connectionString: 'postgres://postgres:postgres@localhost/postgres', name: 'one' }) server.register(require('fastify-postgres'), { connectionString: 'postgres://postgres:postgres@localhost/postgres', name: 'two' }) server.listen(3000); ``` ### Expected Behavior It should start.
https://github.com/fastify/fastify/issues/3323
https://github.com/fastify/fastify/pull/3324
f515fc1b67c5a70e078e45cb351f0611f3b35885
567609b8282e581a44346fe21b98b6f23b86809a
"2021-09-17T13:43:12Z"
javascript
"2021-09-17T14:56:45Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,314
["docs/Request.md", "docs/Server.md"]
Docs mention "parsed querystring" but the format is not documented
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the bug has not already been reported ### Fastify version latest ### Plugin version _No response_ ### Node.js version N/A ### Operating system macOS ### Operating system version (i.e. 20.04, 11.3, 10) N/A ### Description From https://github.com/fastify/fastify/blob/main/docs/Request.md > `query` - the parsed querystring However, the format of this property is not documented. ### Steps to Reproduce See https://github.com/fastify/fastify/blob/main/docs/Request.md ### Expected Behavior _No response_
https://github.com/fastify/fastify/issues/3314
https://github.com/fastify/fastify/pull/3319
ce6270608be0dd56de629be0df149f94c5df95ba
ad967c2cc878eea3e832503e6a081003d13df110
"2021-09-15T12:16:11Z"
javascript
"2021-09-19T06:30:24Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,316
[".taprc", "lib/decorate.js", "lib/reply.js", "lib/request.js", "package.json", "test/internals/decorator.test.js", "test/same-shape.test.js"]
Are conditionally set decorated properties deoptimized?
Over the past week or so I started to learn how V8 optimizes property access through shapes and inline caches by following the blog post link in the decorators documentation ([Shapes and IC](https://mathiasbynens.be/notes/shapes-ics) + [Optimizing Prototypes](https://mathiasbynens.be/notes/prototypes)). After reading this and other information I found about this topic, I was curious if the following scenario would deoptimize the example given in the decorator documentation. In the decorator documentation, it states that the following should be avoided: ```js fastify.addHook('preHandler', function (req, reply, done) { req.user = 'Bob Dylan' done() }) // Use the attached user property in the request handler. fastify.get('/', function (req, reply) { reply.send(`Hello, ${req.user}`) }) ``` Instead, a user should decorate the request prototype by using a decorator like so: ```js fastify.decorateRequest('user', '') fastify.addHook('preHandler', (req, reply, done) => { req.user = 'Bob Dylan' done() }) fastify.get('/', (req, reply) => { reply.send(`Hello, ${req.user}!`) }) ``` After reading about how V8 optimizes things like property access and function calls, I realized that this example can be optimized since the same "shape" request is being passed to the route handler. Since the same shape is always passed in this example, then property lookup can take advantage of inline caches and the function can be optimized. What I'm curious about is what would happen if the user string was conditionally set in the `preHandler` hook: ```js fastify.decorateRequest('user', '') fastify.addHook('preHandler', (req, reply, done) => { if (condition) { req.user = 'Bob Dylan' } done() }) fastify.get('/', (req, reply) => { reply.send(`Hello, ${req.user}!`) }) ``` This would mean that based on the condition, the shape of the object going into the route handler would be different. I read [here](https://itnext.io/v8-function-optimization-2a9c0ececf5e) that after a function receives too many different shapes, it stops filling inline caches. I'm curious about a couple of things in this scenario: 1. Should conditional property setting be avoided in these types of scenarios? If that's the case, wouldn't always setting the user string in the prehandler and omitting the empty user string on the request prototype have the same performance boost from inline caches since the same shape would always reach the handler? 2. Does setting the empty user string on the request prototype instead of leaving it unset prevent repeated object property lookups by forcing there to be a "fallback" value sitting in an inline cache for each shape? When the request prototype property value is not set (ie. when decorateRequest is not used), does V8 repeatedly attempt to look up the property value in the prototype chain, or is a special null value placed in the inline cache to prevent this lookup? 3. Are there any other deoptimizations that occur by having this conditional value? Does it make it harder for TurboFan to optimize the route handler function? 4. Are there any conventions we should follow with handling decorated properties that will speed up our applications? Thanks!
https://github.com/fastify/fastify/issues/3316
https://github.com/fastify/fastify/pull/3317
11cdc231510011efe64af8fe57836ab2b5a7c3aa
e77bfa26809e08e82a5f3180572ccd4d4c4d771a
"2021-09-14T18:28:27Z"
javascript
"2021-09-16T12:32:49Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,300
["docs/Recommendations.md"]
NGINX docs
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the feature has not already been requested ### πŸš€ Feature Proposal In https://github.com/fastify/fastify/pull/3298, we added some docs on NGINX. However the config file is not well documented. Add more inline comments on the NGINX configs. ### Motivation _No response_ ### Example _No response_
https://github.com/fastify/fastify/issues/3300
https://github.com/fastify/fastify/pull/3352
43d61a57efaba3eaf1b63db1b28f28673e7cd8fa
ba364756e4afdd2061e25c21d9cdee9a93436410
"2021-09-07T12:02:14Z"
javascript
"2021-09-30T21:13:07Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,296
["test/schema-feature.test.js"]
Adapt test to support V8 9.3
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure the issue has not already been raised ### Issue There is one test that will fail with Node.js >= 16.9.0, because V8 changed an error message: https://github.com/fastify/fastify/blob/02d17b006082553ac628a9b97581502e52f90a26/test/schema-feature.test.js#L207 See https://ci.nodejs.org/view/Node.js-citgm/job/citgm-smoker/2754/nodes=fedora-latest-x64/testReport/junit/(root)/citgm/fastify_v3_20_2/ ``` not ok 2 - should be equal --- compare: === at: line: 207 column: 7 file: test/schema-feature.test.js stack: | cb (test/schema-feature.test.js:207:7) manageErr (fastify.js:479:11) fastify.js:468:11 Object._encapsulateThreeParam (node_modules/avvio/boot.js:551:7) Boot.timeoutCall (node_modules/avvio/boot.js:447:5) Boot.callWithCbOrNextTick (node_modules/avvio/boot.js:428:19) release (node_modules/fastq/queue.js:149:16) Object.resume (node_modules/fastq/queue.js:82:7) node_modules/avvio/boot.js:167:18 node_modules/avvio/plugin.js:270:7 done (node_modules/avvio/plugin.js:202:5) check (node_modules/avvio/plugin.js:226:9) source: >2 t.equal(err.code, 'FST_ERR_SCH_SERIALIZATION_BUILD') t.equal(err.message, "Failed building the serialization schema for GET: /:id, due to error Cannot read property 'type' of undefined") // error from fast-json-strinfigy ------^ }) }) diff: > --- expected +++ actual @@ -1,1 +1,1 @@ -Failed building the serialization schema for GET: /:id, due to error Cannot read property 'type' of undefined +Failed building the serialization schema for GET: /:id, due to error Cannot read properties of undefined (reading 'type') ... # failed 1 of 2 tests ```
https://github.com/fastify/fastify/issues/3296
https://github.com/fastify/fastify/pull/3297
02d17b006082553ac628a9b97581502e52f90a26
33290ee5a012badd3dca11ca31c53d58acdc8c22
"2021-09-06T11:48:03Z"
javascript
"2021-09-06T12:36:26Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,286
["docs/Ecosystem.md"]
Suggestion: Adding an official Supabase Plugin
<!-- Before you submit an issue we recommend you visit [Fastify Help](https://github.com/fastify/help) and ask any questions you have or mention any problems you've had getting started with Fastify. **Please read this entire template before posting any issue. If you ignore these instructions and post an issue here that does not follow the instructions, your issue might be closed, locked, and assigned the `missing discussion` label.** --> ## πŸš€ Feature Proposal I am proposing an official [Supabase](https://supabase.io/) Plugin for Fastify. This would be similar in nature to the likes of the following official database plugins: - [fastify-postgres](https://github.com/fastify/fastify-postgres) - [fastify-mysql](https://github.com/fastify/fastify-mysql) - [fastify-mongodb](https://github.com/fastify/fastify-mongodb) ## Motivation [Supabase](https://supabase.io/) is an open source alternative to Firebase built on top of Postgres. While supabase does allow connecting to a postgres database through traditional connection methods (db name, db password, db host, etc) which can be used via the [fastify-postgres](https://github.com/fastify/fastify-postgres) plugin, they provide a robust API to access ones database (thanks to [postgREST](https://postgrest.org/en/v8.0/)). That being said, it would be pretty cool to include a supabase plugin for the Fastify community. ## Example An example of how this feature would be used is one could import the supabase plugin as such: ```typescript import fastify from 'fastify'; import supabasePlugin from 'fastify-supabase'; fastify.register(supabasePlugin, { supabaseUrl: 'supabase-url', supabaseKey: 'super-secret-supabase-key' }) ``` Then the user could use the supabase plugin to interact with their database! ## Contributing I am happy to work on an official supabase plugin if the community would find this beneficial. πŸš€
https://github.com/fastify/fastify/issues/3286
https://github.com/fastify/fastify/pull/3348
44db95025d1d782ca6ef121dbd3b5d1ee2b43bcd
4b389207765ac2c746725041dca0043b9c2aaf01
"2021-09-01T06:06:20Z"
javascript
"2021-09-29T13:54:08Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,282
["build/build-validation.js", "docs/Server.md", "lib/configValidator.js", "test/internals/initialConfig.test.js", "test/request-error.test.js"]
Docs: Ensure everyone who uses HTTP2 knows http2SessionTimeout will cripple their performance
## πŸš€ Feature Proposal Make `http2SessionTimeout` more prominent to users who enable the https2 flag. ## Motivation I'm developing a website which is hosted in the US (210ms from me). After 5 seconds of being idle, the next request would take around a second, instead of being nearly instant. Hours of debugging later on different OS's & browsers - I noticed the `http2SessionTimeout` attribute. Setting this to a higher value eliminated this delay. Most users of fastify I suspect would have no idea this is causing delays.
https://github.com/fastify/fastify/issues/3282
https://github.com/fastify/fastify/pull/3304
efbea2f0d3799dc67fb9f8fe0842023c5fcf7e65
3feacfb1d7ef7d2748dafdccd5c1d252326117cd
"2021-08-27T06:23:24Z"
javascript
"2021-09-10T18:10:41Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,266
["docs/ContentTypeParser.md", "docs/Routes.md", "lib/route.js", "test/route.test.js", "test/schema-examples.test.js", "test/schema-feature.test.js"]
GET request payload validation error
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure it has not already been reported ### Fastify version 3.20.1 ### Plugin version _No response_ ### Node.js version 14.15 ### Operating system macOS ### Operating system version (i.e. 20.04, 11.3, 10) 10.15.6 ### Description Fastify currently parses the request payload from `DELETE` requests but not from `GET` requests even though [RFC 7231](https://datatracker.ietf.org/doc/html/rfc7231#section-4.3) states the same for both methods. > A payload within a DELETE request message has no defined semantics; sending a payload body on a DELETE request might cause some existing implementations to reject the request. and > A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request. The fact that Fastify does not parse the request payload of a `GET` request, but at the same time allows the developer to define a validation scheme for a `GET` endpoint, adds to confusing errors for the developer. So Fastify tries to validate the request payload, which was not parsed before. Thus, the client always receives the error `"body should be object"`since its request payload was not parsed and is, therefore `null` and the validation can only fail. ### Steps to Reproduce ```javascript const app = require('fastify')() app.get('/', { schema: { body: { name: { type: 'string' } } } }, function (req, reply) { // req.body === null reply.send('ok') }) app.listen(8080) ``` Now when a client makes the following request: ```http GET / HTTP/1.1 Host: localhost:8080 Content-Type: application/json Content-Length: 26 { "name": "testName" } ``` it always receives the response: ```json { "statusCode": 400, "error": "Bad Request", "message": "body should be object" } ``` ### Expected Behavior Fastify should therefore either parse the payload of `GET` requests, give developers a warning when they specify a body validation schema, or simply skip the body validation if it is a `GET` request.
https://github.com/fastify/fastify/issues/3266
https://github.com/fastify/fastify/pull/3274
695b1f12f8edcaf268d4da73dc653faa9a2c5ea0
e6e25935c85477200b9af07a40aea80f5a2c4f82
"2021-08-17T23:55:18Z"
javascript
"2021-08-23T12:02:39Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,260
["build/build-validation.js", "docs/Server.md", "fastify.js", "lib/configValidator.js", "lib/server.js", "test/internals/initialConfig.test.js", "test/maxRequestsPerSocket.test.js"]
max requests on a socket
## πŸš€ Feature Proposal In keep-alive response header, there is a posibility to define the timeout and max requests for the connection https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Keep-Alive I would like propose the functionality on the server, that will count requests per socket and send "connection: closed" header and actually close the connection when it reached the maximum value ## Motivation Currently as fast as I can understand, nothing can force the connection on the server to be closed, for example both "connectionTimeout" and "keepAliveTimeout" define the time of inactivity, for the socket to be closed, but if the socket is always active, or the client ignores this header, server will not send the "connection: close" header and close the connection
https://github.com/fastify/fastify/issues/3260
https://github.com/fastify/fastify/pull/3335
a478dd2e842de949c2c76d542143a23b279328fe
a454883afbd12871aef426ea43480d61240c11cf
"2021-08-16T07:16:42Z"
javascript
"2021-09-23T16:13:12Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,251
["fastify.js", "test/request-error.test.js"]
Socket leakage on tls handshake timeout in https protocol
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure it has not already been reported ### Fastify version 3.19.2 ### Plugin version 3.0.0 ### Node.js version 16.6.1 ### Operating system Linux ### Operating system version (i.e. 20.04, 11.3, 10) alpine-3.13.5 ### Description I've switched my code from koa to fastify on a single region. After switch I've started to get EMFILE error when uptime reaches 24 hours. To debug the issue I've added running `lsof` every 2 minutes. This is the response: ``` Β  | 2021-08-11T13:43:42.999+03:00 | node 6 node 75u sock 0,8 0t0 24642 protocol: TCP Β  | 2021-08-11T13:43:42.999+03:00 | node 6 node 79u sock 0,8 0t0 24737 protocol: TCP Β  | 2021-08-11T13:43:42.999+03:00 | node 6 node 84u sock 0,8 0t0 30347 protocol: TCP Β  | 2021-08-11T13:43:42.999+03:00 | node 6 node 86u sock 0,8 0t0 25148 protocol: TCP Β  | 2021-08-11T13:43:42.999+03:00 | node 6 node 87u sock 0,8 0t0 24837 protocol: TCP Β  | 2021-08-11T13:43:42.999+03:00 | node 6 node 92u sock 0,8 0t0 33185 protocol: TCP Β  | 2021-08-11T13:43:42.999+03:00 | node 6 node 93u sock 0,8 0t0 28289 protocol: TCP Β  | 2021-08-11T13:43:42.999+03:00 | node 6 node 98u sock 0,8 0t0 28314 protocol: TCP ... hundreds of them ... ``` When I've tried to track a history of a single socket from different lsof commands I got this: ``` timestamp,message 1628624501275,node 7 node 99u IPv4 999238 0t0 TCP 172.31.42.211:8443->xxx.xxx.xxx.xxx:49758 (FIN_WAIT1) 1628624621276,node 7 node 99u IPv4 999238 0t0 TCP 172.31.42.211:8443->xxx.xxx.xxx.xxx:49758 (CLOSING) 1628624741286,node 7 node 99u IPv4 999238 0t0 TCP 172.31.42.211:8443->xxx.xxx.xxx.xxx:49758 (CLOSING) 1628624861284,node 7 node 99u IPv4 999238 0t0 TCP 172.31.42.211:8443->xxx.xxx.xxx.xxx:49758 (CLOSING) 1628624981274,node 7 node 99u IPv4 999238 0t0 TCP 172.31.42.211:8443->xxx.xxx.xxx.xxx:49758 (CLOSING) 1628625101280,node 7 node 99u IPv4 999238 0t0 TCP 172.31.42.211:8443->xxx.xxx.xxx.xxx:49758 (CLOSING) 1628625221279,node 7 node 99u IPv4 999238 0t0 TCP 172.31.42.211:8443->xxx.xxx.xxx.xxx:49758 (CLOSING) 1628625341277,node 7 node 99u IPv4 999238 0t0 TCP 172.31.42.211:8443->xxx.xxx.xxx.xxx:49758 (CLOSING) 1628625461284,node 7 node 99u sock 0,8 0t0 999238 protocol: TCP 1628625581286,node 7 node 99u sock 0,8 0t0 999238 protocol: TCP 1628625701274,node 7 node 99u sock 0,8 0t0 999238 protocol: TCP 1628625821280,node 7 node 99u sock 0,8 0t0 999238 protocol: TCP 1628625941287,node 7 node 99u sock 0,8 0t0 999238 protocol: TCP 1628626061287,node 7 node 99u sock 0,8 0t0 999238 protocol: TCP 1628626181284,node 7 node 99u sock 0,8 0t0 999238 protocol: TCP ... last line repeats till the death of the process ``` As you can see, this zombie socket (with id 999238) was initially a https socket, handled by fastify. It does not include all states (ESTABLISHED and so on) because snapshot was saved every 2 minutes First time I've blamed proxywrap module (which worked for koa as well), but removing proxywrap did not change anything ### Steps to Reproduce I don't have yet steps to reproduce. All my attempts to reproduce did not succeed (in production it is still an issue). I think it is related with very slow EDGE mobile connection, but it is a guess Here is my app config: ```js const app = fastifyFactory({ serverFactory: (handler, opts) => { let server: http.Server; if (!httpsMode) { server = http.createServer((req: any, res: any) => { handler(req, res); }) as http.Server; } else { server = https.createServer({ SNICallback: createSNICallback(), key: selfSignedKey, cert: selfSignedCert, handshakeTimeout: 10000, }, handler); server.setTimeout(10000); server.on('error', serverErrorHandler); server.on('tlsClientError', serverErrorHandler); return server as https.Server; } server.keepAliveTimeout = opts.keepAliveTimeout as number; server.setTimeout(opts.connectionTimeout as number); return server; }, keepAliveTimeout: 0, connectionTimeout: 10000, logger: false, trustProxy: [ ... ] }); ``` ### Expected Behavior All sockets needs to be closed
https://github.com/fastify/fastify/issues/3251
https://github.com/fastify/fastify/pull/3254
846284d57305ba93389062b3b913c1b45c4aaf2e
3956e684247492bff41bae30eed4355bfb0ef63d
"2021-08-11T11:00:54Z"
javascript
"2021-08-13T09:32:45Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,217
["docs/Reference/Reply.md", "lib/error-handler.js", "test/internals/reply.test.js"]
Invalid character in header content ["location"] error when redirecting to url with unicode encoded character in query parameters
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure it has not already been reported ### Fastify version 3.19.2 ### Plugin version _No response_ ### Node.js version 14.15.1 ### Operating system macOS ### Operating system version (i.e. 20.04, 11.3, 10) 11.4 ### Description The following error is thrown when redirecting to a url which includes encoded unicode characters. ``` "reqId":"req-1","err":{"type":"NodeError","message":"Invalid character in header content [\"location\"]","stack":"TypeError [ERR_INVALID_CHAR]: Invalid character in header content [\"location\"] at storeHeader (_http_outgoing.js:502:5) ``` This is reproducible with the following code ```js // Require the framework and instantiate it const fastify = require('fastify')({ logger: true }) // capture query parameters for redirection global.prepParams = function (req){ var query_parameters = ''; for (const [key,value] of Object.entries(req.query)){ if (query_parameters === '') query_parameters += '?'; else query_parameters += '&'; query_parameters += key + '=' + value; } return query_parameters; }; // Declare a route fastify.get('/1', async (req, reply) => { var query_parameters=prepParams(req); console.log('redirect url: ', '/2'+query_parameters); reply.redirect('/2'+query_parameters); }); fastify.get('/2', async (req, reply) => { return { hello: 'world' } }); // Run the server! const start = async () => { try { await fastify.listen(3004) } catch (err) { fastify.log.error(err) process.exit(1) } } start() ``` A request to `'http://localhost:3004/1?key=ab'` succeeds, but a request to `http://localhost:3004/1?key=a%e2%80%99b` fails ### Steps to Reproduce With the code above running, send request to `http://localhost:3004/1?key=a%e2%80%99b` ### Expected Behavior _No response_
https://github.com/fastify/fastify/issues/3217
https://github.com/fastify/fastify/pull/3593
20e17310b74fddb786a33484183ad0e49e817ab6
38fc063ecd3febeb7e2d93453760ab4cd9147845
"2021-07-28T14:55:22Z"
javascript
"2022-01-05T13:47:29Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,209
["lib/reply.js", "test/async-await.test.js"]
Request hangs when returning in `setErrorHandler`
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure it has not already been reported ### Fastify version v3.19.2 ### Plugin version _No response_ ### Node.js version v16.2.0 ### Operating system Windows ### Operating system version (i.e. 20.04, 11.3, 10) 10 ### Description This type of code works in route handlers and `setNotFoundHandler`: ```js reply.code(someCode) return { msg: "someMsg" } ``` but it doesn't work in `setErrorHandler`, it just hangs when doing it like that. ### Steps to Reproduce ```js // index.js import Fastify from 'fastify' const fastify = Fastify({ logger: true }) fastify.route({ method: 'GET', url: '/', handler: function (request, reply) { const err = new Error('ERROOOR') err.statusCode = 400 throw err } }) fastify.setNotFoundHandler(function (request, reply) { reply.code(404) return { msg: 'Not Found' } }) fastify.setErrorHandler(function (error, request, reply) { const statusCode = error.statusCode if (statusCode == 400) { // Hangs here reply.code(statusCode) return { msg: error.message } } reply .code(500) .send({ msg: 'Internal Server Error' }) }) fastify.listen(8080) ``` Run `node index.js` and then try `curl http://localhost:8080/ -v` ### Expected Behavior _No response_
https://github.com/fastify/fastify/issues/3209
https://github.com/fastify/fastify/pull/3211
7db55d47a80607f97c4fd8e3e54c649abcd78f2f
aa58990205ec6923358c5f86a8b0bf55a3f378f0
"2021-07-22T10:58:02Z"
javascript
"2021-07-24T15:16:46Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,207
["lib/logger.js", "lib/route.js"]
Logger warning: "[PINODEP007] Warning: bindings.level is deprecated, use options.level option instead"
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure it has not already been reported ### Fastify version 3.19.1 ### Plugin version _No response_ ### Node.js version 14.17.3 ### Operating system macOS ### Operating system version (i.e. 20.04, 11.3, 10) macOS Big Sur 11.4 ### Description The following warning occurs when logging is enabled in a Fastify app: ``` [PINODEP007] Warning: bindings.level is deprecated, use options.level option instead ``` This appears to be a result of the changes introduced in https://github.com/pinojs/pino/pull/1067 ### Steps to Reproduce 1. Create a basic Fastify app with an `index.js` containing the example code found on fastify.io ```js // Require the framework and instantiate it const fastify = require('fastify')({ logger: true }) // Declare a route fastify.get('/', async (request, reply) => { return { hello: 'world' } }) // Run the server! const start = async () => { try { await fastify.listen(3000) } catch (err) { fastify.log.error(err) process.exit(1) } } start() ``` 1. Start the server by running `node index.js` 1. Make a request to `GET http://localhost:3000` 1. See the warning output between pino logs ### Expected Behavior No warning should appear
https://github.com/fastify/fastify/issues/3207
https://github.com/fastify/fastify/pull/3208
ae9074319a88f267459f2bc7a072410f85be2e42
bdba8ed2a05625e827ab7b1ac3ffd8c22fa6c922
"2021-07-21T17:39:12Z"
javascript
"2021-07-21T19:33:44Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,202
["test/types/reply.test-d.ts", "test/types/request.test-d.ts", "types/reply.d.ts", "types/request.d.ts"]
[Typescript]: request and reply missing `server` property type define
In https://github.com/fastify/fastify/pull/3102 add `server` property to req/res properties, but it seems not defining a typescript type for that.
https://github.com/fastify/fastify/issues/3202
https://github.com/fastify/fastify/pull/3204
014d6d6e368496b9ca850d60ae66b18df50fe21a
cfd15505ef64f88eb8e91508c0e0f09aa44b80b2
"2021-07-17T11:55:12Z"
javascript
"2021-07-19T13:11:51Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,193
["docs/Reply.md", "docs/Server.md"]
Links pointing at v8.x node documentation
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure it has not already been reported ### Fastify version 3.19.1 ### Plugin version _No response_ ### Node.js version 14.17.3 ### Operating system Windows ### Operating system version (i.e. 20.04, 11.3, 10) 10 ### Description Documentation that have links to the node documentation are pointing at https://nodejs.org/dist/latest-v8.x/docs/api/. As v10 is the minimum version tested on/supported by Fastify v3.x, this should probably be pointed at https://nodejs.org/dist/latest-v10.x/docs/api/. Happy to open a PR to fix this, just wanted to discuss/raise it first! ### Steps to Reproduce - Navigate to https://github.com/fastify/fastify/blob/main/docs/Server.md#http2 - Click on `HTTP/2` link in section ### Expected Behavior _No response_
https://github.com/fastify/fastify/issues/3193
https://github.com/fastify/fastify/pull/3227
dfdc243b7fc857e5ba5be0728b47bc9b169c24cd
1299d1ef188293bc1085d14f7b488a99a2c5ae92
"2021-07-15T08:15:32Z"
javascript
"2021-08-03T09:35:31Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,163
["package.json"]
Tests are failing for the lowest supported Nodejs version
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure it has not already been reported ### Fastify version main ### Plugin version _No response_ ### Node.js version 10.16.0 ### Operating system Linux ### Operating system version (i.e. 20.04, 11.3, 10) 20.04 ### Description If you checkout the master branch and run the test suite using Nodejs v10.16.0, it will fail due to stream.Readable.from not being a function in 10.16.0 since it was added in 10.17.0 (https://nodejs.org/api/stream.html#stream_stream_readable_from_iterable_options). The CI runs only the latest Nodejs major versions. It should also run the lowest supported version in order to catch such situations in time. ### Steps to Reproduce Checkout master branch and run "npm test" using Nodejs v10.16.0. ### Expected Behavior Test suite to pass.
https://github.com/fastify/fastify/issues/3163
https://github.com/fastify/fastify/pull/3166
7c1bcd176c6a1aaeef3d07f5c079c2d503013f08
d00f557a132faa517f5b39465f209af7e1801f50
"2021-06-28T16:57:41Z"
javascript
"2021-06-29T09:16:27Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,160
["lib/handleRequest.js", "test/reply-error.test.js"]
Wrong status code throwing an object
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure it has not already been reported ### Fastify version 3.18.0 ### Plugin version _No response_ ### Node.js version 16 ### Operating system Windows ### Operating system version (i.e. 20.04, 11.3, 10) 10 ### Description In https://github.com/fastify/fastify/pull/2134 we introduced the possibility to throw an object as the spec admit. In a sync route, the throws of an object won't set the 500 status code This will prevent the execution of the error handler too ### Steps to Reproduce ``` const fastify = require('fastify')({ logger: true }) fastify.get('/a', function (request, reply) { throw { appCode: 418 } // status 200 }) fastify.get('/b', async function (request, reply) { throw { appCode: 418 } // status 500 }) fastify.setErrorHandler(function (_, request, reply) { console.log('CUSTOM ERROR HANDLER') reply.status(500).send({ ok: false }) }) fastify.listen(8080) ``` ### Expected Behavior The `/a` route should return the 500 status code if the user didn't customize it yet
https://github.com/fastify/fastify/issues/3160
https://github.com/fastify/fastify/pull/3162
a791bf83c6555f02294d66021982059eea9b5a46
7c1bcd176c6a1aaeef3d07f5c079c2d503013f08
"2021-06-25T22:48:06Z"
javascript
"2021-06-26T21:22:08Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,158
[".github/workflows/ci.yml", "test/bundler/README.md", "test/bundler/webpack/bundler-test.js", "test/bundler/webpack/package.json", "test/bundler/webpack/src/fail-plugin-version.js", "test/bundler/webpack/src/index.js", "test/bundler/webpack/webpack.config.js"]
Test webpack bundling
<!-- Before you submit an issue we recommend you visit [Fastify Help](https://github.com/fastify/help) and ask any questions you have or mention any problems you've had getting started with Fastify. **Please read this entire template before posting any issue. If you ignore these instructions and post an issue here that does not follow the instructions, your issue might be closed, locked, and assigned the `missing discussion` label.** --> ## πŸš€ Feature Proposal A few users are bundling Fastify with Webpack. While I discourage the practice, adding some regression tests (and necessary fixes) would help a lot in avoiding a lot of issue traffic.
https://github.com/fastify/fastify/issues/3158
https://github.com/fastify/fastify/pull/3240
a04f4c952731c57e79c6ca3794a62959a43731ed
149295670f79cbf1438268f3dbd36ea905d912ca
"2021-06-25T07:17:14Z"
javascript
"2021-08-31T08:03:03Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,127
["lib/fourOhFour.js", "test/404s.test.js", "test/logger.test.js"]
404 error for requests with invalid uri encoding
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure it has not already been reported ### Fastify version 3.17.0 ### Plugin version _No response_ ### Node.js version 14.16 ### Operating system macOS ### Operating system version (i.e. 20.04, 11.3, 10) 11.4 ### Description when receiving a http request that contains invalid url encoding I get the following log output ``` 07:48:34 ✨ incoming request GET xxx /%C0 07:48:34 ⚠️ the default handler for 404 did not catch this, this is likely a fastify bug, please report it 07:48:34 ⚠️ └── / (ACL) / (BIND) / (CHECKOUT) / (CONNECT) / (COPY) / (DELETE) / (GET) / (HEAD) ... ``` As stated in #1884, the result should actually be a 400 and we should not log errors to the log. ### Steps to Reproduce Setup an empty default project ```bash mkdir my-app cd my-app npm init fastify npm install npm run dev ``` Then send the following request (e.g. via `httpie`) ```bash http 'localhost:3000/%c0' ``` ### Expected Behavior The server should return a 400 and not log errors to the log.
https://github.com/fastify/fastify/issues/3127
https://github.com/fastify/fastify/pull/3128
c631bb71b8c180c8ba326e81455836f93b0d08c9
4fb2e090b4ca36a3c17217b4df7231ebb148ed0b
"2021-06-09T08:37:14Z"
javascript
"2021-06-10T16:02:35Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,121
["docs/Guides/Ecosystem.md"]
Option to customize Ajv type coercion behavior based on httpPart
## πŸš€ Feature Proposal Hello! Fastify by default comes with AJV with coerceTypes enabled. Me and some coworkers found that is a pretty good behavior for both querystring and pathParams as they all come as strings However, for body validation as JSON, we actually required to have it turned off, as there are some edge cases that we need to validate that are simply wrong with coercion enabled. ex: { "some_integer_prop": null } passes validation because it is coerced to 0. Our fix was to customize fastify setValidatorCompiler like so: ```javascript const defaultAjv = new Ajv({ removeAdditional: true, useDefaults: true, coerceTypes: true, nullable: true, }) const disabledCoercionAjv = new Ajv({ removeAdditional: true, useDefaults: true, coerceTypes: false, nullable: true, }) // Use ajv instance with disabled type coercion for body params // and default ajv instance for others fastify.setValidatorCompiler(({ schema, httpPart }) => { if (httpPart === 'body') { return disabledCoercionAjv.compile(schema) } return defaultAjv.compile(schema) }) ``` It would be nice if there was a built-in option in fastify to selectively enable this behavior like so: ```javascript const fastify = require('fastify')({ ajv: { customOptions: { coerceTypes: true, coerceTypesBody: false } } }) ``` ## Motivation I understand that maybe this should be a feature of ajv itself to have more granular control of its coercion options, but I believe this is an issue common enough that many developers have without even realizing until they get a bug in production having a field in database with value 0 that shouldn't be there. And since the default in ajv is to not coerce types, but in fastify is to coerce, I guess many fastify users have this issue without even realizing. Maybe if not possible to implement this feature, put a section in the documentation warning of this edge case of body validation. Thanks!
https://github.com/fastify/fastify/issues/3121
https://github.com/fastify/fastify/pull/3535
33ad2fcfe63ac7779e02203a323c9429dcf9e5fe
bb4e78b823426bffb7d5f00c93964ea076d1ca5b
"2021-06-05T01:16:56Z"
javascript
"2021-12-14T13:09:40Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,120
["docs/Server.md"]
"onRequest" hook not triggering when route is not found
## πŸ’¬ Why is the `onRequest` hook not triggering when the application doesnΒ΄t find a registered matching route? When running the `npm init fastify` command and registering a plugin that adds a `onRequest` hook to be available for all the application, if the route is not found, the hook is not triggered and instead fastify passes control to the default error handler, which then throws the 404 not found error. Is this expected behaviour? ### Example plugin (project/plugins/deny.js) ```js 'use strict' const fp = require('fastify-plugin'); module.exports = fp(async function (fastify, opts) { fastify.addHook('onRequest', async function (request) { console.log('This should trigger on every request'); }) }); ```` ### Registered Route (project/routes/root.js) ```js 'use strict' module.exports = async function (fastify, opts) { fastify.get('/', async function (request, reply) { return { root: true } }) } ```` The weird behaviour comes in the app.js file. If I register a `setNotFoundHandler` then the hook works as expected. ### App (project/app.js) ```js 'use strict' const path = require('path') const AutoLoad = require('fastify-autoload') module.exports = async function (fastify, opts) { fastify.register(AutoLoad, { dir: path.join(__dirname, 'plugins'), options: Object.assign({}, opts) }) fastify.register(AutoLoad, { dir: path.join(__dirname, 'routes'), options: Object.assign({}, opts) }) // ----------------------------------------------------------------- fastify.setNotFoundHandler(); // IF I ADD THIS LINE THEN IT TRIGGERS THE ONREQUEST HOOK // ----------------------------------------------------------------- } ```` [Example Repo](https://github.com/luisorbaiceta/fastify-hooks-doubt) ## Environment - *node version*: 14 - *fastify version*: >=3.0.0 - *os*: Windows
https://github.com/fastify/fastify/issues/3120
https://github.com/fastify/fastify/pull/3122
caf108942b9009d17d638a1f4a581b37e4999465
94d37d9d39bd34c099ffd880bd3dc10ea905b38a
"2021-06-03T08:21:07Z"
javascript
"2021-06-05T16:02:33Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,110
["fastify.js", "lib/pluginUtils.js", "test/internals/version.test.js"]
Get version via hardcode/`require('package.json')`/other method instead of `fs.readFileSync`
## πŸš€ Feature Proposal Currently fastify loads its version via `JSON.parse(fs.readFileSync(pkgPath))`: https://github.com/fastify/fastify/blob/6278e7bc2102d57b54d88e9f47d6661a2e0a7624/fastify.js#L663-L666 ## Motivation I use webpack. webpack recognize `package.json` as an asset when it is used that way, and, as a result, fastify's `package.json` appears in the `dist/` output of my application. It creates confusion when there are two `package.json`. While of course I can remove it, that sets the `version` field of fastify to `undefined`, which is probably not ideal. ## Suggestion I suggest that we use a more deterministic method. The simplest and most deterministic way is to simply hardcode the version, which avoids all the loading and dependency on `package.json`. Alternatively we can `require('package.json')`, which allows webpack to bundle it.
https://github.com/fastify/fastify/issues/3110
https://github.com/fastify/fastify/pull/3113
06d9a5bfa366f0da6d3343235016d821817ef49a
9a13502237022db6a731795bbc548af0e8b907da
"2021-05-31T05:00:59Z"
javascript
"2021-05-31T14:25:18Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,107
["lib/handleRequest.js", "lib/reply.js", "lib/symbols.js", "lib/wrapThenable.js", "test/internals/handleRequest.test.js", "test/internals/reply.test.js", "test/wrapThenable.test.js"]
Strange promises behaviour in v3.16.x
<!-- Before you submit an issue we recommend you visit [Fastify Help](https://github.com/fastify/help) and ask any questions you have or mention any problems you've had getting started with Fastify. **Please read this entire template before posting any issue. If you ignore these instructions and post an issue here that does not follow the instructions, your issue might be closed, locked, and assigned the `missing discussion` label.** --> ## πŸ’₯ Regression Report Sorry for the long reproduction, took me a long time to dumb it down and I don't fully understand what is happening under the hood. for some reason Fastify started throwing reply-errors after upgrading to 3.16.2: `FastifyError: Promise may not be fulfilled with 'undefined' when statusCode is not 204` When I change the `reply.code(200).send('OK')` to `await reply.code(200).send('OK')` in my example the error dissapears... Whenever I remove the fastify-session + redis middleware it seems fine too. ## Last working version Worked up to version: 3.15.1 Stopped working in version: 3.16.2 ## To Reproduce Steps to reproduce the behavior: ```js const fastifyCookie = require('fastify-cookie') const fastifySession = require('fastify-session') const RedisStore = require('connect-redis')(fastifySession) const redis = require('redis') const fastify = require('fastify')({ logger: true, }) const redisClient = () => { const client = redis.createClient({ host: 'localhost', port: 6379, }) client.on('connect', function () { console.log('connected!') }) return client } fastify.register(fastifyCookie) fastify.register(fastifySession, { store: new RedisStore({ client: redisClient() }), secret: '12345678901234567890123456789012345678901234567890', saveUninitialized: true, cookie: { secure: false, }, }) fastify.get('/', async (request, reply) => { await new Promise(resolve => resolve()) // this is OK // await reply.code(200).send('OK') // this throws the error reply.code(200).send('OK') }) const start = async () => { try { await fastify.listen(5000) } catch (err) { fastify.log.error(err) process.exit(1) } } start() ``` ## Expected behavior A clear and concise description of what you expected to happen. ```js 3.15.1: {"level":30,"time":1622202218911,"pid":12964,"hostname":"DR","msg":"Server listening at http://127.0.0.1:5000"} connected! {"level":30,"time":1622202222116,"pid":12964,"hostname":"DR","reqId":"req-1","req":{"method":"GET","url":"/","hostname":"localhost:5000","remoteAddress":"127.0.0.1","remotePort":63196},"msg":"incoming request"} {"level":30,"time":1622202222124,"pid":12964,"hostname":"DR","reqId":"req-1","res":{"statusCode":200},"responseTime":7.853700011968613,"msg":"request completed"} 3.16.2: {"level":30,"time":1622202255749,"pid":15216,"hostname":"DR","msg":"Server listening at http://127.0.0.1:5000"} connected! {"level":30,"time":1622202259005,"pid":15216,"hostname":"DR","reqId":"req-1","req":{"method":"GET","url":"/","hostname":"localhost:5000","remoteAddress":"127.0.0.1","remotePort":63212},"msg":"incoming request"} {"level":50,"time":1622202259009,"pid":15216,"hostname":"DR","reqId":"req-1","err":{"type":"FastifyError","message":"Promise may not be fulfilled with 'undefined' when statusCode is not 204","stack":"FastifyError: Promise may not be fulfilled with 'undefined' when statusCode is not 204\n at fastify\\lib\\wrapThenable.js:28:30\n at processTicksAndRejections (node:internal/process/task_queues:96:5)","name":"FastifyError","code":"FST_ERR_PROMISE_NOT_FULFILLED","statusCode":500},"msg":"Promise may not be fulfilled with 'undefined' when statusCode is not 204"} {"level":30,"time":1622202259013,"pid":15216,"hostname":"DR","reqId":"req-1","res":{"statusCode":200},"responseTime":7.443599998950958,"msg":"request completed"} ``` ## Your Environment - *node version*: 16 - *fastify version*: >=3.16.0 - *os*: Windows / Linux - *any other relevant information*
https://github.com/fastify/fastify/issues/3107
https://github.com/fastify/fastify/pull/3108
6278e7bc2102d57b54d88e9f47d6661a2e0a7624
c5662920c4e2b43541d8ab9271c22dbe67019d89
"2021-05-28T12:02:46Z"
javascript
"2021-05-29T08:39:42Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,105
["lib/route.js", "test/versioned-routes.test.js"]
Unclear warning when `version` appears in the route declaration
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure it has not already been reported ### Fastify version 3.13 ### Plugin version _No response_ ### Node.js version 14.16 ### Operating system Linux ### Operating system version (i.e. 20.04, 11.3, 10) 20.04 ### Description if a route definition passed to `fastify.route` contains a `version: 1.0.0` instead of contraints: { version: 1.0.1 } `(node:187842) [FSTDEP006] FastifyDeprecation: You are decorating Request/Reply with a reference type. This reference is shared amongst all requests. Use onRequest hook instead. Property: %s` This warning is unclear and appears to incorrectly formatted with the `%s` specifier in the message. I spent a lot of time investigating plugins and my decoration of the fastify, requests and response until I tracked down the line the warning was being emitted on: https://github.com/fastify/fastify/blob/main/lib/route.js#L230 Which revealed the cause of the warning. On a related note all of the docs related to constraints(https://www.fastify.io/docs/latest/Routes/#constraints) contain invalid syntax specifying the constraint member: The docs show: `fastify.route({ method: 'GET', url: '/', { constraints: { version: '1.2.0'} }, handler: function (request, reply) { reply.send({ hello: 'world' }) } })` when they should show: `fastify.route({ method: 'GET', url: '/', constraints: { version: '1.2.0'}, handler: function (request, reply) { reply.send({ hello: 'world' }) } })` This is repeated through all the examples in the constraints section. ### Steps to Reproduce Run the following program: ``` const fastify = require('fastify')(); fastify.route({ method: 'GET', handler: () => {}, url: '/', version: '1.0.1', // constraints: { version: '1.0.1' }, }); fastify.listen(3000); ``` ### Expected Behavior This warning should indicate be worded like `You are decorating your routes with version, this property is expected to be in the constraints member`.
https://github.com/fastify/fastify/issues/3105
https://github.com/fastify/fastify/pull/3109
cb70ad9a4d7366a04f2ab32ec86c6bd076d3a4a3
06d9a5bfa366f0da6d3343235016d821817ef49a
"2021-05-27T21:52:19Z"
javascript
"2021-05-31T13:02:46Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,101
[".github/workflows/ci.yml", ".github/workflows/package-manager-ci.yml", ".gitignore", "fastify.d.ts", "package.json", "test/types/fastify.test-d.ts", "test/types/import.ts", "test/types/logger.test-d.ts", "types/logger.d.ts"]
Update to pino@7 when it is available
Update to pino@7 when it is available. This issue is a requirement for v4.
https://github.com/fastify/fastify/issues/3101
https://github.com/fastify/fastify/pull/3281
1ceaa35f6cb1dbdcd44e46be138db9f0277c5504
93165e46c7e9fa01375448f02fc6168f697cc98f
"2021-05-26T13:07:12Z"
javascript
"2021-09-04T21:59:32Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,099
["lib/reply.js", "test/internals/reply.test.js"]
reply handling
## πŸ’₯ Regression Report I think it should be related to the reply simplification. https://github.com/fastify/fastify-nextjs/pull/260 Not sure if it is only test case related only or production related. I am not using this plugin but it is worth knowing the test is currently failed. ## Last working version Worked up to version: 3.15.1 Stopped working in version: 3.16.1
https://github.com/fastify/fastify/issues/3099
https://github.com/fastify/fastify/pull/3100
0c39ac9ed322aed7672f28d35cedc41de69afc78
a848b0fba40f419c241679ecb6a1fe66bbaf9b01
"2021-05-26T05:32:20Z"
javascript
"2021-05-26T08:02:42Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,085
["examples/simple-stream.js", "lib/reply.js", "test/hooks.test.js", "test/internals/reply.test.js", "test/route.test.js", "test/stream.test.js"]
Invalid content type default for streams
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure it has not already been reported ### Fastify version 3.15.1 ### Node.js version 14.17 ### Operating system macOS ### Operating system version (i.e. 20.04, 11.3, 10) 11.2.3 ### Description Follow on from https://github.com/fastify/fastify-reply-from/issues/174 When receiving a response stream without a `content-type` then Fastify will set the `content-type` to `application/octet-stream` [here](https://github.com/fastify/fastify/blob/main/lib/reply.js#L143). In most instances this would be fine, however in the original scenario fastify is being used as a proxy and is receiving an empty stream response. Raising this issue to reference the fix as discussed in the comments of the original issue. ### Steps to Reproduce *From the original issue* ```JS const Fastify = require('fastify') const target = Fastify({ logger: true }) target.get('/', (request, reply) => { // added status 204 here reply.status(204).send(); }) const proxy = Fastify({ logger: true }) proxy.register(require('fastify-reply-from'), { base: 'http://localhost:3001/' }) proxy.get('/', (request, reply) => { reply.from('/') }) target.listen(3001, (err) => { if (err) { throw err } proxy.listen(3000, (err) => { if (err) { throw err } }) }) ``` ### Expected Behavior We should not assume any content type for stream responses.
https://github.com/fastify/fastify/issues/3085
https://github.com/fastify/fastify/pull/3086
74867a64c9c5fdbba7bfe9b8ee98a3dc44adafbe
1c752402d90722706916fb866e8dcf1d81748403
"2021-05-21T12:56:39Z"
javascript
"2021-05-24T14:51:43Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,075
["package.json", "test/types/fastify.test-d.ts"]
Fix type definition for latest @types/node version
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure it has not already been reported ### Fastify version 3.15.1/latest ### Node.js version 14.x ### Operating system Linux ### Operating system version (i.e. 20.04, 11.3, 10) 20.04 ### Description Looks like a release in `@types/node` minor broke our CI. More specifically in `Http2Server`. See: #3073 ### Steps to Reproduce From `fastify` source code: ```sh rm -rf node_modules/ npm i npm run test:typescript ``` ### Expected Behavior _No response_
https://github.com/fastify/fastify/issues/3075
https://github.com/fastify/fastify/pull/3076
1c3d4eeb8bae9aafaac29fdda1de5af9abb4bbbb
c74122833536c9b77ddc470ed67aea2d7fff7509
"2021-05-15T15:12:43Z"
javascript
"2021-05-15T16:31:17Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,057
["lib/reply.js", "test/hooks.test.js"]
After changing payload in onSend hook, Content-Length is not updated
### Prerequisites - [X] I have written a descriptive issue title - [X] I have searched existing issues to ensure it has not already been reported ### Fastify version 3.15.1 ### Node.js version 14.16.1 ### Operating system Linux ### Operating system version (i.e. 20.04, 11.3, 10) 20.04 ### Description I'm minifying payloads in onSend. Without explicitly setting Content-Length, the old Content-Length of the unmodified payload is sent. Probably the other relevant detail is that the payloads are generated by fastify-static and they use streams, so I'm draining the stream into a string which I then modify. ### Steps to Reproduce Here's the entire plugin: ```typescript 'use strict'; import fastifyPlugin from 'fastify-plugin'; import {FastifyPluginAsync} from 'fastify'; import htmlMinifier from 'html-minifier'; import {PassThrough} from 'readable-stream'; const streamToString = (stream: any): Promise<string> => { const chunks: Buffer[] = []; return new Promise((resolve, reject) => { stream.on('data', (chunk: any) => chunks.push(Buffer.from(chunk))); stream.on('error', (err: Error) => reject(err)); stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8'))); }); }; const minify = (s: string) => htmlMinifier.minify(s, { collapseBooleanAttributes: true, collapseWhitespace: true, minifyCSS: true, minifyJS: true, removeComments: true, removeEmptyAttributes: true, removeRedundantAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true, useShortDoctype: true, }); const plugin: FastifyPluginAsync = async (app, _options) => { app.addHook('onSend', async (_request, reply, payload) => { const contentType = reply.getHeader('Content-Type'); if (contentType && contentType.includes('text/html')) { if (payload instanceof PassThrough) { const content = minify(await streamToString(payload)); //reply.header('Content-Length', content.length); return content; } } }); }; export default fastifyPlugin(plugin); ``` ### Expected Behavior Content-Length should be set based on the new payload.
https://github.com/fastify/fastify/issues/3057
https://github.com/fastify/fastify/pull/3058
25fed20a2ad5010d8a01d3ecafa01f1cc3329466
64e6d970a982a5e55186dee41965acd1b943799c
"2021-05-06T20:21:17Z"
javascript
"2021-05-07T09:03:43Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,047
["lib/route.js", "test/route.test.js"]
declaring route with empty url crashes node
<!-- Before you submit an issue we recommend you visit [Fastify Help](https://github.com/fastify/help) and ask any questions you have or mention any problems you've had getting started with Fastify. **Please read this entire template before posting any issue. If you ignore these instructions and post an issue here that does not follow the instructions, your issue might be closed, locked, and assigned the `missing discussion` label.** --> ## πŸ› Bug Report if you declare a route with an empty url, fastify raises uncatchable exception that: - crashes node if you run it directly - causes a timeout if you run it with mocha ## To Reproduce Steps to reproduce the behavior: ```js import fastify from "fastify"; try { fastify().route({ method: "GET", url: "", async handler() { return {}; } }).ready().then(null, e => console.log(e, "catched async")); } catch (e) { console.log(e, "catched sync"); } ``` output: ``` % ts-node src {PWD}/node_modules/avvio/boot.js:545 func(err, cb) ^ TypeError: Cannot read property '0' of undefined at {PWD}/node_modules/fastify/lib/route.js:175:22 at Object._encapsulateThreeParam ({PWD}/node_modules/avvio/boot.js:545:7) at Boot.timeoutCall ({PWD}/node_modules/avvio/boot.js:447:5) at Boot.callWithCbOrNextTick ({PWD}/node_modules/avvio/boot.js:428:19) at Boot._after ({PWD}/node_modules/avvio/boot.js:273:26) at Plugin.exec ({PWD}/node_modules/avvio/plugin.js:131:17) at Boot.loadPlugin ({PWD}/node_modules/avvio/plugin.js:266:10) at Task.release ({PWD}/node_modules/fastq/queue.js:147:16) at worked ({PWD}/node_modules/fastq/queue.js:199:10) at {PWD}/node_modules/avvio/plugin.js:269:7 % echo $? 1 ``` ## Expected behavior error results in rejected promise ## Your Environment - *node version*: 12 - *fastify version*: 3.15.0 - *os*: Mac
https://github.com/fastify/fastify/issues/3047
https://github.com/fastify/fastify/pull/3049
647eda62772e3728eddbbef17898d28e2bd2699f
eff4e38c76fda54c8f50c86dcb9312b4c4db9bc1
"2021-04-29T17:27:53Z"
javascript
"2021-04-30T13:39:04Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,030
["lib/reply.js", "test/internals/reply.test.js"]
hasHeader returns false for existing response header
## πŸ› Bug Report There is an issue with hasHeader method of Reply. (https://www.fastify.io/docs/latest/Reply/#hasheaderkey) It returns false in the case of getHeader returning a value, however reply.raw.hasHeader returns true in the same case. ## To Reproduce Steps to reproduce the behavior: Try to add a header directly to reply via .raw anywhere in the code. (Found the place that does it in our code to check why it happens initially). Then you will be able to do getHeader normally, as it uses .raw object to do hasHeader: https://github.com/fastify/fastify/blob/73c0b6f598e0568dfd2944d715dfa7aa997ae457/lib/reply.js#L196-L200 But internal hasHeader function doesn't check that: https://github.com/fastify/fastify/blob/73c0b6f598e0568dfd2944d715dfa7aa997ae457/lib/reply.js#L212 ## Example code to illustrate ![image](https://user-images.githubusercontent.com/1105759/115752472-ccbe8700-a3a2-11eb-9695-0e933ece9330.png) Result: ![image](https://user-images.githubusercontent.com/1105759/115752692-05f6f700-a3a3-11eb-869a-4642ad53bd3c.png) ## Expected behavior hasHeader should return True for both cases ## Your Environment - *node version*: 15 - *fastify version*: latest - *os*: Mac
https://github.com/fastify/fastify/issues/3030
https://github.com/fastify/fastify/pull/3035
28febddefce64d91e2618fd14001211130a067ad
bcc41ac9d57301a1b02998b4a53b74026562e03d
"2021-04-22T16:48:38Z"
javascript
"2021-04-23T13:27:39Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,029
[".taprc", "test/before-tests.js", "test/build-certificate.js", "test/http2/closing.test.js", "test/http2/secure-with-fallback.test.js", "test/http2/secure.test.js", "test/https/custom-https-server.test.js", "test/https/https.test.js", "test/internals/initialConfig.test.js"]
Move the execution of test/before-test.js from .taprc to the actual test files that needs certs
See https://github.com/fastify/fastify/pull/3000#issuecomment-824976561 for more details.
https://github.com/fastify/fastify/issues/3029
https://github.com/fastify/fastify/pull/3032
ba43b314b156b39732dc614826806d4ef61700b8
d831ebdd5adffc35833b4c3643ef7bdb8ff8dde6
"2021-04-22T16:28:10Z"
javascript
"2021-04-22T20:11:54Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,026
["test/types/logger.test-d.ts", "types/logger.d.ts"]
[types] serializers
## πŸ› Bug Report serializers is missing type `ip` ## To Reproduce ```ts import fastify from 'fastify'; // Fastify instance const app = fastify({ logger: { prettyPrint: { levelFirst: true, translateTime: 'h:MM:ss TT', errorProps: 'message', ignore: 'pid,hostname,req,reqId,err,res,responseTime', messageFormat: '{req.method} {res.statusCode} {req.remoteAddress} {req.url} {msg}', }, serializers: { req(req) { /* c8 ignore next 5 */ return { method: req.method, url: req.url, remoteAddress: req.headers['X-Forwarded-For'] || req.ip, // <-- here }; }, }, }, }); // Root endpoint for ping app.get('/', {logLevel: 'error'}, async () => ({hello: 'world'})); export default app; ``` ## Expected behavior Should have valid IP type. ## Your Environment - *node version*: 14 - *fastify version*: 3.15.0 - *os*: Linux
https://github.com/fastify/fastify/issues/3026
https://github.com/fastify/fastify/pull/3034
f655dcf2e99d3dc6133462c07629eae0571b2d5f
1c3d4eeb8bae9aafaac29fdda1de5af9abb4bbbb
"2021-04-22T11:41:22Z"
javascript
"2021-05-14T09:59:29Z"
closed
fastify/fastify
https://github.com/fastify/fastify
3,003
["docs/Guides/Index.md", "docs/Guides/Prototype-Poisoning.md", "docs/Reference/Server.md"]
Add prototype poisoning doc to documentation
https://github.com/fastify/fastify/issues/1426#issuecomment-817957913
https://github.com/fastify/fastify/issues/3003
https://github.com/fastify/fastify/pull/3609
6363ff4eae89cd38dc8b901e5f9c23ce4d57bc0a
d7a23a0477cb5a03ba4b6c6d9736c420b1c7bfed
"2021-04-13T12:12:45Z"
javascript
"2022-01-11T13:29:15Z"
closed
fastify/fastify
https://github.com/fastify/fastify
2,994
["docs/ContentTypeParser.md", "fastify.js", "lib/contentTypeParser.js", "test/content-parser.test.js", "test/custom-parser.test.js", "test/types/content-type-parser.test-d.ts", "types/content-type-parser.d.ts", "types/instance.d.ts"]
catch-all addContentTypeParser doesn't fire if no content-type header in request
## πŸ› Bug Report Docs state `addContentTypeParser('*', ...` is a catch all to "catch all requests regardless of their content type" but the handler is not called if the request does not have a content-type header. Additionally, the catch-all does not fire for application/json because of the built-in parser. That makes sense, but I don't see a `removeContentTypeParser` or way to clear all existing parser. ## To Reproduce Steps to reproduce the behavior: ```ts import fastify, { FastifyReply } from 'fastify'; const port = 8000; const server = fastify(); server.post('/echo', async (request, reply) => { console.log('content-type', request.headers['content-type']); console.log('request.body', request.body); reply.status(200); reply.send(request.body); }); server.addContentTypeParser('*', (req, payload, done) => { console.log('catch all parser entered'); done(); }); ``` ```sh # catch-all parser not hit because content-type not sent # (on my machine curl won't send content-type if no data sent. ymmv) curl -X POST http://localhost:28588/echo # catch-all parser hit and works as expected curl -H 'content-type:whatever' -X POST -d '{}' http://localhost:28588/echo # catch-all not hit because built-in json parser handles the request (expected) curl -X POST -H 'content-type:application/json' -d '{}' http://localhost:28588/echo ``` ## Expected behavior - Catch-all should be called even when there is no content type - Additionally, it should be possible to remove or clear default parsers - And the docs should probably be changed to "catch all requests if no other matching parser exists" or something. I knew what it meant but if taken literally it's not doing what it says ## Your Environment - *node version*: 12.20.2 - *fastify version*: 3.14.2 - *os*: Mac I'm trying to always get the request body as a buffer. #707 was about that and the recommendation was to use a plugin. I couldn't get it to work probably because of what I outlined above.
https://github.com/fastify/fastify/issues/2994
https://github.com/fastify/fastify/pull/3210
52afb4a1ea9f1a7b9907219135e5b087b161acdd
5cf61fcbfa8b20f4b714af6d155d2740bae3d96b
"2021-04-11T00:46:25Z"
javascript
"2021-07-28T19:50:02Z"
closed
fastify/fastify
https://github.com/fastify/fastify
2,949
["CONTRIBUTING.md"]
Docs(contributing): clarification on sort order
<!-- Before you submit an issue we recommend you visit [Fastify Help](https://github.com/fastify/help) and ask any questions you have or mention any problems you've had getting started with Fastify. **Please read this entire template before posting any issue. If you ignore these instructions and post an issue here that does not follow the instructions, your issue might be closed, locked, and assigned the `missing discussion` label.** --> ## πŸ› Bug Report Under [onboarding-collaborators](https://github.com/fastify/fastify/blob/master/CONTRIBUTING.md#onboarding-collaborators) in `CONTRIBUTING.md` it states: > The members lists are sorted alphabetically; make sure to add your name in the proper order. Should they be sorted alphabetically ascending or descending, and on first name or surname?
https://github.com/fastify/fastify/issues/2949
https://github.com/fastify/fastify/pull/2950
3d1c0c84b610aafc9911f597764828babefe29f4
4e0cf70938677d042deb12475785ba9578157057
"2021-03-23T06:58:27Z"
javascript
"2021-03-23T09:59:09Z"
closed
fastify/fastify
https://github.com/fastify/fastify
2,941
["lib/reply.js", "test/schema-serialization.test.js"]
Inconsistency between validation/errorHandler and serializer causes request timeout
## πŸ› Bug Report The following example causes a request timeout although it shouldn't. In general, the semantics of a response serializer are a but unclear in combination with the (default) error handler. ## To Reproduce Steps to reproduce the behavior: ```js const fastify = require("fastify")({ logger: { prettyPrint: true }, }); const requiresFoo = { properties: { foo: { type: "string" } }, required: ["foo"], }; const someUserErrorType1 = { type: "string" }; const someUserErrorType2 = { properties: { code: { type: "number" }, }, required: ["code"], }; fastify.get( "/1", { schema: { query: requiresFoo, // Not reponse schema here }, }, (request, reply) => { reply.code(400).send({ isOk: false }); } ); fastify.get( "/2", { schema: { query: requiresFoo, response: { 400: someUserErrorType1 }, }, }, (request, reply) => { reply.code(400).send("some error"); } ); fastify.get( "/3", { schema: { query: requiresFoo, response: { 400: someUserErrorType2 }, }, }, (request, reply) => { reply.code(400).send({ code: 42 }); } ); fastify.listen(8080, function (err) { if (err) { throw err; } }); ``` Testing the three routes via curls results in: ``` $ curl 'http://127.0.0.1:8080/1?notfoo=string' {"statusCode":400,"error":"Bad Request","message":"querystring should have required property 'foo'"} $ curl 'http://127.0.0.1:8080/2?notfoo=string' "Error: querystring should have required property 'foo'" $ curl 'http://127.0.0.1:8080/3?notfoo=string' <hangs until timeout> ``` ## Expected behavior I assume the timeout shouldn't occur. In general it is the question whether the schema serializer should be applied to responses generated from the error handler or not. - On the one hand it feels weird that the serializer operates on responses generated by the error handler. Basically when a user writes a response schema `400: MyReponseSchema`, the user only has the user-provided route handler in mind. From the local code perspective that it all that matters. However to get it right, the user has to have knowledge of the (global) error handler. For instance, the user has to find out: Can the error handler produce a 400 as well, and with what schema? Then the user has two options: (1) Extend the local schema definition to something like `400: { anyof: [MyReponseSchema, PossibleResponseFromErrorHandler] }`. (2) Alternatively the user can take control over the error handler so that its response somehow matches `MyReponseSchema`. - On the other hand, not applying the serializer to error handler responses means that the check is comprehensive and when generating TypeScript types based on the JSON schemas, there would be certain response that are under the radar. I feel like the latter is less of an issue, because the response schema validation is per status code anyway, so from a TypeScript perspective we are talking about a potentially incomplete union type anyway (something like `TypeFor200 | TypeFor400 | ... | unknown`). ----- The difference between route `/1` and `/2` shows another subtlety. After having seen the "normal" response in `/1` and knowing that a non-matching schema leads to a timeout, I was expecting `/2` to timeout as well. However, presumably the error handler returns an `Error` instance, and ajv coercing rules allow that to be coerced to string. This highlights that applying the user provided schema to the response from the error handler can have quite tricky side-effects like: ```js const MyReponseSchema = { type: "string" } const ValidationError = { properties: { statusCode: { type: "number" }, error: { type: "string" }, message: { type: "string" }, } } // now consider const ResponseSchema1 = { 400: { anyOf: [MyReponseSchema, ValidationError] }} const ResponseSchema2 = { 400: { anyOf: [ValidationError, MyReponseSchema] }} // I would assume the two to behave differently, because applying MyReponseSchema first // can coerce to string, returning e.g. "Error: querystring should have required property 'foo'" // whereas applying ValidationError first would result in a response: // {"statusCode":400,"error":"Bad Request","message":"querystring should have required property 'foo'"} ``` ## Your Environment - *node version*: v14.16.0 - *fastify version*: 3.14.0 - *os*: Ubuntu 18.04
https://github.com/fastify/fastify/issues/2941
https://github.com/fastify/fastify/pull/2942
701804c3bb2f38526b38bbab2bf13c1c1d7fb8a0
3460ddab5c87b8baa0cd7a93a2c7d34e86d535fb
"2021-03-18T19:53:32Z"
javascript
"2021-03-20T13:59:12Z"
closed
fastify/fastify
https://github.com/fastify/fastify
2,930
["fastify.d.ts", "test/types/content-type-parser.test-d.ts", "test/types/instance.test-d.ts", "types/content-type-parser.d.ts", "types/instance.d.ts"]
Missing types for getDefaultJsonParser and defaultTextParser
<!-- Before you submit an issue we recommend you visit [Fastify Help](https://github.com/fastify/help) and ask any questions you have or mention any problems you've had getting started with Fastify. **Please read this entire template before posting any issue. If you ignore these instructions and post an issue here that does not follow the instructions, your issue might be closed, locked, and assigned the `missing discussion` label.** --> ## πŸ› Bug Report When trying to access the default json parser oder default text parser via the `getDefaultJsonParser()` and `defaultTextParser()` methods the TypeScript compiler throws an error. ## To Reproduce Steps to reproduce the behavior: ```js const server: FastifyInstance = fastify() // Error: Property 'getDefaultJsonParser' does not exist on type 'FastifyInstance'. server.getDefaultJsonParser('ignore', 'ignore') ``` ## Expected behavior There should be typings for the two methods. ## Your Environment - *node version*: 14 - *fastify version*: >=3.13.0 - *os*: Mac
https://github.com/fastify/fastify/issues/2930
https://github.com/fastify/fastify/pull/2951
5d4379b5e9cfa0110d9e7acad9d9f9c2ad234a83
e995839520cd6d865ac0932126dc7e99585b7cd6
"2021-03-11T13:30:08Z"
javascript
"2021-03-23T14:23:44Z"
closed
fastify/fastify
https://github.com/fastify/fastify
2,914
["lib/route.js", "package.json", "test/schema-special-usage.test.js"]
Schema with key or id already exists error after upgrading to 3.12.0
## πŸ’₯ Regression Report After having installed 3.12.0 my app stopped booting and this error popped up: ``` Error: schema with key or id "CircleEventShow" already exists ``` My schemas use arrays with `$ref` to reference other schemas and it seems they are fully expanded instead of only referenced, copying the `$id` field and causing this duplicate key or id error. As per @Eomm request I am opening a new issue as this seems to be different from the error encountered in #2901. My app is split into self-contained "route plugins" and I use `fastify.register` to load each endpoint. If not using `fastify.register` the code would constantly raise the schema error, even in versions prior to 3.12.0. ## Last working version Worked up to version: 3.11.0 Stopped working in version: 3.12.0 ## To Reproduce Steps to reproduce the behavior: ```js import fastify from "fastify" import fastifyPlugin from "fastify-plugin" import S from "fluent-json-schema" const ShowSchema = S.object().id("ShowSchema").prop("name", S.string()) const ListSchema = S.array().id("ListSchema").items(S.ref("ShowSchema#")) const app = fastify({ logger: true, }) app.addSchema(ListSchema) app.addSchema(ShowSchema) const defaultRouteOptions = { schema: { response: { 200: S.ref("ListSchema#") } }, } app.register( async (app) => { app.get("/resource/", defaultRouteOptions, () => ({})) }, { prefix: "/prefix1" } ) app.register( async (app) => { app.get("/resource/", defaultRouteOptions, () => ({})) }, { prefix: "/prefix2" } ) try { await app.listen(4000) } catch (err) { app.log.error(err) process.exit(1) } ``` ## Expected behavior I expect my app to boot fine. ## Your Environment - *node version*: 15.10.0 - *fastify version*: 3.12.0 - *os*: Linux
https://github.com/fastify/fastify/issues/2914
https://github.com/fastify/fastify/pull/2925
c50b879ed622426689893e465280b46c939789ff
53e3e792ebd5aba68be94f753f48d2e9b2ed832c
"2021-03-07T22:51:43Z"
javascript
"2021-03-16T16:12:48Z"
closed
fastify/fastify
https://github.com/fastify/fastify
2,906
[".github/labeler.yml", ".github/workflows/labeler.yml"]
Auto label PR
## πŸš€ Feature Proposal Add a GH Action that adds: - the `documentation` label when an issue or PR has the `docs` string on the title or only the `docs/` folder has been edit - the `typescript` label only when a PR changes the `type/` folder or `fastify.d.ts` file (should be possible with `paths-ignore`) ## Motivation Better search tags/filter
https://github.com/fastify/fastify/issues/2906
https://github.com/fastify/fastify/pull/2908
0af94651ee311f9637bed97ab255b4f5173d5837
29200ee5b84b66f8c81ac50ae9fa37847e84b65a
"2021-03-06T11:22:47Z"
javascript
"2021-03-08T17:35:51Z"
closed
fastify/fastify
https://github.com/fastify/fastify
2,902
["test/types/logger.test-d.ts", "types/logger.d.ts"]
Breaking change in typing for error
In upgrading to the latest fastify, we see a change in the parameter type for err From an object to a string. Was this intentional? ## πŸ› Bug Report ![image](https://user-images.githubusercontent.com/1200635/110139385-f561d180-7da0-11eb-842b-b8cbd56d9d6f.png) A clear and concise description of what the bug is. ## To Reproduce Steps to reproduce the behavior: ``` server.log.error(err); ``` ## Expected behavior Typing to accept an err object as previous release did.
https://github.com/fastify/fastify/issues/2902
https://github.com/fastify/fastify/pull/2926
7f9bdda6088fc0d0c1573405007ddec04b927e72
3510c7ea41d2f4135b8f889dc0b7b2db479b56c2
"2021-03-05T15:54:57Z"
javascript
"2021-03-09T13:51:09Z"
closed
fastify/fastify
https://github.com/fastify/fastify
2,901
["package.json", "test/schema-special-usage.test.js"]
Schema with key or id "<$id>" already exists
<!-- Before you submit an issue we recommend you visit [Fastify Help](https://github.com/fastify/help) and ask any questions you have or mention any problems you've had getting started with Fastify. **Please read this entire template before posting any issue. If you ignore these instructions and post an issue here that does not follow the instructions, your issue might be closed, locked, and assigned the `missing discussion` label.** --> ## πŸ› Bug Report When using [`oneOf`](https://json-schema.org/understanding-json-schema/reference/combining.html#oneof) fastify fails with `FST_ERR_SCH_VALIDATION_BUILD` when a request is injected. ## To Reproduce Steps to reproduce the behavior: ```js const app = fastify(); const first_schema = { $id: "example1", type: "object", properties: { name: { type: "string", }, }, }; app.addSchema(first_schema); const reused_schema = { $id: "example2", type: "object", properties: { name: { oneOf: [ { $ref: "example1", }, ], }, }, }; app.get( "/a", { schema: { body: reused_schema, response: { 200: reused_schema, }, }, }, async () => "OK-A" ); app.get( "/b", { schema: { body: reused_schema, response: { 200: reused_schema, }, }, }, async () => "OK-B" ); await app.inject().get("/"); ``` ## Expected behavior I'm expecting an error before request is handled. Maybe schema resolvers are not well referencing the used schemas? Not sure about the issue behind this. ## Your Environment - *node version*: v15.11.0 - *fastify version*: >= 3.13.0 - *os*: Mac
https://github.com/fastify/fastify/issues/2901
https://github.com/fastify/fastify/pull/2923
bba7de46d70128c246c9ee5428da6b73963b2a3e
cc134942aaa3b66bbecbada459b5deb17471ef8c
"2021-03-05T15:43:17Z"
javascript
"2021-03-08T22:10:37Z"