jsonwebtoken.sign() fails with expiresIn option set
Asked Answered
C

4

38

I need to get a token by signing a user ID with JWT:

var token = jwt.sign(accounts[request.headers.login].id, privateKey, {expiresIn: 60});

Where id and privateKey are strings.

The error is Error: Uncaught error: "expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60. If I remove options object at all, it works, but without options I need to set.

The issue seems to be simple but I don't know how to fix it, what am I doing wrong?

Cotenant answered 1/2, 2016 at 13:6 Comment(0)
D
52

https://www.npmjs.com/package/jsonwebtoken#jwtsignpayload-secretorprivatekey-options-callback

payload could be an object literal, buffer or string. Please note that exp is only set if the payload is an object literal.

Deuteron answered 1/2, 2016 at 19:11 Comment(1)
Oh, seems like I can't set expire date if payload is a string. Thanks!Cotenant
C
25

Set the payload as an object if you want to be able to set the expiresIn option

var token = jwt.sign(
    {id: accounts[request.headers.login].id}, // object and not string
    privateKey,
    {expiresIn: '60d'} // added days, default for ex 60 would be ms, you can also provide '1h' etc
)
Ca answered 23/12, 2020 at 18:26 Comment(5)
"be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default" It would be 60ms not 60 secondsAmorphism
@Amorphism edit my answer please! with example providing units ;)Ca
I get the 'Suggested edit queue is full' error from stackoverflowAmorphism
the PAYLOAD!!!! needs to be and object (gush what a crappy error message),Umbles
also: 60d should be '60d'Umbles
A
0

I am also facing the same question.There is my answer. the initial code

const setToken = function (data) {
  return new Promise((resolve, reject) => {
    const token = jwt.sign( data , signkey, { expiresIn: "1d" });
    resolve(token);
  });
};

The first parameter(data) should be object or add braces({}); the edited code

const setToken = function (data) {
  return new Promise((resolve, reject) => {
    const token = jwt.sign({ data }, signkey, { expiresIn: "1d" });
    resolve(token);
  });
};
Arguseyed answered 11/3, 2022 at 6:42 Comment(1)
Please do not post images of code. Use the formatting tools to put the code here,Scalise
R
-1

In my case, it was a wrong file name that was referencing the env variables.

technicianAuthSchema.methods.getSignedToken = async function() {
return jwt.sign( { id: this._id }, process.env.JWT_SECRET, { expiresIn: process.env.EXPIRE, } );};

instead of this

technicianAuthSchema.methods.getSignedToken = async function() {
return jwt.sign( { id: this._id }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRE, } );};

Wrong file name: expiresIn: process.env.EXPIRE
Correct file name: expiresIn: process.env.JWT_EXPIRE

Rookie answered 30/4, 2021 at 12:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.