import { NextResponse } from"next/server";let locales = ['en-US','nl-NL','nl']// Get the preferred locale, similar to the above or using a libraryfunctiongetLocale(request) { ... }exportfunctionmiddleware(request) {// Check if there is any supported locale in the pathnameconst { pathname } =request.nextUrlconstpathnameHasLocale=locales.some( (locale) =>pathname.startsWith(`/${locale}/`) || pathname ===`/${locale}` )if (pathnameHasLocale) return// Redirect if there is no localeconstlocale=getLocale(request)request.nextUrl.pathname =`/${locale}${pathname}`// e.g. incoming request is /products// The new URL is now /en-US/productsreturnNextResponse.redirect(request.nextUrl)}exportconstconfig= { matcher: [// Skip all internal paths (_next)'/((?!_next).*)',// Optional: only run on root (/) URL// '/' ],}
最後,請確保 app/ 內的所有特殊檔案都嵌套在 app/[lang] 下。這讓 Next.js 路由器能夠動態處理路由中的不同語系設定,並將 lang 參數轉發到每個佈局和頁面。例如:
app/[lang]/page.js
// You now have access to the current locale// e.g. /en-US/products -> `lang` is "en-US"exportdefaultasyncfunctionPage({ params: { lang } }) {return...}