Hi, I'm creating a server using express-graphql, I need to create an authentication API with GraphQL, I have some mutations and queries that requires an authentication middleware and someothers that doesn't require an authentication middleware.
I try to call graphqlHTTP two times, injecting authentication middleware, but the second graphqlHTTP is ignored.
app.use('/api/v1/user', graphqlHTTP((req, res) => ({ schema: UserSchemaWithoutAuth, context: { req, res } })));
// Below code is ignored, but if I comment above code, it works.
app.use('/api/v1/user', (req, res, next) => {
console.info('This is a test middleware!');
next();
}, graphqlHTTP((req, res) => ({ schema: UserSchemaWithAuth, context: { req, res } })));
How can I resolve it?
Regards.
When graphqlHTTP function in first app.use(...) gets executed, the response is over. There is nothing left to do. That's why second route gets ignored.
You can make auth available in resolve() function by attaching it to the request object before graphqlHTTP middleware. See https://github.com/graphql/express-graphql#combining-with-other-express-middleware
check this package from npm:
https://www.npmjs.com/package/graphql-add-middleware
GraphQL Middleware is probably the most popular package for adding middleware-like functionality to your resolvers. However, you can also just get away with creating a higher-order function that you can wrap your resolvers in.
Most helpful comment
check this package from npm:
https://www.npmjs.com/package/graphql-add-middleware