I was unable to create JWT token

From front-end webapp i was creating a user, eventually the user is created but JWT token was unable to generate. It shows the erro of {msg: ‘option expires is invalid’}

code for creating JWT token

const jwt = require('jsonwebtoken')

const createJWT = ({ payload }) => {
  const token = jwt.sign(payload, process.env.JWT_SECRET, {
    expiresIn: '30d',
  })
  return token
}

const isTokenValid = ({ token }) => jwt.verify(token, process.env.JWT_SECRET)

const attachCookiesToResponse = ({ res, user }) => {
  const token = createJWT({ payload: user })
  const oneDay = 1000 * 60 * 60 * 24

  res.cookie('token', token, {
    httpOnly: true,
    expires: new Date(Date.now + oneDay),
    signed: true,
    domain: 'http://localhost:3000/',
    sameSite: 'none',
  })
}

module.exports = {
  createJWT,
  isTokenValid,
  attachCookiesToResponse,
}

authController register function

const register = async (req, res) => {
  let { email, name, password, role } = req.body || req.query

  //checking if email already exist
  const emailAlreadyExists = await User.findOne({ email })
  if (emailAlreadyExists) {
    throw new CustomError.BadRequestError('Email already exists')
  }

  //first account will be registered as admin
  const isFirstAccount = (await User.countDocuments({})) === 0
  if (isFirstAccount === 0) {
    role = 'admin'
  }

  const user = await User.create({ name, email, password, role })
  console.log('here 1')
  const tokenUser = createTokenUser(user)
  console.log('here 2')
  attachCookiesToResponse({ res, user: tokenUser })
  console.log('here 3')
  res.status(StatusCodes.CREATED).json({ user: tokenUser })
}
const oneDay = 1000 * 60 * 60 * 24
new Date(Date.now + oneDay)
// Invalid Date

Date.now() is a static method, it has to be invoked.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.