I'm having an issue with my Fastify + TypeScript application. When I try to use the authenticate method in my routes, TypeScript gives me the following error:
Property 'authenticate' does not exist on type 'FastifyInstance<RawServerDefault, IncomingMessage, ServerResponse<IncomingMessage>, FastifyBaseLogger, FastifyTypeProviderDefault>'.
This is the code that's causing the problem:
import { FastifyInstance, FastifyPluginOptions } from "fastify";
import { UserController } from "../controllers/UserController";
const userRoutes = async (
fastify: FastifyInstance,
options: FastifyPluginOptions
) => {
fastify.addHook("preHandler", fastify.authenticate);
fastify.get("/", UserController.getUsers);
fastify.get("/:id", UserController.getUserById);
fastify.get("/mail/:mail", UserController.getUserByMail);
fastify.get("/user/:user", UserController.getUserByUser);
};
export default userRoutes;
I've already tried:
- Decorating the Fastify instance with the authenticate method in my main file:
import fastify, { FastifyReply, FastifyRequest } from "fastify";
import { connectDB } from "./config/db";
import userRoutes from "./routes/userRoutes";
import projectsRoutes from "./routes/projectRoutes";
import fastifyJwt from "@fastify/jwt";
const app = fastify({ logger: true });
app.register(fastifyJwt, {
secret: process.env.SECRET_KEY || "secret_key",
});
app.decorate("authenticate", async function (request, reply) {
try {
await request.jwtVerify();
} catch (err) {
reply.send(err);
}
});
app.register(userRoutes, { prefix: "/api/v1/user" });
app.register(projectsRoutes, { prefix: "/api/v1/project" });
connectDB();
export default app;
- Creating a type definition file in
src/types/fastify.d.ts
:
import "fastify";
declare module "fastify" {
export interface FastifyInstance {
authenticate: any;
}
}
- My
tsconfig.json
configuration:
{
"compilerOptions": {
"typeRoots": ["./node_modules/@types", "./src/types"],
"outDir": "./dist",
"rootDir": "./src",
"lib": ["esnext"],
"target": "ESNext",
"moduleResolution": "NodeNext",
"module": "NodeNext",
"strict": false,
"sourceMap": true,
"esModuleInterop": true,
"declaration": true
},
"include": ["src/**/*.ts"]
}
Full error output:
/home/user/project/node_modules/ts-node/src/index.ts:859
return new TSError(diagnosticText, diagnosticCodes, diagnostics);
^
TSError: ⨯ Unable to compile TypeScript:
src/routes/userRoutes.ts:8:41 - error TS2339: Property 'authenticate' does not exist on type 'FastifyInstance<...>'.
8 fastify.addHook("preHandler", fastify.authenticate);
~~~~~~~~~~~~