#How to handle params with match in middlewre
1 messages · Page 1 of 1 (latest)
Hi @fathom egret. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
In Next.js middleware, you can handle route parameters using the matcher property in the config object. The matcher property can be used to define either a single path or multiple paths using an array syntax.
Here's an example of matching a single path:
export const config = {
matcher: '/about/:path*',
};
And here's an example of matching multiple paths:
export const config = {
matcher: ['/about/:path*', '/dashboard/:path*'],
};
You can also use regular expressions in your matcher config. For example, to match all request paths except for the ones starting with api, _next/static, or favicon.ico, you can use a negative lookahead:
export const config = {
matcher: ['/((?!api|_next/static|favicon.ico).*)'],
};
To match a path like /blog/123 but not /blog/abc, you can use a custom regex:
export const config = {
matcher: ['/blog/:slug(\\d{1,})'],
};
Please note that there are some issues reported on GitHub regarding the behavior of the matcher configuration for named parameters. You might want to check these issues for more context and possible workarounds.
Sources:
- Vercel Docs: Match paths based on custom matcher config (https://vercel.com/docs/functions/edge-middleware/middleware-api#match-paths-based-on-custom-matcher-config)
- GitHub Issue: Incorrect Behavior in Matcher Configuration Documentation (https://github.com/vercel/next.js/issues/55558)
- GitHub Issue: Middleware does not match when use :path (https://github.com/vercel/next.js/issues/53840)
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@fathom egret kapa.ai is still learning and improving, please let us know how it did by reacting below
@obtuse pilot It seems that its sending me to login page with this /en/product/rog_strix_gefore_rtx4090_oc_edition_24gb
My current code is
import { NextResponse, type NextRequest } from "next/server";
import createIntlMiddleware from "next-intl/middleware";
import { auth } from "@/app/api/auth/auth";
import { redirect } from "next/navigation";
const defaultLocale = "ja";
const localePrefix = "always";
const locales = ["en", "ja"];
const publicPages = [
"/",
"/discover",
"/account/signin",
"/account/signup",
"/account/forgot-password",
"/account/forgot-password/*",
"/product/:slug",
];
const intlMiddleware = createIntlMiddleware({
locales,
defaultLocale,
localePrefix,
});
const authMiddleware = auth((req) => {
// private routes here
const session = req.auth;
if (!session) {
return NextResponse.redirect(new URL("/account/signin", req.url));
}
if (session) {
return intlMiddleware(req);
}
});
export default function middleware(req: NextRequest) {
const publicPathnameRegex = RegExp(
^(/(${locales.join("|")}))?(${publicPages .flatMap((p) => (p === "/" ? ["", "/"] : p)) .join("|")})/?$,
"i"
);
const isPublicPage = publicPathnameRegex.test(req.nextUrl.pathname);
if (isPublicPage) {
return intlMiddleware(req);
} else {
return (authMiddleware as any)(req);
}
}
export const config = {
matcher: ["/((?!api|_next|.\..).*)"],
};
Let me check the knowledge base for you. One moment! :books:
Your current code is set up to redirect to the /account/signin page if there is no session found. The authMiddleware checks for a session and if none is found, it redirects to the sign-in page.
The publicPages array is used to define routes that are accessible without authentication. The isPublicPage variable checks if the current route is in the publicPages array. If it is, the intlMiddleware is used, otherwise, the authMiddleware is used.
The issue you're facing might be due to the publicPages array not correctly matching the route /en/product/rog_strix_gefore_rtx4090_oc_edition_24gb.
The publicPages array includes the route /product/:slug, which should match any product route. However, the regular expression used to test the publicPages might not be correctly accounting for the locale prefix and the product slug.
You might want to check the regular expression used in publicPathnameRegex and ensure it correctly matches the routes with the locale prefix and the product slug.
Please note that there are some issues reported on GitHub regarding the behavior of the matcher configuration for named parameters. You might want to check these issues for more context and possible workarounds.
Sources:
- Next.js Docs: Handling Unauthorized Access (https://nextjs.org/docs/app/building-your-application/authentication#handling-unauthorized-access)
- GitHub Issue: Incorrect Behavior in Matcher Configuration Documentation (https://github.com/vercel/next.js/issues/55558)
- GitHub Issue: Middleware does not match when use :path (https://github.com/vercel/next.js/issues/53840)
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@fathom egret kapa.ai is still learning and improving, please let us know how it did by reacting below
howd u fix the publicPathnameRegex @obtuse pilot
Let me check the knowledge base for you. One moment! :books:
The issue seems to be with the regular expression used in publicPathnameRegex. It might not be correctly matching the routes with the locale prefix and the product slug.
Here's a modified version of your publicPathnameRegex:
const publicPathnameRegex = new RegExp(
`^/(${locales.join("|")})?(${publicPages.join("|")})/?$`,
"i"
);
This regular expression will match any route that starts with an optional locale prefix followed by any of the paths in the publicPages array.
Please note that this assumes that the publicPages array contains paths starting with a / and that the locale is directly appended to the start of the path. If your routes are structured differently, you might need to adjust the regular expression accordingly.
Also, remember to escape any special characters in your publicPages paths that have special meaning in regular expressions. For example, if you have a path like /product/:slug, you should escape the : character like this: /product/\\:slug.
Sources:
- MDN Web Docs: Regular Expressions (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)
- GitHub Issue: Incorrect Behavior in Matcher Configuration Documentation (https://github.com/vercel/next.js/issues/55558)
- GitHub Issue: Middleware does not match when use :path (https://github.com/vercel/next.js/issues/53840)