sandrinodimattia / nextjs-auth0-example

A sample application showing how your users can sign in to your Next.js application using Auth0
https://nextjs-auth0-demo.now.sh/
MIT License
44 stars 9 forks source link

Calling API in getInitialProps #9

Open MarketBranch opened 4 years ago

MarketBranch commented 4 years ago

First off, awesome example! It really helped me out.

One thing I'm curious about is making API calls from getInitialProps. When I do this, my API routes don't seem to have access to the session at all. However, if I run the API within the React component, it works just fine.

I'm assuming this is because the cookies have no way to get set on the browser given that getInitialProps is being run on the server. Are there any workarounds you know of that might help get the proper cookie and manually set it with the request?

Thank you!

MarketBranch commented 4 years ago

For what it's worth, I ended up being able to forward the session cookie. I'm not sure if it's an OK method, but this is how I did it:

    const response = await fetch(YOUR_URL_HERE, {
      credentials: 'include',
      headers: {
        Cookie: ctx.req.headers.cookie,
      },
    });