The ability to reply to discussions is limited to PRO members. Want to join in the discussion? Click here to subscribe now.

hapi.js - Managing State with Cookies

hapi.js - Managing State with Cookies

3:05
hapi has built-in support for parsing cookies from a request headers, and writing cookies to a response, making state management easy and straight-forward. It even has built in support for cookie encryption and auto detects when a cookie contains JSON, parsing or stringifying automatically.
Watch this lesson now
Avatar
egghead.io

hapi has built-in support for parsing cookies from a request headers, and writing cookies to a response, making state management easy and straight-forward. It even has built in support for cookie encryption and auto detects when a cookie contains JSON, parsing or stringifying automatically.

Avatar
Irvin

Enjoyed the course. Would really like a course building an API application using hapi.js. For example, the proverbial ToDo or Bookstore app, with a Mongo or RethinkDB backend, models, controllers, project structure and tooling. Maybe touch on testing at the end. This would be great!

In reply to egghead.io
Avatar
Alexander Hofstede

+1 What Irvin said ^^ ;)

In reply to Irvin
Avatar
Vincent

+1 to Irvan, would like to be able to produce something useful, not just piece of code that i will have to lose hours trying to figure out how to make it work together

Avatar
Charles

Hi! JSON cookie values aren´t working for me! apparently hapi doesn't serialize/deserialize objects anymore?? (hapi version: ^14.2.0)

//------ index.js ------
server.route(
{
        method: 'GET',
        path: '/cookies',
        handler: (request, reply) => {
          let johnCookie= request.state.charlie
          let resp = reply(`<h1>Cookie <em>${johnCookie}</em> found!</h1>`)

          resp.state('john', {fname: 'john', lname: 'doe', email: 'johndoe@gmail.com'})
        }
})
//------ server nodemon------
Debug: internal, implementation, error
    Error: Invalid cookie value: [object Object]
    at C:\__dirname\node_modules\statehood\lib\index.js:373:38
    at C:\__dirname\node_modules\statehood\lib\index.js:447:20
    at C:\__dirname\node_modules\hoek\lib\index.js:854:22
    at nextTickCallbackWith0Args (node.js:453:9)
    at process._tickDomainCallback (node.js:423:13)
160822/091352.066, [response] http://localhost:8000: get /cookies {} 500 (54ms)

//------ browser response------
{"statusCode":500,"error":"Internal Server Error","message":"An internal server error occurred"}

´´´
In reply to egghead.io
Avatar
yuki

Adding "isSecure:false" option to cookie configuration did the trick! It's true by default and it means it's not available in insecure environment like http.

server.state('id', {
  ttl: 60 * 60 * 1000,
  isHttpOnly: true,
  isSecure: false,
  encoding: 'iron',
  password: 'password'
});
In reply to Charles
HEY, QUICK QUESTION!
Joel's Head
Why are we asking?