You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Fastify中TypeScript报错:FastifyInstance不存在config属性

解决Fastify中Cookie插件访问环境配置的TypeScript类型错误

我在Fastify应用中创建了两个插件:一个用于从.env文件加载环境变量,另一个处理Cookie逻辑。但在Cookie插件中访问环境配置时,TypeScript抛出以下错误:

TSError: ⨯ Unable to compile TypeScript:
src/plugins/cookie.ts:7:34 - error TS2339: Property 'config' does not exist on type 'FastifyInstance

环境插件代码

import fp from "fastify-plugin";
import Env from "@fastify/env";
import { FastifyInstance } from "fastify";

const jwtConfig = {
  type: "object",
  required: ["JWT_SECRET", "COOKIE_SECRET"],
  properties: {
    JWT_SECRET: { type: "string" },
    COOKIE_NAME: { type: "string", default: "token" },
    COOKIE_SECRET: { type: "string", default: "cookie-secret" },
  },
};

const serverConfig = {
  type: "object",
  properties: { PORT: { type: "string", default: "8080" } },
};

const envPlugin = fp(async (fastify: FastifyInstance, opts: any) => {
  fastify.register(Env, {
    confKey: "config",
    schema: {
      type: "object",
      properties: {
        ...jwtConfig.properties,
        ...serverConfig.properties,
      },
      required: [...jwtConfig.required],
    },
    dotenv: true,
  });
});

export default envPlugin;

Cookie插件代码

import fastifyCookie from "@fastify/cookie";
import { FastifyInstance } from "fastify";
import fp from "fastify-plugin";

const cookiePlugin = fp(async (fastify: FastifyInstance, opts: any) => {
  const cookieSecret = (fastify as any).config.COOKIE_SECRET;

  fastify.register(fastifyCookie, { secret: cookieSecret, parseOptions: {} });
});

export default cookiePlugin;

插件注册代码

import fastify from "fastify";
import envPlugin from "./plugins/env";
import cookiePlugin from "./plugins/cookie";

const server = fastify({ logger: true });

server.register(envPlugin);

server.register(cookiePlugin);

server.get("/ping", async (request, reply) => {
  return "pong\n";
});

export default server;

自定义类型声明文件

import "fastify";

declare module "fastify" {
  interface FastifyInstance {
    authenticate: (
      request: FastifyRequest,
      reply: FastifyReply
    ) => Promise<void>;
    config: {
      JWT_SECRET: string;
      COOKIE_NAME: string;
      PORT: string;
      COOKIE_SECRET: string;
    };
  }

  interface FastifyRequest {
    user?: { id: string; email: string };
  }
}

解决步骤

  1. 确保类型声明文件被TypeScript识别

    • 自定义类型声明文件建议命名为fastify.d.ts,放在项目的src/types目录下
    • 在tsconfig.json的include数组中添加该文件路径,确保TypeScript能扫描到:
      {
        "include": ["./src/**/*", "./src/types/**/*.d.ts"]
      }
      
  2. 保证插件加载顺序与依赖关系
    当前Env插件和Cookie插件是并行注册的,Cookie插件可能在Env插件完成初始化前就执行,导致fastify.config未挂载。可以通过两种方式解决:

    • 方式一:按顺序注册
      修改插件注册代码,让Cookie插件在Env插件初始化完成后再注册:
      server.register(envPlugin).after(() => {
        server.register(cookiePlugin);
      });
      
    • 方式二:声明插件依赖
      在Cookie插件的fp配置中声明依赖Env插件,Fastify会自动保证加载顺序:
      const cookiePlugin = fp(async (fastify: FastifyInstance, opts: any) => {
        const cookieSecret = fastify.config.COOKIE_SECRET;
        fastify.register(fastifyCookie, { secret: cookieSecret, parseOptions: {} });
      }, {
        dependencies: ['@fastify/env']
      });
      
  3. 移除不必要的类型断言
    当类型声明生效且插件依赖正确后,就不需要(fastify as any)的类型断言了,直接访问fastify.config.COOKIE_SECRET即可,TypeScript会自动识别config属性。


内容的提问来源于stack exchange,提问作者Nazar Duma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 21:54:53