ElPirru
ElPirru

Reputation: 183

How do I request a cookie when server rendering on hapi?

I know that when using express, a cookie can be requested with the following code:

req.get('cookie')

However, I am now facing an issue when requesting a cookie using a hapi server.

The code for requesting a cookie should be the following:

request.state['COOKIE_NAME']

However, my request.state is always emtpy when server rendering my pages. When the cookie is request on the client, there is no issue, the request.state is populated with the cookies.

On my server file, I am using the onPreResponse hook as follows:

server.ext( 'onPreResponse', ( request, reply ) => {
...
  fetch('http://localhost:3000/api/getcookie', {
    credentials: 'same-origin',
    headers: {'Cookie': request.state['COOKIE_NAME']} // Still empty
  })
...
});

The hapi Route is:

{
  method: 'GET',
  path: '/getcookie',
  config: {
    auth: false
},
  handler: ( request, reply ) => {
    console.log('GET COOKIE ROUTE: ', request.state); // <-- this is empty when server rendering

    reply({
      statusCode: 200,
      message: 'get cookie',
      data: {
        text: request.state
      }
    })
    .code(200);
}

The cookies are being set without a problem and I can retrieve them on the client as well. The issue is when I try to get the cookie on the server.

If you need any more info, please let me know.

Upvotes: 1

Views: 1545

Answers (1)

Patrick Meier
Patrick Meier

Reputation: 444

Your question was a bit hard to understand for me. You write...

The cookies are being set without a problem and I can retrieve them on the client as well. The issue is when I try to get the cookie on the server.

... but I do not see any code that actually sets a cookie value. So I cannot understand how you would successfully get in on the client. And to request the same route in the servers onPreResponse extension point with some fetch method is also not clear to me.

I wrote a small and complete example which actually sets a cookie and also makes use of the onPreResponse extension point.

'use strict';

const Hapi = require('hapi');
const Path = require('path');

// Create a server with a host and port
const server = new Hapi.Server();
server.connection({
  port: 3000
});

//Define the cookie
server.state('data', {
    encoding: 'base64json'
});

// Add the route
server.route({
  method: 'GET',
  path: '/getcookie',
  handler: function(request, reply) {

    const counterState = request.state.data.counter;
    const counter = counterState ? counterState + 1 : 1;

    return reply({
      statusCode: 200,
      message: 'get cookie',
      currentState: request.state
    })
    .state('data', {counter: counter}); //<-- You missed to actually SET your cookie!
  }
});

server.ext( 'onPreResponse', ( request, reply ) => {

  //Here you have full access to the original request
  console.log("PreResponse counter value: " + request.state.data.counter);

  return reply.continue();

});

// Start the server
server.start((err) => {

  if (err) {
    throw err;
  }

  console.log('Server running at:', server.info.uri);
});

I hope this helps you understand how to work with cookies in hapi and somehow presents a solution to your specific problem.

Upvotes: 1

Related Questions