Currently, I have successfully set up next-auth in my next.js 13 project with app router, and it is functioning as expected. My next step is to incorporate internationalization into my app following the guidelines provided in the next.js documentation. However, I am facing challenges when trying to integrate the two functionalities seamlessly.
Middleware Setup for Next-Auth
I need all routes under /user/ to be secure and protected.
export { default } from "next-auth/middleware"
export const config = { matcher: ["/(user/.*)"] }
Middleware for Next-Auth and Internationalization (i18n)
Here is the progress I've made so far. The i18n implementation appears to be functioning correctly, but the routes under /user/ are not adequately protected.
import { match } from '@formatjs/intl-localematcher'
import Negotiator from 'negotiator'
import { NextResponse } from 'next/server'
export { default } from "next-auth/middleware"
let locales = ['en', 'de']
let defaultLocale = 'en'
function getLocale(request) {
let headers = { 'accept-language': 'en' }
let languages = new Negotiator({ headers }).languages()
return match(languages, locales, defaultLocale) // -> 'en'
}
export function middleware(request) {
// Check if there is any supported locale in the pathname
const pathname = request.nextUrl.pathname
const pathnameIsMissingLocale = locales.every(
(locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
)
// Redirect if there is no locale
if (pathnameIsMissingLocale) {
const locale = getLocale(request)
// e.g. incoming request is /products
// The new URL is now /en/products
return NextResponse.redirect(
new URL(`/${locale}/${pathname}`, request.url)
)
}
}
export const config = {
// '/(\w{2}/user/.*)' from nextauth (\w{2} because of /en/ or /de/); '/((?!_next).*)' from i18n
matcher: ['/(\w{2}/user/.*)', '/((?!_next).*)'],
}
I am seeking guidance on how to effectively combine these two functionalities?