ApolloServer enables you to provide your own CORS configuration directly in the constructor.
Since there is many ways to setup and construct your Apollo server, you should look up the correct way for your stack.
You can read more about Configuring CORS in Apollo on their website.
This is how I do it for version 3 of apollo-server:
const server = new ApolloServer({
typeDefs,
resolvers,
...
cors: {
origin: true,
credentials: true, // true if you need cookies/authentication
methods: ['GET', 'POST', 'OPTIONS'],
},
})
Apollo version 4
Apollo removed support for CORS in their ApolloServer class and solely relies on Express now if you need to use middleware, CORS included.
It would look something like this
import { ApolloServer } from '@apollo/server'
import { expressMiddleware } from '@apollo/server/express4'
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer'
import express from 'express'
import http from 'http'
import cors from 'cors'
import bodyParser from 'body-parser'
const app = express()
const httpServer = http.createServer(app)
const server = new ApolloServer({
typeDefs,
resolvers,
plugins: [
ApolloServerPluginDrainHttpServer({ httpServer }),
],
})
await server.start()
app.use(
cors({
methods: ['GET', 'POST', 'OPTIONS'],
credentials: true,
maxAge: 600,
origin: [
'http://example.com',
'https://studio.apollographql.com'
],
}),
bodyParser.json(),
expressMiddleware(server, {
context: async ({ req, res }) => {
return {}
}
})
await new Promise<void>((resolve) => httpServer.listen({ port: 4000 }, resolve))
console.log(`🚀 GraphQL server is ready`)
Note: Please always post the code directly into StackOverflow, as screenshots are hard for people to work with.