This is my middleware.js file for the front end in Next.js. I want to create protected routes so that if a user doesn't have an access token, they are redirected to /. However, the cookies from the frontend are getting removed when navigating to a protected route, even if the token is present. Interestingly, this issue does not occur when I run my backend locally.
import { NextResponse } from 'next/server';
const protectedRoutes = [
'/home',
'/home/activeusers',
'/home/apimaster/add-sub-company',
'/home/apimaster/api-companies',
'/home/apimaster/api-companies/details',
'/home/apimaster/api-companies/disabled',
'/home/apimaster/api-companies/employees',
'/home/apimaster/disabled-sub-companies',
'/home/apimaster/sub-companies',
'/home/apimaster/transactionreport',
'/home/apimaster/withdrawalrequest',
'/home/articlesection',
'/home/attendance',
'/home/company/addcompany',
'/home/company/company-list',
'/home/company/details',
'/home/company/disabled',
'/home/company/employees',
'/home/dailypay',
'/home/dashboard',
'/home/employee/add',
'/home/employee/details',
'/home/employee/disabled',
'/home/employee/list',
'/home/logs',
'/home/managebanks',
'/home/messages',
'/home/paymentstatus',
'/home/roles-and-permission/roles',
'/home/roles-and-permission/users/add',
'/home/roles-and-permission/users/list',
'/home/transactionreports',
'/home/userandrole',
'/home/whitelabel',
'/home/withdrawalreport/details',
'/home/withdrawalreport/list',
'/home/withdrawalrequest',
'/home/withdrawalrequest/edit'
];
export default function middleware(request) {
const token = request.cookies.get('access_token')?.value;
const { pathname } = request.nextUrl;
if (token && pathname === '/') {
return NextResponse.redirect(new URL('/home', request.url));
}
if (!token && protectedRoutes.includes(pathname)) {
return NextResponse.redirect(new URL('/', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: protectedRoutes
};
This is how I am setting the cookie in backend:
res.cookie('access_token', keycloakRes.access_token, {
httpOnly: true,
secure: true,
sameSite: process.env.NODE_ENV === 'dev' ? 'lax' : 'none',
maxAge: accessTokenExpirey,
path: '/'
});