My frontend is running on localhost:3000 while backend which is on nestjs is running on localhost:3006. When user signs up or logs in then I have set cookie in the following way
const setCookie = context.res.cookie('cookie-data', {
accessToken: token.accessToken,
refreshToken: token.refreshToken,
user: user,
});
Now, I need this cookie to authenticate each route. I mean if I go to particular page which is a private page then I need to check if those token exist and is valid or not from cookie by calling api for that particular user through the token I get from cookie. If it's valid then allow user to navigate to that page otherwise redirect user to login.
This is how I am trying to get the cookie that's set from backend while user logs in
_app.tsx
function MyApp({ router, pageProps, Component, cookies }) {
return (
<>
<Header />
{
Component.auth ?
<Auth cookies={cookies}>
<Component key={router.route} {...pageProps} />
</Auth> :
<Component key={router.route} {...pageProps} />
}
</>
)
}
MyApp.getInitialProps = async (appContext) => {
const appProps = await App.getInitialProps(appContext);
let cookies = {};
if (process.browser === false) {
cookies = appContext.ctx.req?.cookies;
} else {
cookies = Cookies.get();
}
return { ...appProps, cookies }
}
export default MyApp
The problem is appContext.ctx.req?.cookies; returns an empty object. How can I receive cookie that is set from backend(nestjs) ?
It should be
cookies = appContext.ctx.req.headers?.cookie;