How to integrate next-intl middleware with an existing middleware #1613
Answered
by
AnouarMc
AssadRajab
asked this question in
Q&A
-
I have an existing middleware that handles the auth. Now i am trying to add the next-intl to my project. However i am having a hard time combining both of them. I followed the tutorial and implemented everything as the doc says I am using Next.JS 15 App Router with Src directory Here is my existing middleware: import { NextRequest, NextResponse } from "next/server";
import { getSession } from "@/lib/auth/iron-session";
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
const session = await getSession();
const isLoggedIn = session.isLoggedIn;
// Check if the user is logged in
if (!isLoggedIn && pathname !== "/einloggen") {
return NextResponse.redirect(new URL("/einloggen", request.url));
}
if (isLoggedIn && pathname === "/einloggen") {
return NextResponse.redirect(new URL("/", request.url));
}
// Allow access to other pages
return NextResponse.next();
}
export const config = {
// Apply the middleware to all paths except for the ones we want to exclude (like _next and favicon.ico)
matcher: ["/((?!_next|favicon.ico).*)"],
}; |
Beta Was this translation helpful? Give feedback.
Answered by
AnouarMc
Dec 23, 2024
Replies: 1 comment 4 replies
-
I think you can execute the next-intl middleware first. If the response is a redirect, return it otherwise, pass it to the auth middleware, and make sure to return that response if the auth middleware passes. import createMiddleware from "next-intl/middleware";
const i18nMiddleware = createMiddleware(routing);
export default async function middleware(request: NextRequest) {
const response = i18nMiddleware(request);
if (response && !response.ok) {
// response not in the range 200-299 (usually a redirect)
// no need to execute the auth middleware
return response;
}
return await authMiddleware(request, response);
}
async function authMiddleware(request: NextRequest, response: NextResponse) {
const { pathname } = request.nextUrl;
const session = await getSession();
const isLoggedIn = session.isLoggedIn;
// Check if the user is logged in
if (!isLoggedIn && pathname !== "/einloggen") {
return NextResponse.redirect(new URL("/einloggen", request.url));
}
if (isLoggedIn && pathname === "/einloggen") {
return NextResponse.redirect(new URL("/", request.url));
}
// Allow access to other pages
return response;
} |
Beta Was this translation helpful? Give feedback.
4 replies
Answer selected by
AssadRajab
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think you can execute the next-intl middleware first. If the response is a redirect, return it otherwise, pass it to the auth middleware, and make sure to return that response if the auth middleware passes.