Tuesday, 25 April 2017

Hapijs - persist cookie between requests

Using the Hapijs Node framework, I want to ensure a certain cookie exists for each request. If it doesn't exist, I want to create it. This cookie should persist between requests, but when I check the browser, it is never registered as a cookie.

server.ext('onPreHandler', function (request, reply) {
    console.log(`state: ${JSON.stringify(request.state)}`) // state == null
    request.state['my_cookie'] = request.state.my_cookie || 'my data'
    return reply.continue();
});


server.route({
    method: 'GET',
    path: '/',
    handler: function(request, reply) {
        // includes `my_cookie`
        reply(`Cookies: ${JSON.stringify(request.state)}`);
    }
})

// cookie does not exist in the browser

How can I ensure that the cookie I add persists between requests?



via dyer

No comments:

Post a Comment