Node.js: cookie policy in ExpressJS

Node.js: cookie policy in ExpressJS

In this tutorial we will see how to allow users to deny their consent to the use of third party cookies.

In this tutorial we will see how to allow users to deny their consent to the use of third party cookies.

To begin, let's create a simple JavaScript file that will simulate the creation of a third party cookie.

'use strict';
(function() {

    const date = new Date();
    const daysToExpire = 365;
    const cookieName = 'testcookie';
    const cookieValue = 'test';

    date.setTime(date.getTime() + (daysToExpire * 24 * 60 * 60 * 1000));

    document.cookie = `${cookieName}=${cookieValue}; expires=${date.toGMTString()}`;
})();

The logic is this: if the user consents to the use of cookies, we insert the script in the head element of the pages, vice versa we do not insert it. To store the user's choice we will use our technical cookie or we could use web storage but in this case we will not be able to manage its duration and the user will have more difficulty managing it in the browser.

We therefore write:

<head>
<% if(cookieAccepted === 1) { %>
    <script src="/public/js/cookie.js"></script>
    <% } %>
</head>

The insertion of the banner of choice will follow the same logic:

<% if(cookieAccepted === null) { %>

<div id="cookie-policy-banner">
    <p>
        Lorem ipsum dolor sit amet ete ideo autem aquis ut meus est mos.
    </p>
    <div>
        <button type="button" id="reject-cookie-policy" data-choice="0">No thanks</button>
        <button type="button" id="accept-cookie-policy" data-choice="1">Accept</button>
    </div>
</div>
<% } %>

The banner will be inserted only if the user has not yet made a choice. Attributes button data will be used to perform the operation via AJAX (we will use jQuery below). We then implement the creation of the cookie that will store the user's choice using the middleware cookie-parser:


'use strict';

const express = require('express');
const router = express.Router();


router.get('/', (req, res, next) => {
    const cookieAccepted = req.cookies.cookieAccepted ? parseInt(req.cookies.cookieAccepted, 10) : null;
    res.render('index', { cookieAccepted });
});

router.post('/setcookie', (req, res, next) => {
    const { choice } = req.body;
    const value = parseInt(choice, 10);
    const allowedValues = [0, 1];

    if(!allowedValues.includes(value)) {
        return res.sendStatus(403);
    }

    
    res.cookie('cookieAccepted', value, { maxAge: 60 * 60 * 24 * 365 * 1000 } ).json({ value });
});

module.exports = router;

You will notice that both cookies have an expiration of 1 year. This value is purely indicative and can be adapted to the various needs of your policy.

We just have to implement the request in AJAX:

"use strict";

$(function() {
   var $cookieBanner = $( "#cookie-policy-banner" );
   if( $cookieBanner.length ) {
       $cookieBanner.find( "button" ).click(function() {
            var choice = $( this ).data( "choice" );
            $.post( "/setcookie", { choice: choice }, function( res ) {
                if( $.isNumeric( res.value ) ) {
                    window.location = location.href;
                }
            });
       });
   }
});

Here we simply reload the current page so that the changes made take effect immediately.