-
|
Hi everyone, I’m using Next.js App Router with next-intl for localization. I have a LocaleSwitcher component that switches between en and km locales. Example: The problem is that the query string (loginToken=abc123) is lost when switching locales. I’m currently using this code: My LocaleSwitcher component "use client";
import { usePathname, useRouter } from "@/i18n/navigation";
import { LOCALE } from "@/i18n/routing";
import ReactCountryFlag from "react-country-flag";
export const LocaleSwitcher = () => {
const pathname = usePathname();
const router = useRouter();
const updateLocale = (locale: LOCALE) => {
router.push(pathname, { locale });
};
return (
<div>
<button
className="px-2 py-1 text-xs font-semibold text-primary hover:bg-muted rounded transition-colors"
onClick={() => updateLocale("km")}
>
<ReactCountryFlag countryCode="kh" svg className="text-xl" />
</button>
<button
className="px-2 py-1 text-xs font-semibold text-muted-foreground hover:bg-muted rounded transition-colors"
onClick={() => updateLocale("en")}
>
<ReactCountryFlag countryCode="us" svg className="text-xl" />
</button>
</div>
);
};How can I switch locales using next-intl in Next.js while preserving the search/query parameters in the URL? Any guidance or examples would be appreciated. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
Hey! The issue is that const searchParams = useSearchParams();
const updateLocale = (locale: LOCALE) => {
router.push(
{ pathname, query: Object.fromEntries(searchParams), locale },
undefined,
{ locale }
);
};This preserves the query when switching. If you're on Next.js 15+, you can also do: router.push({ pathname, ...searchParams, locale });That should keep your |
Beta Was this translation helpful? Give feedback.
@pratikrath126 Thank you, I appreciate your help. It works for me.