I have an express application with express-session for my server hosted on api.example.com and a NextJS application hosted on example.com. Locally everything works fine the server will set a cookie and because they are both on localhost the client can read this cookie, but when the site is in production I need to host the server elsewhere so when the server sends the cookie the client can't read it because its on a different domain.
Reading the cookie on the client:
ExampleApp.getInitialProps = async (app: any) => {
const appProps = await App.getInitialProps(app);
const sid = app.ctx.req?.cookies?.["connect.sid"] ?? "";
const user = await getUser({ sid });
return { ...appProps, user };
};
Is there any way to resolve this issue or is this just not the correct approach? If more information is needed I can provide it. Thank you in advance.
You cannot set the cookie from one subdomain to another. The work around I went with was sending the cookie in the response from the server then using NextJS api routes set it on the client.