Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

node.js - use ENV variable inside jwt sign

I am using JWT in my system and it pretty much works fine which I use a regular String for my SecretKey here is the working code

export class CompanyResolver {

  @Query(() => [Company])
  companies() {
    return Company.find();
  }

  @Query(() => Company)
  async login(
    @Arg("email") email: string,
    @Arg("password") password: string,
  ): Promise<Company | null> {
    const company = await Company.findOne({ where: { email } });

    if (!company)
      throw new Error("Company Not Found!!!");

    if (!await bcrypt.compare(password, company.password))
      throw new Error("Incorrect Password!!!");

    const secret=process.env.JWT_SECRET;  

    console.log(secret)

     company.accessToken = jsonwebtoken.sign({ company }, "12345", {
       expiresIn: "30 days"
     })
    return company;
  }

I have defined my secret in my env file which upon doing console.log(process.env.JWT_SECRET) does give me back my key which means there is not issue in that however the issue is when I try to use it

company.accessToken = jsonwebtoken.sign({ company }, secret, {
           expiresIn: "30 days"
         })

I get

Type 'undefined' is not assignable to type 'Secret'.

I'm a newbie to nodejs and TS I apologize in advance for any childish mistake, can someone point out the issue?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

process.env value type is string | undefined. This means Typescript is not guaranteeing you that there must be string type returned for every process.env.MY_ENV_VAR. It may possibly return undefined if the environment variable is not set, so, take your precaution.

In this case, something like this should help

if(secret){
  company.accessToken = jsonwebtoken.sign({ company }, secret, {
           expiresIn: "30 days"
         })
} else {
  // Handle the case where the variable is not set, may be throw exception
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...