dulnan / nuxt-graphql-middleware

GraphQL in the backend, fetch in the frontend. With TypeScript support.
https://nuxt-graphql-middleware.dulnan.net
MIT License
57 stars 11 forks source link

Forward server response headers to the client #6

Closed arthurfiorette closed 1 year ago

arthurfiorette commented 2 years ago

Currently, the http headers returned by the graphql server are stuck in the nuxt middleware. So, when the server returns a cookie that the client should always use in the next requests, the client never receives this header and is not even able to send it the next time.

There should also be an option in nuxt config to enable custom GraphQLClient settings.

https://github.com/dulnan/nuxt-graphql-middleware/blob/0a52813333f23178c0240286316f7e45ccea7bfd/src/serverMiddleware.ts#L55

dulnan commented 2 years ago

You can provide a onQueryResponse method that handles this:

https://github.com/dulnan/nuxt-graphql-middleware#serveronqueryresponse-response-graphqlresponse-req-request-res-response--any

The first argument response is the raw response object from graphql-request: https://github.com/prisma-labs/graphql-request#receiving-a-raw-response It contains a headers object.

The second and third arguments are req and res from express, so you could pass headers back to the client, for example:

onQueryResponse(graphqlResponse: any, _req: Request, res: Response) {
  if (graphqlResponse.headers['set-cookie']) {
    res.setHeader('set-cookie', graphqlResponse.headers['set-cookie'])
  }
  return res.json(graphqlResponse.data)
}
arthurfiorette commented 2 years ago

Interesting...

I was trying with onMutationResponse. Is there a reason why in the mutation function you use request and the query function you use the rawRequest?

https://github.com/dulnan/nuxt-graphql-middleware/blob/0a52813333f23178c0240286316f7e45ccea7bfd/src/serverMiddleware.ts#L91

https://github.com/dulnan/nuxt-graphql-middleware/blob/0a52813333f23178c0240286316f7e45ccea7bfd/src/serverMiddleware.ts#L119

Because i can only access headers, status and so on in the onQueryResponse.

dulnan commented 1 year ago

I actually changed that a few months ago so both query and mutations use rawRequest.

For the upcoming V3 release of this module this isn't an issue anymore as both queries and mutations are handled by the same code/method.