Home > Net >  How to use .env file variables with typescript?
How to use .env file variables with typescript?

Time:10-30

I am saving my jwt token secret into the .env file.

JWT_SECRET="secretsecret"

Now when I try to fetch the value using process.env.JWT_SECRET I get error as

Argument of type 'string | undefined' is not assignable to parameter of type 'Secret'

I am trying to learn typescript but facing this issue with .env please guide me.

CodePudding user response:

First of all, to load the environment constants (.env file) into your program you must install dotenv (npm install dotenv --save) and add the following into the .ts file:

import * as dotenv from 'dotenv'
dotenv.config()

Note: set it at the top of the .ts file.

CodePudding user response:

Environment variables are supported out of the box with Node and are accessible via the env object (which is a property of the process global object.)

To see this in action, you can create your own environment variable right in the Node REPL by appending a variable to the process.env object directly.

To create environment variables in your Node app, you will probably want to use a package like DotEnv.

DotEnv is a lightweight npm package that automatically loads environment variables from a .env file into the process.env object.

To use DotEnv, first install it using the command: npm i dotenv Then in your app, require and configure the package like this: require('dotenv').config()

You can declare multiple variables in the .env file. For example, you could set database-related environment variables like this:

DB_HOST=localhost
DB_USER=admin
DB_PASSWORD=password

There is no need to wrap strings in quotation marks. DotEnv does this automatically for you.

Accessing your variables is super easy! They are attached to the process.env object, so you can access them using the pattern process.env.KEY.

enter image description here

CodePudding user response:

The error is arising because a parameter of typeSecret is required but process.env.JWT_SECRET is of type string|undefined

To resolve this issue import {Secret} from "jsonwebtoken" and add process.env.JWT_SECRET as Secret instead of just process.env.JWT_SECRET

  • Related