How does middleware composition work ?
Unanswered
Purple Martin posted this in #help-forum
Purple MartinOP
I'm fairly new to next.js, and I'd like to use a middleware to handle 2 usecases: on one hand, I'd like to handle auth-based redirections with my middleware. So I came up with this:
on the other hand, I'd like to add i18n capabilities to my app. After digging up a bit, I found this library called
But since both export a middleware, I have no idea how to combine them. Is it even possible ?
import { ACCESS_TOKEN_COOKIE_NAME } from "constants/cookies";
import { HOME_PATH, LOGIN_PATH, TERMS_PATH } from "constants/paths";
import { NextRequest, NextResponse } from "next/server";
const PUBLIC_PATHS = [LOGIN_PATH, TERMS_PATH];
/**
* Redirect to login page if no access token is found
*/
export function middleware(request: NextRequest) {
const token = request.cookies.get(ACCESS_TOKEN_COOKIE_NAME);
if (token?.value) {
// redirect to homepage if token is found on login page
if (request.nextUrl.pathname === LOGIN_PATH) {
return NextResponse.redirect(new URL(HOME_PATH, request.nextUrl.origin));
}
return NextResponse.next();
}
// Skip middleware for the public pages
if (PUBLIC_PATHS.includes(request.nextUrl.pathname)) {
return NextResponse.next();
}
return NextResponse.redirect(new URL(LOGIN_PATH, request.nextUrl.origin));
}
export const config = {
// Match only internationalized pathnames
matcher: ["/", "/(fr|en)/:path*"],
};on the other hand, I'd like to add i18n capabilities to my app. After digging up a bit, I found this library called
next-intl/middleware. its middleware setup is pretty straightforward:import createMiddleware from "next-intl/middleware";
export default createMiddleware({
// A list of all locales that are supported
locales: ["fr", "en"],
// Used when no locale matches
defaultLocale: "fr",
});But since both export a middleware, I have no idea how to combine them. Is it even possible ?