JSON Cookies with Express

express provides a little known facility for storing JavaScript objects in cookies, and it’s surprisingly simple to use. Just pass a JavaScript object instead of a string for the cookie value to cause JSON.stringify() and JSON.parse() to be run in the background when storing and parsing a cookie.

'use strict';

const express = require('express');
const cookieParser = require('cookie-parser');

const app = express();

app.use(cookieParser('cheese'));

app.get('/', (req, res) => {
    res.cookie('j:cheeses', [
        'cheddar',
        'gouda',
        'munster',
        'mozzarella'
    ], {
        signed: true,
        expires: new Date(Date.now() + 1000000),
        httpOnly: true
    });
    res.redirect('show');
});

app.get('/show', (req, res) => {
    const cheeses = req.signedCookies['j:cheeses'] || [];
    res.clearCookie('j:cheeses');
    res.json(cheeses);
});

app.listen(3000);