I'm currently utilizing Next.js (v13.5.4) and next-intl (v3.0.0-beta.19) for internationalization. My goal is to modify the URL structure for locales from a format like en-GB to en/UK.
I've set up Next with the app router and initialized next-intl following the server component guide.
Here's my attempt to set up URL rewrites in next.config.js:
/** @type {import('next').NextConfig} */
const nextConfig = {
async rewrites() {
return {
beforeFiles: [
{
source: "/en/uk/:path*",
destination: "/en-GB/:path*",
}
]
}
},
}
module.exports = withNextIntl(nextConfig);
With this config, navigating to http://localhost:3000/en-GB functions as expected. However, accessing http://localhost:3000/en/uk redirects to http://localhost:3000/en-GB/en/uk (where en-GB is the last locale I accessed).
For further context, this is my middleware:
import createMiddleware from 'next-intl/middleware';
export default createMiddleware({
locales: ['de-DE', 'en-GB'],
defaultLocale: ''
});
export const config = {
matcher: ['/((?!api|_next|_vercel|.*\\..*).*)']
};
Attempts at Resolving:
- Removed the
beforeFilessegment from the rewrite configuration. - Incorporated
locale: falsein my config. - Adjusted the matcher in the middleware to
matcher: ['/((?!api|en/uk|_next|_vercel|.*\\..*).*)'], which resulted in the error: Error: Unable to find next-intl locale, have you configured the middleware.
Any insights, alternative solutions, or suggestions would be immensely appreciated.
My previous answer only works for client components. To get it to work with server components, you need to to do the url rewrite in the middleware. This is because next.js prioritises redirects and rewrites in the middleware over the rewrites in the config. Here is my middleware in the end: