i18n geo usage with next-i18next & Next's built in internationalized routing
I'm trying to follow the example within the i18n folder but am running into some issues since my requirements are a bit different.
How our use case differs from the example:
- We still want to use next-i18next and store our translations in JSON files.
- We want to use different paths for different locales like the behavior is when using Next's built-in Internationalized Routing, i.e. when user is visiting from Iceland, we want to have all of his visiting pathnames prefixed with /is.
Here's the code for the middleware I'm currently working with:
import { NextRequest, NextResponse } from "next/server";
const PUBLIC_FILE = /\.(.*)$/;
const SUPPORTED_LOCALES = ["en", "is", "pt"];
const DEFAULT_LOCALE = "en";
export function middleware(req: NextRequest) {
const currentPathName = req.nextUrl.pathname;
// 1. Only rewrite files that don't have a file extension (favicon, etc)
// 2. We don't want to detect locale if the user is already visiting with a locale prefix.
if (!PUBLIC_FILE.test(currentPathName)) {
let country = req.geo?.country?.toLowerCase();
if (!country && process.env.NODE_ENV === "development") {
country = "is";
}
const isVisitingWithLocalePath =
!!SUPPORTED_LOCALES.find((l) => currentPathName.includes(l)) ||
currentPathName === `/${country}`;
const locale =
req.headers.get("accept-language")?.split(",")?.[0] || DEFAULT_LOCALE;
const newLocale = country || locale;
if (!isVisitingWithLocalePath) {
req.nextUrl.locale = newLocale;
req.nextUrl.pathname = `/${newLocale}`;
} else {
req.nextUrl.locale =
currentPathName === `/${country}`
? DEFAULT_LOCALE
: currentPathName.split("/")[1];
}
return NextResponse.rewrite(req.nextUrl).cookie("NEXT_LOCALE", newLocale);
}
}
When visiting our page we receive the following error:
Error: The provided `as` value (/) is incompatible with the `href` value (/[company]).
If I add console.log(req.nextUrl) just before returning, this is the output (running locally):
NextURL {
href: '/is/is',
origin: '',
protocol: '',
username: '',
password: '',
host: '',
hostname: '',
port: '',
pathname: '/is',
search: '',
searchParams: URLSearchParams {},
hash: ''
}
Also let me know if you'd want this issue to be posted on Stackoverflow or the main Nextjs repo.
I'm quite late, did you ever managed to fix the issue? i18n should be working better these days with Next.js. I'm closing the issue for now but lmk if you still have the issue.
I ended up with Next.js's build-in internationalized routing. Then in v13 that's been left up to the user to implement but it looks like i18n has better support indeed 👍