Kristian Golemi
Kristian Golemi

Reputation: 81

Passing request parameter into middleware which uses 'createHandler' function of 'graphql-http'

I have created an express server which uses GraphQL for handling requests over HTTP. Among others, the express server has the two middlewares below.

app.use(authenticate);

app.use('/graphql', createHandler({ schema }));

The authenticate middleware invokes a function which has req, res and next as parameters and in certain conditions assigns a value to req.user.

How can I pass the req object into the next middleware which is responsible for handling GraphQL requests?

I've searched for it in graphql-http's documentation but no luck. Any help will be appreciated. Link to the package's documentation: https://github.com/graphql/graphql-http#with-express

Upvotes: 3

Views: 689

Answers (1)

Kristian Golemi
Kristian Golemi

Reputation: 81

Apparently a way to achieve what I wanted is the below code

app.use(
  '/graphql',
  createHandler({
    schema,
    context: (req) => ({
      user: req.raw.user,
      random: req.raw.random
    }),
  })
);

If you need to pass the whole req object, then you can adjust the context field of the createHandler function like shown below. However, in the resolver you'll have to access fields of the req object like this: user = req.req.raw.user

    context: (req) => ({
      req
    }),

Upvotes: 4

Related Questions