How can i pass express Request and Response objects into graphql-yoga context using the createYoga function?

899 views Asked by At

I want to pass the express req and res object to my context because i want to use express-sessions to do session-based-auth because the default requests from the context does not know about sessions. Here is what I have tried

app.use("/graphql", (req, res) => {
    return createYoga({
      context: ({ params }) => {
        return {
          req,
          params,
          res,
          prisma,
          redis: redisClient,
        };
      },
      graphiql: true,
      landingPage: false,
      cors: false,
      schema,
    });
});

But if i try this it seems like the request is not going through.

1

There are 1 answers

0
Yogesh_D On

According to the docs, while running in node.js and express runtime, the context will automatically have the request and response.

Server Context

When creating the server instance, GraphQL Yoga accepts an additional object from your base server framework or library that will be merged with the default context. Node.js (standalone, express and Next.js etc.)

If you are using GraphQL Yoga as a standalone server with createServer from the http(s) module or exposing it as a middleware as we show in the express or Next.js integration recipes.

req - Node.js IncomingMessage object
res - Node.js ServerResponse object

The req and res objects are added to the initial context object.

const serverContext = { ...defaultContext, req, res }

Thus, when using @graphql-yoga/node, it is possible to access context.req and context.res within the GraphQL resolvers or the user context factory function.

However, we recommend avoiding using context.req and context.res wherever possible and instead favor context.request, as it is more future-proof and platform independent (as Node.js HTTP servers adopt the Fetch Response API).

I did try this out and the context does have the req and res objects. req and res present while running in node.js and express.