I'm working on a project with NestJS as the backend and Next.js 14 (app router) for the frontend. My backend implements cookie-based session authentication, where the session ID is stored in a cookie. I need help setting up role-based access control for protected routes in my Next.js app, utilizing session validation from my NestJS backend.
Here's the flow I'm trying to achieve:
- A user makes a request to the Next.js server.
- The Next.js server extracts the session cookie from the request and forwards it to the NestJS backend for session validation.
- The NestJS backend validates the session and, if valid, responds with the user's session data, including roles such as adminId, studentId, and teacherId.
- Based on the backend's response: If 401, the Next.js server redirects the user to /login. If 200, the Next.js server checks the user's role against the requested route (/admin, /student, /teacher) and serves the route only if the corresponding role ID is present in the session data.
Additionally, I'm using next-intl for internationalization, with the following middleware setup for locale handling:
import createMiddleware from "next-intl/middleware";
export default createMiddleware({
locales: ["en", "uk"],
defaultLocale: "en",
});
export const config = {
matcher: ["/", "/(uk|en)/:path*"],
};
And my i18n.ts for locale validation:
import { notFound } from "next/navigation";
import { getRequestConfig } from "next-intl/server";
const locales = ["en", "uk"];
export default getRequestConfig(async ({ locale }) => {
if (!locales.includes(locale as any)) notFound();
return {
messages: (await import(`../messages/${locale}.json`)).default,
};
});