I am facing a rather interesting issue. I have frontend and backend services running separately on GCP Cloud Run. FE is Next.js 14 + Apollo Client + Supabase for authentication. Backend is Express + Apollo Server Express + TypeGraphQL.
Both applications are dockarized, then deployed to Cloud Run using GitHub Actions.
I have a setup where my Apollo client in the frontend includes cookies to be sent to the backend. Then I use the cookie values to authenticate certain paths in the server. I do this by setting credentials to true when creating a new HttpLink instance.
const httpLink = new HttpLink({
uri: process.env.GRAPHQL_URI,
credentials: 'include'
});
And in the backend, I have the following to configure CORS.
const corsConfig = {
credentials: true,
origin: ['http://localhost:3000', 'https://frontend-instance.a.run.app'],
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
allowedHeaders:
'Origin, X-Requested-With, Content-Type, Accept, Authorization, Cookie',
};
app.use(cors(corsConfig));
...
const appServer = new ApolloServer({
schema: buildSchemaSync({
resolvers: [
...
]
});
appServer.applyMiddleware({
cors: corsConfig,
app,
path: '/graphql',
});
This has been working as expected in localhost, however after deploying to production servers I can observe that cookies are not included in the graphql request to the backend. What could be causing this? Would this be a problem with the CORs setup, or something with Cloud Run? Given this works as expected in localhost, I'd assume the problem is not in the setup, but how Cloud Run handles passing of cookies.
Any pointer will be much appreciated.
[EDIT]
Versions:
NextJS: 14.0.1
Apollo Client: 3.8.0-rc.2
Supabase: 2.38.4
Express: 4.18.2
Apollo Server Express: 3.12.0
TypeGraphQL Prisma: 0.25.1
The solution involved using NextJs' rewrites rule. I edited next.config.js
and added the following:
const nextConfig = {
...,
async rewrites() {
return [
{
source: '/api',
destination: process.env.GRAPHQL_URI,
},
];
},
};
Then, in the code where I create an HTTP Link to backend, I simply updated the URI like so:
const httpLink = createHttpLink({
uri: BACKEND_API_PROXY_URI,
credentials: 'include',
});
where BACKEND_API_PROXY_URI
is something like http://localhost:3000/api
After deploying to Cloud Run, I noticed that Cookies are now being sent correctly!