What Is Cross-Origin Resource Sharing (CORS)?
See the MDN Docs:
Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin. A web application makes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, and port) than its own origin.
A web page won’t allow a HTTP request from a different domain. But in practice, some of the resources in a web application will come from various sources, for example when you deploy your database from another server, or you serve the browser fonts from a CDN.
In a typical example, your front-end application (e.g., create-react-app
) will make a request to your GraphQL back-end server. If those are on different domains (or on different ports during local development on your machine), using GraphQL won’t be possible.
This blog post from the Prisma.io team explains how to enable CORS with Express (hint: use Express.js inbuilt middleware).
But what happens if you don’t use Express.js?
If you build an API from scratch with Node.js, you don’t need Express.js if you want to run a GraphQL endpoint. Apollo 2 now ships with lots of features, so that you don’t need a complicated setup anymore.
Luckily, apollo-server
allows you to add cors as an option.
const { ApolloServer, gql } = require('apollo-server-lambda');
// Construct a schema, using GraphQL schema language
const typeDefs = gql`
type Query {
hello: String
}
`;
// Provide resolver functions for your schema fields
const resolvers = {
Query: {
hello: () => 'Hello world!',
},
};
// Instantiate the server
const server = new ApolloServer({ cors: true, typeDefs, resolvers });` // <- ADD CORS
When you instantiate a new apollo server, pass in the cors
parameter.
You can also further specify the options:
const server = new ApolloServer({
cors: {
origin: '*', // <- allow request from all domains
credentials: true}, // <- enable CORS response for requests with credentials (cookies, http authentication)
typeDefs,
resolvers });`