i am building a graphql api using apollo-server-express. I am using jwt and cookies for authentication so in my cors options credentials is set to true, the thing is, when credentials is set to true, Access-Control-Allow-Origin is always *, even if i set the origin in my cors options, it still is *.
here is my middleware:
app.use(
cors({
origin: "https://studio.apollographql.com",
credentials: true,
})
);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ limit: "2mb" }));
app.use(cookieParser());
To reproduce you need a graphql and express server.
// Initialize dotenv
dotenv.config();
// Get env variables
const PORT = process.env.PORT || 5000;
// Create express server
const app = express();
// Express server middleware
app.use(
cors({
credentials: true,
origin: "https://studio.apollographql.com",
})
);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ limit: "2mb" }));
app.use(cookieParser());
// Create new apollo server
const gqlServer = new ApolloServer({
typeDefs: [typedefs],
resolvers: { ...resolvers },
context: ({ req, res }: ContextType) => {
// const { isValid, userData } = verifyToken(req.cookies?.xToken);
return {
// isLoggedIn: isValid,
// userData: userData,
req,
res,
};
},
});
(async () => {
await gqlServer.start();
gqlServer.applyMiddleware({ app });
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
})();
Then you need to go on localhost:5000/graphql, tap query your server, and go to apollo. In apollo studio, on the top left, where your url is displayed (should be localhost:5000), there should be a little cog icon (settings icon), you can tap on that, then go to include cookies and set it on. Thats it, if you go in dev tools at the network tab, you'll see cors errors from your server localhost:5000 ant the value of Access-Control-Allow-Origin is *. btw you need to set up some resolvers and type definitions.
I solved the problem, i needed to apply the cors middleware to my graphql server as well.
gqlServer.applyMiddleware({
app,
cors: {
origin: "https://studio.apollographql.com",
credentials: true,
},
});