dotansimha / graphql-yoga

🧘 Rewrite of a fully-featured GraphQL Server with focus on easy setup, performance & great developer experience. The core of Yoga implements WHATWG Fetch API and can run/deploy on any JS environment.
https://the-guild.dev/graphql/yoga-server
MIT License
8.2k stars 566 forks source link

How do I add headers to a server response? #619

Closed knixer closed 2 years ago

knixer commented 4 years ago

Not every response should have these headers. Just when dealing with tokens I want to add some headers.

ardatan commented 2 years ago

It depends on where you want to manipulate the headers; Let's say you want to access the response object in the resolvers in Node env;

(root, args, context, info) => {
  context.res // You can find `ServerResponse` object here
}

If you want to do it in the middleware level;

const http = require('http');
const yoga = require('@graphql-yoga/node');

const yogaApp = yoga.createServer(..);

const server = http.createServer((req, res) => {
  // You can manipulate `res` here
   yogaApp.requestListener(req, res);
})
Redskinsjo commented 5 months ago

I have many 405 Method Not Allowed errors when building my NextJs14 app. I have set cors: { methods: ["POST", "OPTIONS", "GET"], }, but it doesn't work. If the context is the right way to set to allowed methods, what is the best way to set allowed method for every requests ?

Redskinsjo commented 5 months ago

also I don't find any res field on YogaInitialContext

ardatan commented 5 months ago

You can create a plugin that changes the headers; https://the-guild.dev/graphql/yoga-server/docs/features/envelop-plugins#onresponse But your issue looks different. Could you create a new issue with a reproduction on CodeSandbox or StackBlitz? Thanks!

Redskinsjo commented 5 months ago

my application stack is quite large, how do you suggest me to make a simple reproduction without identifying the origin of the issue ?