RevereCRE / relay-nextjs

⚡️ Relay integration for Next.js apps
https://reverecre.github.io/relay-nextjs/
MIT License
251 stars 30 forks source link

Authenticated requests from the client #40

Closed p-null closed 2 years ago

p-null commented 2 years ago

Hi Ryan,

I am not sure if I could ask questions in this github issue but please me know if there is a better place to ask questions.

Could you shed some light on this?

I would like to make authenticated requests to a graphql api, which means I need to include a Authorization header with a token string value.

By following the example in the doc, I am able to pass the auth token to createServerEnvironment. This works fine for the initial landing page (e.g. Page A), since the request was made on the server side which uses the server env (which uses auth token).

However, if I naviagte to page B and back to page A (or page C which also makes graphql requests), it will defintely fail since the request is made from the client, and I didn't create a client env with auth token

But how can I create a client environment with a auth token? I am using next-auth, two ways to get session tokens are useSession and getSession. None of them will work if I call these inside getClientEnvironment since useSession needs to be wrapped with a SessionProvider, and getSession is a async function.

Another question: Do I have to to create a relay client environemnt with auth token? In other words, can I make all requests are made from the server side (which uses relay server environemnt), so that all pages are hydrated before it returns to the client?

Thanks in advance!

rrdelaney commented 2 years ago

I am not sure if I could ask questions in this github issue but please me know if there is a better place to ask questions. Could you shed some light on this?

I set up discussions in the repo for this in the future 😄

But how can I create a client environment with a auth token?

It seems like this can be done in the client-side Environment before fetching:

export function createClientNetwork() {
  return Network.create(async (params, variables) => {
    const session = await getSession();
    const response = await fetch('/api/graphql', {
      method: 'POST',
      credentials: 'include',
      headers: {
        'Content-Type': 'application/json',
        /* Authorization info from session here. */
      },
      body: JSON.stringify({
        query: params.text,
        variables,
      }),
    });

    const json = await response.text();
    return JSON.parse(json, withHydrateDatetime);
  });
}

can I make all requests are made from the server side (which uses relay server environemnt), so that all pages are hydrated before it returns to the client?

This isn't supported. It would require a bunch of work hacking into getServerSideProps and the Relay runtime. It's also always possible to proxy requests through your server before making the GraphQL request.