3

What are the benefits of using Express with GraphQL? All the advantages of GraphQL can also be used with a simple Node.js application without Express. As GraphQL has only one endpoint and no middleware concept like in case of Express, why would we want to use Express and not just Node.js?

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183

1 Answers1

2
  1. Express uses the Node.js http module under the hood but through middleware provides a way for you to implement various features for your endpoint. For example, to process POST requests (which you would need to do for GraphQL), you would need to parse the request body into a usable format -- if you don't utilize Express and a middleware like body-parser, you'd have to do this by hand. The same goes for other common functionality you're likely to need, like CORS, session management, etc. -- why reinvent the wheel when there's a middleware for it?

  2. GraphQL itself might not have a concept of middleware (although there is a library that effectively does just that), Express's middleware still applies to your GraphQL endpoint as a whole. That means you can set up middleware that is ran before the GraphQL endpoint. Outside of features already described above, this also allots you the opportunity to implement authorization logic for your endpoint. For example, you could prevent access to the entire endpoint to users that fail to provide an appropriate custom header.

  3. In reality, your app may need more than just your GraphQL endpoint. Authentication is commonly handled outside of GraphQL by exposing one or more additional endpoints -- this is particularly true if you implement an OAuth flow for your app. Likewise you may interface with third-party services that utilize webhooks, which would require you to expose additional endpoints on your server specifically for that purpose. The same often goes for health checks, like those used by load balancers.

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183