apollographql / apollo-server

🌍  Spec-compliant and production ready JavaScript GraphQL server that lets you develop in a schema-first way. Built for Express, Connect, Hapi, Koa, and more.
https://www.apollographql.com/docs/apollo-server/
MIT License
13.75k stars 2.03k forks source link

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

Open christhegrand opened 1 year ago

christhegrand commented 1 year ago

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)
    }
  })
glasser commented 1 year ago

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.)

Nargonath commented 5 months ago

@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?

glasser commented 4 months ago

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

Nargonath commented 4 months ago

Alright, thanks @glasser.