apollo-server-express CORS issue apollo-server-express CORS issue express express

apollo-server-express CORS issue


From my understanding of the Apollo Server middleware API, CORS options, body-parser options and the graphql endpoint are treated as special entities that must be passed directly to the applyMiddleware param object.

So you want to try the following configuration:

const app = express();// CORS configurationconst corsOptions = {    origin: 'http://localhost:3000',    credentials: true}// The following is not needed, CORS middleware will be applied// using the Apollo Server's middleware API (see further below)// app.use(cors(corsOptions))// Setup JWT authentication middlewareapp.use(async (req, res, next) => {    const token = req.headers['authorization'];    if(token !== "null"){        try {            const currentUser = await jwt.verify(token, process.env.SECRET)            req.currentUser = currentUser        } catch(e) {            console.error(e);        }    }    next();});const server = new ApolloServer({     typeDefs,     resolvers,     context: ({ req }) => ({ Property, User, currentUser: req.currentUser })});// There is no need to explicitly define the 'path' option in// the configuration object as '/graphql' is the default endpoint// If you planned on using a different endpoint location,// this is where you would define it.server.applyMiddleware({ app, cors: corsOptions });const PORT = process.env.PORT || 4000;app.listen(PORT, () => {    console.log(`Server listening on ${PORT}`);})


With Apollo Server 2.x you supply the cors field in the constructor of ApolloServer.

So in your case, it should look like the following:

const corsOptions = {    origin: 'http://localhost:3000',    credentials: true}// Setup JWT authentication middlewareapp.use(async (req, res, next) => {    const token = req.headers['authorization'];    if(token !== "null"){        try {            const currentUser = await jwt.verify(token, process.env.SECRET)            req.currentUser = currentUser        } catch(e) {            console.error(e);        }    }    next();});const server = new ApolloServer({     typeDefs,     cors: cors(corsOptions),    resolvers,     context: ({ req }) => ({ Property, User, currentUser: req.currentUser })});server.applyMiddleware({ app });const PORT = process.env.PORT || 4000;app.listen(PORT, () => {    console.log(`Server listening on ${PORT}`);})

Here you find all params accepted by the apollo server:https://www.apollographql.com/docs/apollo-server/api/apollo-server.html#Parameters-2

Here you find the relevant discussion:https://github.com/apollographql/apollo-server/issues/1142


The CORS settings come from ExpressJS, not from ApolloServer. If you want to add a custom or wildcard origin you have to handle it with a callback/handler function.

const server = new ApolloServer({    ....,    cors: {        credentials: true,        origin: (origin, callback) => {            const whitelist = [                "http://site1.com",                "https://site2.com"            ];            if (whitelist.indexOf(origin) !== -1) {                callback(null, true)            } else {                callback(new Error("Not allowed by CORS"))            }        }    }});