I’m trying to accept an HTTP Only cookie with graphql. For normal express endpoints it works fine, but for /graphql it seems apollo is using it’s own independant cors settings. I have apollo client/server fully working, until I try to pass cookies from frontend. here’s a snippet of my frontend code:
const link = from([
errorLink,
new HttpLink({ uri: import.meta.env.VITE_GRAPHQL_URL,
credentials: 'include' }),
]);
const client = new ApolloClient({
cache: new InMemoryCache(),
link: link,
});
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<ApolloProvider client={client}>
<RouterProvider router={router} />
</ApolloProvider>
</React.StrictMode>
);
Here’s a snippet of my backend apollo initialization code:
const httpServer = http.createServer(app);
const bootstrapServer = async () => {
const server = new ApolloServer({
typeDefs,
resolvers,
plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
});
await server.start();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
app.use(cors());
// app.use((req, res, next) => {
// console.log("CORS middleware executed");
// res.setHeader("Access-Control-Allow-Origin", "*");//process.env.FRONTEND_URL + "");
// res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
// res.setHeader("Access-Control-Allow-Headers", "Content-Type");
// res.setHeader("Access-Control-Allow-Credentials", "true"); // Allow credentials
// next();
// });
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(disallowTrace);
app.use(cookieParser());
app.use(decodeToken);
console.log(process.env.FRONTEND_URL + "");
app.use(
"/graphql",
cors<cors.CorsRequest>({
origin: process.env.FRONTEND_URL + "",
credentials: true,
}),
expressMiddleware(server, {
context: async ({ req, res }) => ({
user: res.locals.user,
}),
})
);
I believe the correct way to enable cors with apollo server is with
cors<cors.CorsRequest>({
origin: "*",
credentials: true,
}),
as described here Configuring CORS - Apollo GraphQL Docs but it doesn’t work, whether I try “*” or “http://frontendurl/”.
Still though, I get a cors error:
Would really appreciate any help been stuck for hours on this. If you need any more context to help me please let me know and I will send it.
Also the response headers in the network tab are empty. Which I think confirms that no cors settings are being applied since they should appear there I think.
Thanks