fastify-type-provider-zod
fastify-type-provider-zod copied to clipboard
validation fail for params of type numbers. expects a string
example: the following route if you open http://127.0.0.1:3003/x/12 it will fail expected number, received string.
fastify.withTypeProvider<ZodTypeProvider>().get("/x/:n", {
schema: {
params: z.object({ n: z.number() }),
response: {
200: z.object({ n: z.number() }),
},
},
handler: ({ params: { n } }) => {
return { n };
},
});
You need to use .coerce for query and path params, as these always are passed as strings, because fastify has no way to establish their true type
example: the following route if you open
http://127.0.0.1:3003/x/12it will failexpected number, received string.fastify.withTypeProvider<ZodTypeProvider>().get("/x/:n", { schema: { params: z.object({ n: z.number() }), response: { 200: z.object({ n: z.number() }), }, }, handler: ({ params: { n } }) => { return { n }; }, });
just like this:
fastify.withTypeProvider<ZodTypeProvider>().get("/x/:n", {
schema: {
params: z.object({n: z.coerce.number()}),
response: {
200: z.object({n: z.number()}),
},
},
handler: ({params: {n}}) => {
return {n};
},
});