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?
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
}