Monday, July 4, 2022

How to access environment variable from Fastify server?

 We can easy access the environment variable from the express server with help from dotenv library. we can just need to add this following line the Server.ts or Index.ts file, then we can access the environment variable.

require('dotenv').config();
 app.use(
    cors({
      origin: __prod__
        ? process.env.CORS_ORIGIN_PROD
        : process.env.CORS_ORIGIN_DEV,
      credentials: true
    })
  )

In the server, we can't not simply assign the JWT_SECRET that stored in the environment setting as we usually did in the express server. In the fastify server, we should create a Constant.ts file to store the code above, the we import the Constant.ts into Server.ts file.

require('dotenv').config();

export const DB_CONNECTION_STRING =
  process.env.DB_CONNECTION_STRING ||
  "mongodb://localhost:27017/password-manager";

export const CORS_ORIGIN = process.env.CORS_ORIGIN || "http://localhost:3000";

export const COOKIE_DOMAIN = process.env.COOKIE_DOMAIN || "localhost";

export const JWT_SECRET= process.env.JWT_SECRET || "jwt-secret-key";

Server.ts 

import { JWT_SECRET } from "../constant";
 app.register(fastifyJwt, {
    secret: JWT_SECRET,
    cookie: {
        cookieName: "token",
        signed: false,
    },
    });



No comments:

Post a Comment