How I can sign jwt accesstoken in node using typescript

I want to sign an jwt accestoken, when the user gets logged in. I done this before without typescript like this:

 const accessToken = jwt.sign(
            {id: user!._id,
             isAdmin:user!.isAdmin,
            },
            process.env.JWT_SEC,
            {expiresIn:"30d"}
        )

I setted the both exclamation marks for telling typescript that the values cannot be null. But it underlines me process.env.JWT_SEC and tells me:

No overload matches this call.
The overload 1 of 3 (payload: string | object | Buffer, secretOrPrivateKey: Secret, options?: SignOptions | undefined): string) caused the following error.
The string | argument undefined" cannot be assigned to the Secret parameter.

Thank you for your help.

1 Like

Do you resolver this issue? I’m facing the same problem

Yes, you must tell typescript, that there is a string in the .env. For that I put it in into a variable. let sec:string = process.env.JWT_SEC as string;
And then set the variable into the jwt.sign:

const accessToken = jwt.sign(
            {id: user!._id,
             isAdmin:user!.isAdmin,
            },
            sec,
            {expiresIn:"30d"}
        )

Hope that helps.