Reputation: 584
I have created an environment plugin to load data from a .env file and another plugin to handle cookies in my Fastify application. However, when I try to use the environment configuration in the cookie plugin, TypeScript throws an error:
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 Plugin:
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;
That's how i register plugins:
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;
And that's how I added config type:
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 };
}
}
Upvotes: 1
Views: 272