Next.js: Data-fetch using isomorphic-fetch (per the example) doesn't include cookie on server.

Created on 3 Jul 2017  路  6Comments  路  Source: vercel/next.js

Here's the data fetch example: https://github.com/zeit/next.js/tree/v3-beta/examples/data-fetch

When there is a cookie, that cookie is part of the request as seen from the server _only_ when the fetch is a browser-side (non-SSR) fetch.

When fetching during SSR, the cookie is not part of the request that the server sees.

I expect the cookies to be available on the server (to Express routes) isomorphically -- during SSR and otherwise.

Most helpful comment

@tashburn you can do something like this:

const options = {
    method: 'GET',
    credentials: 'include', // for client side requests
  };
  if (req) {
    options.headers = { cookie: req.headers.cookie }; // for server side request
  }
  const prefix = req ? `${req.protocol}://${req.get('Host')}` : window.location.origin;
  return fetch(`${prefix}/admin/api/endPoint, options).then(res => ...)

All 6 comments

What the client you using for fetching?
Did you try Axios? Because I have the same problem with isomorphic-fetch

You'll have to manually pass the cookies off (reading from req) and pass them to axios / isomorphic-fetch

@kv9991 what do you mean by "client"?

@timneutkens thanks. i'll see if i can find out how to pass them to isomorphic fetch -- hopefully as a callback, because they may change, and isomorphic-fetch always needs the latest.

@tashburn you can do something like this:

const options = {
    method: 'GET',
    credentials: 'include', // for client side requests
  };
  if (req) {
    options.headers = { cookie: req.headers.cookie }; // for server side request
  }
  const prefix = req ? `${req.protocol}://${req.get('Host')}` : window.location.origin;
  return fetch(`${prefix}/admin/api/endPoint, options).then(res => ...)

@sscaff1 Thanks

Thank you all for this. Found out the solution by myself, but heh it was somewhere!

Would love to see this as part of the docs explaining how isomorphic fetch works.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ghost picture ghost  路  3Comments

jesselee34 picture jesselee34  路  3Comments

havefive picture havefive  路  3Comments

irrigator picture irrigator  路  3Comments

sospedra picture sospedra  路  3Comments