[Docs]: Middleware matcher with Next-Auth #1076
Replies: 3 comments 4 replies
-
If you want to protect your Route Handlers with NextAuth, I guess you could change the matcher for them to pass also through the middleware, but add a condition within the middleware code to exclude them from running through the middleware from I'll move this to a discussion since it's a usage question. |
Beta Was this translation helpful? Give feedback.
-
I'm in exactly the same situation. What would be the ideal approach about this case? |
Beta Was this translation helpful? Give feedback.
-
the middleware that works perfectly for me is as below. although i'm no longer use next-auth. lucia-auth is much more flexible, and i can customize it as i like. import { NextRequest } from "next/server";
import { withAuth } from "next-auth/middleware";
import createIntlMiddleware from "next-intl/middleware";
import { locales } from "@/messages";
const privatePages = ["/admin(/.*)?"];
const intlMiddleware = createIntlMiddleware({
locales,
localePrefix: "as-needed",
defaultLocale: "us",
});
const authMiddleware = withAuth(
function onSuccess(req) {
return intlMiddleware(req);
},
{
callbacks: {
authorized: ({ token }) => token != null,
},
pages: {
signIn: "/login",
},
},
);
export default function middleware(req: NextRequest) {
const isPrivatePage = privatePages.some((page) => {
const pageRegex = new RegExp(
`^(/(${locales.join("|")}))?(${privatePages
.map((page) => page.replace(/\(\.\*\)\?$/, "(.*)"))
.join("|")})/?$`,
"i",
);
return pageRegex.test(req.nextUrl.pathname);
});
if (!isPrivatePage || req.nextUrl.pathname === "/") {
return intlMiddleware(req);
}
return (authMiddleware as any)(req);
}
export const config = {
matcher: ["/((?!api|_next|.*\\..*).*)"],
}; |
Beta Was this translation helpful? Give feedback.
-
Link to page
https://github.com/amannn/next-intl/tree/main/examples/example-app-router-next-auth
Describe the problem
I am using Next-Auth and Next-Intl together. I have progressed smoothly with the codes in the example section. My auth mechanizm works correctly. But in my project, I have some cases where I need to intercept with middleware before the requests I make hit the api routes. But i think with the current matcher configuration this becomes impossible.
Because if I remove the 'api' from the matcher configuration the requests always go with the locale prefix but my api folder has to be outside [locale]. I would like to ask for your support on this issue,
Thanks.
middleware.js
My app structure:
Beta Was this translation helpful? Give feedback.
All reactions