How to manage cookies with Hapi


cookies hapi nodejs Tutorials

When you visiting the most of all sites in internet, you see the messages about cookies. Cookies it’s a small piece of data, which sends with every request to server. Cookies allow to get more information about what user do on site during the session. In Hapi, you can simply start to work with cookies without any libraries.

To set HTTP cookie we should you the .state method of server instance. The first argument - the cookie name, the second - options. Options object accepts the next popular properties:

KeyValue description
isHttpOnlyhttpOnly flag, the default value - true
ttltime to live of session, the default value - null
isSecuresecure flag, the default value - true
encodingtype of encoding, the default value - ‘none’, other values - ‘base64’, ‘base64json’, ‘form’, ‘iron’

About other properties you can read in the official Hapi documentation.

In the following example, we will set the cookie for one day and called it testCookie:

'use strict';

const Hapi = require('hapi');

const server = Hapi.server({
    port: 3000,
    host: 'localhost'
});

server.state('testCookie', {
    ttl: 1000 * 60 * 60 * 24,
    encoding: 'base64json'
});

server.route({
    method: 'GET',
    path: '/index',
    options: {
        handler: async (req, h) => {
            return h.response({
                status: 'ok'
            });
        }
    }
});

const init = async () => {
    await server.start();
    console.log(`Server running at: ${server.info.uri}`);
};

process.on('unhandledRejection', (err) => {
    console.log(err);
    process.exit(1);
});

init();

If you want to set cookie for a specific route, you need to set the options.state object (to parse and store cookies) in route handler and use the .state method of response object or response toolkit:

server.route({
    method: 'GET',
    path: '/index',
    options: {
        state: {
            parse: true,
            failAction: 'error'
        },
        handler: async (req, h) => {
            // first example
            h.state('testCookie', {
                ttl: 1000 * 60 * 60 * 24,
                encoding: 'base64json'
            });
            return h.response({
                status: 'ok'
            });
            // or you can use the following example
            return h.response({ status: 'ok' }).state('testCookie', { ttl: 1000 * 60 * 60 * 24, encoding: 'base64json' });
        }
    }
});

When you reach GET /index endpoint, you should see the following response headers in browser:

Custom route cookie

All cookies will store in req.state object and can be accessed by the name of cookie as property of req.state:

server.route({
    method: 'GET',
    path: '/index',
    options: {
        handler: async (req, h) => {
            console.log(req.state.testCookie);
            return h.response({
                status: 'ok'
            });
        }
    }
});

To remove a cookie, you can use the .unstate('cookieName'). For example. the cookie with name testCookie can be cleared like this:

server.route({
    method: 'GET',
    path: '/index',
    options: {
        handler: async (req, h) => {
            return h.response({
                status: 'ok'
            }).unstate('testCookie');
        }
    }
});

Learning Hapi.js? Buy my Hapi.js Handbook🔥

comments powered by Disqus