I am currently trying to deploy my NestJS server using Graphql on Google Cloud Run. I also have a React app that I use as a client, that I hosted on Netlify.
I am getting the following CORS (Cross Origin Resource Sharing) error in the console when I try to run this, however:
Access to fetch at 'https://google-cloud.run.app/graphql' from origin 'https://myapp.netlify.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
My NestJS app configuration looks as follows:
// {cors: true}
const app = await NestFactory.create(AppModule);
app.enableCors({
origin: true,
credentials: true,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
allowedHeaders: "Content-Type,Accept,Authorization,Access-Control-Allow-Origin"
});
In another stackoverflow post, I saw that the GraphQL CORS configuration overrides the NestJS CORS configuration, so I added the CORS logic also into the GraphQL app.module.ts
as follows:
@Module({
controllers: [],
imports: [
...,
GraphQLModule.forRootAsync({
useFactory: (configService) => {
const playground = configService.get("GRAPHQL_PLAYGROUND");
const introspection = configService.get("GRAPHQL_INTROSPECTION");
return {
autoSchemaFile: true,
playground,
introspection: playground || introspection,
cors: {
credentials: true,
origin: true,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
allowedHeaders: "Content-Type,Accept,Authorization,Access-Control-Allow-Origin"
},
context: ({req}) => {
return {req};
},
installSubscriptionHandlers: true
};
},
inject: [ConfigService],
imports: [ConfigModule]
}),
...
When I run the client from localhost
, and when there is a direct connection to the Google Cloud Run Container, everyting works fine at this point, and I don't receive any CORS errors. I am using the Apollo GraphQL client to make the API requests.
When I use the Netlify Client, however, I get the CORS issue above.
Any idea on how to address this? Is this a Netlify issue? Is this a Google Cloud Run Issue? Or am I missing any headers with the CORS?