Jakub
Jakub

Reputation: 2729

Why token expiration time passed via env var not working

I have created the NodeJS API and an Auth system with in it using JWT. I set the token expiration in my env but in this way its not working and I have to write manually the time inside my function.

My function is a helper:

// RNV
const { Config } = require("../config");
// JWT
const jwt = require("jsonwebtoken");

// Token helper
module.exports = {
    getToken: user => jwt.sign(user, Config.jwt.secret, { expiresIn: <ENV> })
};

It seems to be not working this way and I would like to understand the reason for it.

Upvotes: 0

Views: 2136

Answers (2)

Jakub
Jakub

Reputation: 2729

Answering my question as I found a solution to my problem and maybe can be discussed :)

As from ENV is a String I had to convert it to a number int as it is accepting it the expiresIn and I used parseInt(<env string>) to get the right thing actually

// ENV
const { Config } = require("../config");
// JWT
const jwt = require("jsonwebtoken");

// Token helper
module.exports = {
    getToken: user => jwt.sign(user, Config.jwt.secret, { expiresIn: parseInt(Config.jwt.expiration) } )
};

Upvotes: 1

matheusopedro
matheusopedro

Reputation: 149

You should try something like this: proccess.env.JWT_EXPIRE.

// You env variable    
JWT_EXPIRE=12h

Then, in your javascript code:

// RNV
const { Config } = require("../config");
// JWT
const jwt = require("jsonwebtoken");

// Token helper
module.exports = {
    getToken: user => jwt.sign(user, Config.jwt.secret, { expiresIn: process.env.JWT_EXPIRE })
};

Upvotes: 0

Related Questions