Search code examples
javascriptnode.jscookiesreactjsisomorphic-javascript

How to pass Request cookies through node-fetch in isomorphic app?


I'm trying to build isomorphic project using React, Express and isomorphic fetch (based on whatwg-fetch on client and node-fetch on server), from this common boilerplate. I'm using cookies for my access token, and credentials: 'same-origin' on front-end side to send it to GraphQL -- works pretty well.

The problem is that I can't use the same solution for server side -- node-fetch just don't support using of XMLHttpRequest cookies from the box. My fetch request is under few abstract layers from router, so I can't just use cookie value from req.

Here is my server.js code (full version):

server.get('*', async (req, res, next) => {
  try {
    // some presettings here..

    await Router.dispatch({ path: req.path, query: req.query, context }, (state, component) => {
      data.body = ReactDOM.renderToString(component);
    });

    res.send(template(data));
  } catch (err) {
    next(err);
  }
});

and Route's index.js (full version):

export const action = async (state) => {
  const response = await fetch('/graphql?query={me{id,email}}', {
    credentials: 'same-origin',
  });
  const { data } = await response.json();
  // ...
  return <Login title={title} me={data.me} />;
};

How can I pass my token from server.js to my fetch module? Or, maybe there are some better decisions?


Solution

  • First off, I hope you have found an answer by now!

    Secondly, cookies are really just headers. If you need to send a cookie to authorize server-side requests, you can always just create the string that you need for the cookie value and send it as a header.

    For an example, take a look at how this server-side node-fetch wrapper appends saved cookies to the outbound request: https://github.com/valeriangalliat/fetch-cookie/blob/master/index.js#L17