Reputation: 23
I'm trying to create a cookie under my route handler after my response object with the state method, but the cookie isn't appearing in any way. Even pasting many of the examples on the hapijs website is not working either.
My index.js:
const Hapi = require('hapi')
const server = new Hapi.Server
({
host: 'localhost',
port: 8000
})
server.route({
method: 'GET',
path: '/',
config: {
handler: (request, h) => {
return h.response(`Cookie!`).state('cookie-name', 'cookie-value');
}
}
})
async function start() {
await server.start();
console.log(`Server started at ${ server.info.uri }`);
}
start();
I was expecting 'cookie-name' to appear under 'name' in the developer console, as well as 'cookie-value' to appear as the 'value'. Nothing shows up and I am receiving this error message upon refreshing my localhost:
Debug: internal, implementation, error
Error: Invalid cookie value: [object Object]
at exports.Definitions.internals.Definitions.internals.Definitions.format (/Users/cayden/Documents/egghead/introduction-to-node-servers-with-hapijs/lessons/12-hapi.js-managing-state-with-cookies/node_modules/hapi/node_modules/statehood/lib/index.js:361:24)
at process._tickCallback (internal/process/next_tick.js:68:7)
Establishing a cookie the way I am doing it is near an example I saw on their website. What am I missing that is causing my code to not produce the cookie?
Upvotes: 2
Views: 1037
Reputation: 573
To set a cookie legitimately, you first need to configure the cookie by calling server.state(name, [options])
method where name is the cookie name. And options are the objects to configure that cookie.
Add this lines of code to your existing code:
server.state("cookie-name", {
ttl: null,
isSecure: false,
isHttpOnly: true,
clearInvalid: false,
strictHeader: true
});
server.route({
method: 'GET',
path: '/',
config: {
handler: (request, h) => {
return h.response(`Cookie!`).state('cookie-name', 'cookie-value');
}
}
})
Hopefully now you can see the cookie and it's value in the development browser.
Upvotes: 2