14

I'm using dotenv to declare JWT_SECRET env variable and It's showing the error mentioned in title.

.env

NODE_ENV="development"
JWT_SECRET="mySecretString"

environment.d.ts

import { Secret } from 'jwt-promisify'

declare global {
    namespace NodeJS {
        interface ProcessEnv {
            JWT_SECRET: Secret,
            NODE_ENV: 'development' | 'production',
            PORT?: number | string
        }
    }
}

export {}

I'm using in my routes file im signing token with JWT_SECRET

route.ts

const token = await jwt.sign({ id: newUser.id }, process.env.JWT_SECRET)

Here intellisense is working but when I run the app or compile it the error appears.

error

error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'Secret'.
  Type 'undefined' is not assignable to type 'Secret'.

32         const token = await jwt.sign({ id: newUser.id }, process.env.JWT_SECRET)
                                                            ~~~~~~~~~~~~~~~~~~~~~~

4
  • do you use import dotenv from 'dotenv' dotenv.config() in the top of file? Feb 23, 2021 at 9:07
  • yes i'm using it in app.ts Feb 23, 2021 at 9:07
  • I think you should use in every file that you want use process.env Feb 23, 2021 at 9:08
  • I don't think so because when i was using Node.js in previous project i just required dotenv in app.js only then it worked with other files as well Feb 23, 2021 at 10:07

3 Answers 3

44
  jwt.sign(data, process.env.SIGNATURE_KEY as string, {
        expiresIn: '30d',
        algorithm: "HS256"
    }, (err, encoded)=>{
        err ? reject(err) : resolve(encoded)
    })

For Typescript, I think Type casting works. I also didn't implement async-await because the sign method wasn't hinted as a Promise. But I guess it works too!

3

First solution

just use ! right after process.env.JWT_KEY actually, exclamation (!) says, hey typescript, don't worry, don't check this.

const userJwt = jwt.sign({
   id: newUser.id 
}, process.env.JWT_KEY!);

And in the startup project(index.ts), when I want to load the database config, etc add the below condition

‍‍‍//index.ts
const start = async () => {
  try {
    if(!process.env.JWT_KEY){
      throw new Error('JWT_KEY must be defined')
    }
    //Connect to database or ...
  } catch (error) {
    console.log(error)
  }
}

Second solution

Because if you check the JWT_KEY before using jwt.sign like the below code, the problem will be solved without using ! after process.env.JWT_KEY, but the first solution is better

if(!process.env.JWT_KEY){
  throw new Error('JWT_KEY must be defined')
}
const userJwt = jwt.sign({
  id: user.id,
}, process.env.JWT_KEY);
-2

The problem here is that typeof process.env.JWT_SECRET is either string or undefined. So you could do:

const token = await jwt.sign({ id: newUser.id }, process.env.JWT_SECRET || "")
2
  • 5
    Do you seriously suggest to sign with an empty (or any other hardcoded) string?
    – zerkms
    Mar 19, 2021 at 8:20
  • I was just pointing out the issue, he can manage it however he wants. Anyhow, please add your suggestion too Mar 24, 2021 at 8:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.