withAuth middleware pass context locale #6946
Replies: 2 comments 1 reply
-
were you able to solve this issue ? |
Beta Was this translation helpful? Give feedback.
-
Hello, popping in to see if I can help out! I am going to spell this out in stages.
export default withAuth({
callbacks: { ... },
pages: {
signIn: "/signIn/{locale}"
}
})
// middleware.ts
import { withAuth } from "next-auth/middleware";
import { NextFetchEvent } from "next/server";
// More on how NextAuth.js middleware works: https://next-auth.js.org/configuration/nextjs#middleware
export default async function middleware(req: Request, event: NextFetchEvent) {
const localeStr = req.headers.get("Accept-Language");
const locale = localeStr?.split(";")[0].split(",")[0]; // Feel free to replace this with any logic for parsing the desired locale
const withAuthMiddleware = withAuth({
callbacks: {}, // Whatever callbacks you have
pages: {
signIn: `/${locale}/sign-in`,
},
});
// @ts-ignore: types do not narrow as expected but should be fine. Hover over the function to see its types
return await withAuthMiddleware(req, event);
}
export const config = { matcher: ["/admin", "/me"] }; Hope this helps you! I have a minimal working example here. UPDATE: An alternate way to call // middleware.ts
export default async function middleware(req: Request) {
// ...
// @ts-ignore: again type issue here but should be fine
const response = withAuth(req, { ... });
return response
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Question 💬
Hi, i want to protect the entire site within
withAuth
middlewaresrc/middleware.ts
works fine but i experienced that it doesn't pass a locale as i switched my preferred browser locale to en-US
expected:
user navigates to a protected route as guest => redirects to /{context.locale}/sign-in like /en-US/sign-in
how do i achieve this?
project deps. versions:
How to reproduce ☕️
https://codesandbox.io/s/eloquent-khayyam-fxmncr?file=/middleware.ts
Contributing 🙌🏽
Yes, I am willing to help answer this question in a PR
Beta Was this translation helpful? Give feedback.
All reactions