Express-graphql: [Http headers] I need to send a cookie.

Created on 14 Apr 2016  路  9Comments  路  Source: graphql/express-graphql

How can I access to the response headers since this lib provides only the req parameter but not res ?

Most helpful comment

You're right, they're not defined in the example I gave above, so it wouldn't work. What you actually have to write is something like this (which wraps the graphqlHTTP middleware in a function that acts as middleware:

app.use('/graphql', (req, res) => {
  return graphqlHTTP({
    schema,
    graphiql: true, // or whatever you want
    context: { req, res },
  })(req, res);
);

All 9 comments

You could wrap graphqlHTTP and pass res into the context, then you can access it from resolvers.

Yep of course there are workarounds, for instance I had fork this project and added the res to the options. It took only 3 lines of code... So why the heck only the req is set ???

I'm not sure why you thought you had to fork the project to do this... the following should work:

app.use('/graphql', graphqlHTTP({
  schema,
  graphiql: true, // or whatever you want
  context: { req, res },
});

and in your resolve function:

resolve: (root, args, context) => {
  let cookieValue;
 /* your code here */
  context.res.set('cookie', cookieValue);
}

Where did your req and res come from ?

You're right, they're not defined in the example I gave above, so it wouldn't work. What you actually have to write is something like this (which wraps the graphqlHTTP middleware in a function that acts as middleware:

app.use('/graphql', (req, res) => {
  return graphqlHTTP({
    schema,
    graphiql: true, // or whatever you want
    context: { req, res },
  })(req, res);
);

response is now added to the middleware config function, and of course you can do what @helfer suggested as well, but definitely be careful in setting headers from a graphql function, it's typically a sign of something gone awry.

it's typically a sign of something gone awry

@leebyron how else would you set a cookie if user signed up or logged in?

I would strongly suggest against using GraphQL as a replacement for OAuth or other forms of authentication.

@leebyron at the end of a valid non-graphql OAuth flow (e.g. firebase) the client ends up with a token that you need to send to the server (and expecting the server to validate the token (from firebase) and set a secure cookie. This is one of the few ways to have graphql subscriptions since websockets cannot set custom headers (so only cookies provide security).

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dmytro-kerest picture dmytro-kerest  路  3Comments

arunoda picture arunoda  路  4Comments

jeud picture jeud  路  4Comments

m-diiorio picture m-diiorio  路  4Comments

justinmchase picture justinmchase  路  4Comments