How to Get a Cookie’s Expiry Value on a Server by@zellwk

How to Get a Cookie’s Expiry Value on a Server

Browsers handle cookie expiry so they don’t pass the cookie’s expiry value to the server. You have to make some adjustments if you want to get the cookie’s expiry value on the server.
image
Zell Liew HackerNoon profile picture

Zell Liew

I'm a developer who creates content to make the web a better place. I write about HTML, CSS, JS, Node and other things.


Browsers handle cookie expiry so they don’t pass the cookie’s expiry value to the server. You have to make some adjustments if you want to get the cookie’s expiry value on the server.


There are two methods:

  • You can create a cookie with a JSON value
  • You can use another cookie to signify the expiry

Creating a cookie with a JSON value

You can create a cookie with a JSON value. It looks like this:


const cookieValue = JSON.stringify({
  value: 'hello world',
  expiry: Date.now() + 3600 * 1000
})

res.cookie('myCookie', cookieValue)


If you use Express, you can indicate to cookie-parser that a cookie is a JSON cookie by prepending the value with a j:. Cookie-parser will automatically decode the JSON cookie and turn it back into an object.


// Setting a JSON cookie for cookie-parser
const cookieValue = JSON.stringify({
  value: 'hello world',
  expiry: Date.now() + 3600 * 1000
})

res.cookie('myCookie', `j: ${cookieValue}`)


// Reading the JSON cookie
import cookieParser from 'cookie-parser'

app.use(cookieParser())

app.get('/', (req, res) => {
  const { myCookie } = req.cookies

  if (myCookie.expiry < Date.now()) {
    // Do something
  }
})


Of course, if you want the browser to remove the cookie automatically when it expires, you can still set the maxAge property.


res.cookie('myCookie', 'j:' + cookieValue, { maxAge: 3600 * 1000 })

Creating another cookie to store the expiry

You can create another cookie to store the expiry value. Here’s what it looks like (including the maxAge property).


res.cookie('myCookie', 'hello world', { maxAge: 3600 * 1000 })
res.cookie('myCookieExpiry', Date.now() + 3600 * 1000 { maxAge: 3600 * 1000 })


You’d be able to check the cookie expiry value in the server like this:


import cookieParser from 'cookie-parser'
app.use(cookieParser())

app.get('/', (req, res) => {
  const { myCookie, myCookieExpiry } = req.cookies

  if (myCookieExpiry < Date.now()) {
    // Do something
  }
})


That’s it!


Thanks for reading. This article was originally posted on my blog.

react to story with heart
react to story with light
react to story with boat
react to story with money
Zell Liew HackerNoon profile picture
by Zell Liew @zellwk.I'm a developer who creates content to make the web a better place. I write about HTML, CSS, JS, Node and other things.
Read my stories
L O A D I N G
. . . comments & more!