Fastify decorate未注册中间件:TypeScript中authenticate装饰器报错
Fastify TypeScript环境下JWT认证装饰器未识别问题
我将原生JS的JWT校验中间件转为TypeScript后,使用fastify.decorate注册的authenticate方法,在路由中调用时提示类型错误,找不到该属性。
相关代码
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(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();
路由调用(报错位置)
fastify.post<{ Body: MatchAttributes }>( "/matches", { onRequest: [fastify.authenticate], }, async (request, reply) => { // 路由逻辑 } );
报错信息
Property 'authenticate' does not exist on type 'FastifyInstance<RawServerDefault, IncomingMessage, ServerResponse
, FastifyBaseLogger, FastifyTypeProviderDefault>'.ts(2339)
解决步骤
1. 添加Fastify类型扩展声明
在项目中创建fastify.d.ts类型声明文件,扩展FastifyInstance接口:
import { FastifyRequest, FastifyReply } from "fastify"; declare module "fastify" { interface FastifyInstance { authenticate: (request: FastifyRequest, reply: FastifyReply) => Promise<void>; } }
2. 配置TypeScript识别声明文件
修改tsconfig.json的include字段,确保包含上述声明文件:
{ "compilerOptions": { // 其他配置 }, "include": [ "src/**/*.ts", "fastify.d.ts" // 加入此行 ] }
3. 优化插件泛型定义
去掉authMiddleware.ts中fastify-plugin的显式泛型参数,让类型自动推断:
// 原代码 const authenticatePlugin = fp<FastifyInstance>(async (fastify, opts) => { // 修改后 const authenticatePlugin = fp(async (fastify, opts) => {
完成以上操作后,TypeScript就能正确识别fastify.authenticate装饰器,不会再抛出类型错误。
内容的提问来源于stack exchange,提问作者cw23
相关产品推荐
相关产品推荐

