Michael Michael - 1 month ago 12
Node.js Question

Create a cookie via Hapi.js

According to the hapi framework docs here, and tutorial here, in order to create a cookie you must first configure the server by calling server.state(...) immediately after creating the server.

I have the following code

const server = new hapi.Server();

try {
server.state('session', {
ttl: 1000 * 60 * 60 * 24,
encoding: 'base64json'
})
} catch (err) {
server.app.cookieError = err
}


Which results in the following error:

Error: Cannot add state without a connection


I have followed the docs and other tutorials exactly, this error should not be happening, i have searched google for the error text and it brings up zero results!

Answer Source

Try this way, you need to configure your server with connection and then start it.

'use strict';

const Hapi = require('hapi');
const server = new Hapi.Server();

server.connection({ port: 3000, host: 'localhost'});

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

server.start((err) => {
    if (err) {
        throw err;
    }

    console.log(`Server running at: ${server.info.uri}`);
})