Next.js Discord

Discord Forum

how to make json web token not expire by session

Unanswered
Cuvier’s Dwarf Caiman posted this in #help-forum
Open in Discord
Cuvier’s Dwarf CaimanOP
I would like to have a token that does not automatically expire when I restart the browser.
Any thoughts on this?
const token = jsonwebtoken.sign({ id: user.id }, secret, { expiresIn: '7d' })

Thank you, Timo

28 Replies

Cuvier’s Dwarf CaimanOP
cookies().set('token', token, {
  httpOnly: true
})

What format should the expiration value have?
@Cuvier’s Dwarf Caiman ts cookies().set('token', token, { httpOnly: true }) What format should the expiration value have?
'use server'
 
import { cookies } from 'next/headers'
 
async function setCookie(data) {
  const oneDay = 24 * 60 * 60 * 1000
  cookies().set('name', 'value', { expires: Date.now() + oneDay })
}
Cuvier’s Dwarf CaimanOP
so I have to multiply by 1000 ??
@Cuvier’s Dwarf Caiman so I have to multiply by 1000 ??
yes, it must be in milliseconds
Cuvier’s Dwarf CaimanOP
ok
you can use the ms package from vercel to convert human readable text to milliseconds
Cuvier’s Dwarf CaimanOP
the 1000 milliseconds were my mistake
and what format should the token expiration value have?
Cuvier’s Dwarf CaimanOP
when I add expires value to cookies(), the cookie is not set.
can you show your code
Cuvier’s Dwarf CaimanOP
yes I will
This is the part where the token is set as a cookie:
const token = sign({ id: user.id }, secret)
if (!token) {
  console.error('Token has not been created.')
  return false
} else {
  cookies().set('token', token, {
    httpOnly: true
  })
  console.log('Token has been created.')
}
Cuvier’s Dwarf CaimanOP
when I add "expires" to the cookie, the token is not set anymore
show the code where you set expiry
Cuvier’s Dwarf CaimanOP
const token = sign({ id: user.id }, secret)
if (!token) {
  console.error('Token has not been created.')
  return false
} else {
  cookies().set('token', token, {
    httpOnly: true,
    expires: 1000 * 60 * 60 * 24 * 7
  })
  console.log('Token has been created.')
}
hey
so you should do new Date().getTime() + <your logic>
Cuvier’s Dwarf CaimanOP
I needed to set maxAge
NOT expires
ohh
Cuvier’s Dwarf CaimanOP
I have got to the solution by using ChatGPT. :lolsob: