Express-graphql: Adds a middleware in some resolvers?

Created on 31 Oct 2017  路  3Comments  路  Source: graphql/express-graphql

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.

question

Most helpful comment

All 3 comments

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

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mkermani144 picture mkermani144  路  5Comments

arunoda picture arunoda  路  4Comments

justinmchase picture justinmchase  路  4Comments

jamesmoriarty picture jamesmoriarty  路  4Comments

kaareal picture kaareal  路  3Comments