In the process of crafting middleware for scrutinizing the JWT transmitted during route invocations, I meticulously adhered to the guidelines stipulated in the JWT middleware manual and ported the code to TypeScript from vanilla JS. Regrettably, an anomaly arises where fastify.decorate
fails to acknowledge the newly designed decorator earmarked for invocation on requests.
authMiddleware.ts
import fp from "fastify-plugin";
import fastifyJwt from "@fastify/jwt";
import { FastifyInstance, FastifyRequest, FastifyReply } from "fastify";
const authenticatePlugin = fp<FastifyInstance>(async (fastify, opts) => {
fastify.register(fastifyJwt, {
secret: "secret",
});
fastify.decorate(
"authenticate",
async (request: FastifyRequest, reply: FastifyReply) => {
try {
await request.jwtVerify();
} catch (err) {
reply.send(err);
}
}
);
});
export default authenticatePlugin;
Index.ts(entry point to api)
const server = fastify({
logger: pino({ level: "info" }),
});
server.register(authenticatePlugin);
server.register(db, { uri });
server.register(MatchRoute);
server.register(AuthRoutes);
const start = async () => {
try {
await server.listen({ port: 7000 });
console.log("Server started successfully");
} catch (err) {
server.log.error(err);
process.exit(1);
}
};
start();
The root cause is pinpointed within my route:
fastify.post<{ Body: MatchAttributes }>(
"/matches",
{
onRequest: [fastify.authenticate],
},
async (request, reply) => {
An error crops up upon invoking fastify.authenticate
:
Property 'authenticate' does not exist on type 'FastifyInstance<RawServerDefault, IncomingMessage, ServerResponse<IncomingMessage>, FastifyBaseLogger, FastifyTypeProviderDefault>'.ts(2339)