apollo-server icon indicating copy to clipboard operation
apollo-server copied to clipboard

Allow way to disable get requests for /graphql route in Apollo Server Express

Open christhegrand opened this issue 1 year ago • 4 comments

By default, Apollo Server Express handles requests for get and post methods on the /graphql route. We would like get requests to /graphql to return a 404 and for the route to only be accessible via post. There does not seem to be a way to configure this at the moment.

Right now I'm working around this by adding this to our Express server before we create the GQL middleware:

  app.use('/graphql', (req, res, next) => {
    if (req.method === 'POST') {
      next()
    } else {
      return res.sendStatus(404)
    }
  })

christhegrand avatar May 25 '23 21:05 christhegrand

That's not an unreasonable approach, for what it's worth. For another approach, you can throw a GraphQLError in your context function; something like (untested)

app.use('/graphql', expressMiddleware(server, {
  context: async ({ req }) => {
    if (req.method === 'GET') {
      throw new GraphQLError("Only POSTs are allowed on /graphql", { extensions: { http: { status: 404 } } });
    }
    // return normal context here
  }
}));

Note that (as of AS4) the GraphQL middleware only knows how to return errors in GraphQL-style JSON so if you want to do your Express server's normal HTTP 404 page you probably just want to do what you showed above.

(Doing it this way will still leave the "landing page" enabled when viewed with a browser (which sends accept: text/html); it will only block things that don't look like they're from a browser.)

glasser avatar May 25 '23 22:05 glasser

@glasser If we didn't use the context function before and added one only to handle the case raised by OP, is there a specific return to do or can we just return undefined?

Nargonath avatar Apr 04 '24 17:04 Nargonath

{} is better — if you use TypeScript you will see that your context's type has to extend {}.

glasser avatar Apr 16 '24 01:04 glasser

Alright, thanks @glasser.

Nargonath avatar Apr 16 '24 20:04 Nargonath