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 their tutorial and implemented everything as the doc says:
https://next-intl.dev/docs/getting-started/app-router/with-i18n-routing
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).*)"],
};
The conflict comes up because both the auth middleware and next-intl middleware have to process requests one after the other, which can lead to some path handling issues.
import { NextRequest, NextResponse } from "next/server";
import { createMiddleware } from "next-intl/middleware";
import { getSession } from "@/lib/auth/iron-session";
// Initialize next-intl middleware
const nextIntlMiddleware = createMiddleware({
locales: ["en", "de"], // Add supported locales
defaultLocale: "en",
});
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Run next-intl middleware for locale detection
const intlResponse = nextIntlMiddleware(request);
if (intlResponse) return intlResponse;
// Run authentication logic
const session = await getSession();
const isLoggedIn = session?.isLoggedIn;
if (!isLoggedIn && pathname !== "/einloggen") {
return NextResponse.redirect(new URL("/einloggen", request.url));
}
if (isLoggedIn && pathname === "/einloggen") {
return NextResponse.redirect(new URL("/", request.url));
}
return NextResponse.next();
}
// Middleware matcher configuration
export const config = {
matcher: [
"/((?!_next|favicon.ico).*)" // Exclude _next and favicon.ico paths
],
};
1