How to Fix CORS Error with GraphQL: Simple Steps
CORS error with GraphQL, configure your server to include the correct Access-Control-Allow-Origin headers. This usually means enabling CORS middleware or settings in your GraphQL server to allow requests from your frontend domain.Why This Happens
CORS (Cross-Origin Resource Sharing) errors happen because browsers block requests from one domain to another unless the server explicitly allows it. When your frontend tries to call a GraphQL API on a different domain or port, the browser checks if the server permits this. If the server does not send the right headers, the browser stops the request and shows a CORS error.
const { ApolloServer, gql } = require('apollo-server'); const typeDefs = gql`type Query { hello: String }`; const resolvers = { Query: { hello: () => 'Hello world!' } }; const server = new ApolloServer({ typeDefs, resolvers }); server.listen().then(({ url }) => { console.log(`Server ready at ${url}`); });
The Fix
You fix this by enabling CORS on your GraphQL server. For Apollo Server, you can pass cors options when starting the server to allow your frontend origin. This tells the browser it’s safe to make requests from that origin.
const { ApolloServer, gql } = require('apollo-server'); const typeDefs = gql`type Query { hello: String }`; const resolvers = { Query: { hello: () => 'Hello world!' } }; const server = new ApolloServer({ typeDefs, resolvers }); server.listen({ cors: { origin: 'http://localhost:3000', credentials: true } }).then(({ url }) => { console.log(`Server ready at ${url}`); });
Prevention
Always configure CORS on your server before connecting your frontend. Use environment variables to set allowed origins dynamically for different environments (development, staging, production). Avoid using * wildcard in production to keep your API secure. Use middleware or built-in server options to handle CORS consistently.
Related Errors
Other common errors include:
- Preflight request failures: Happens when the browser sends an OPTIONS request and the server does not respond correctly.
- Credential issues: If you use cookies or authentication, you must set
credentials: 'include'on the client andcredentials: trueon the server CORS config. - Mixed content errors: Occur if your frontend uses HTTPS but your GraphQL server uses HTTP.