I have a Django backend that returns an httpOnly cookie on successful login. This cookie is required for accessing protected routes in the Next app. I have a middleware that checks if a protected route is being accessed – if it is, then an api call is made to ensure that the user can access said page. Here’s the code for that –
export default middleware = async (request) => {
//check auth status if user tries to access protected routes
if (PROTECTED_ROUTES.includes(request.nextUrl.pathname)) {
try {
let res = await fetch(
process.env.NEXT_PUBLIC_BACKEND_URL + "/authentication/check",
{ credentials: "include" }
);
//Go to login page if not signed in
if (res.status !== 200) {
return NextResponse.redirect(new URL(PAGE_ROUTES.LOGIN, request.url));
}
} catch (error) {
//In case API fails or there is an exception, send them to login page
return NextResponse.redirect(new URL(PAGE_ROUTES.LOGIN, request.url));
}
}
};
On login, I can see the cookie in the application tab under chrome dev tools. But when I try accessing a protected route, I get sent back to the login page, as the cookie is not being sent. Why is this happening? How can I make the middleware pass the cookie that is saved in the clients browser?