Search code examples
hapi

Why does Hapi bomb when creating cookies?


Setting a simple cookie with Hapi.

return h.redirect('http://localhost:3000/handle-login').state('tester', { authToken, refreshToken })

It breaks.

Error: Invalid cookie value: [object Object]
    at exports.Definitions.internals.Definitions.internals.Definitions.format...

refreshToken and authToken are just strings.

Seems this is a common issue with Hapi https://github.com/hapijs/hapi/issues?utf8=%E2%9C%93&q=%22Invalid+cookie+value%22

But no real solutions other than disabling some error configs in the server (sounds like a bad idea to me)

How can I make Hapi happy with simple cookie handling?


Solution

  • If you are storing a cookie as a JSON, you need to set the encoding attribute when you configure the server:

    server.state('tester', {
        ttl: null,
        isSecure: true,
        isHttpOnly: true,
        encoding: 'base64json',
        clearInvalid: true,
        strictHeader: true
    });