Next.js 14: using next-intl to change the language, redirects me to home page whenever I change the language

43 views Asked by At

I am using Next.js 14 and next-intl in my project. I am able to chagne between the languages, but the issue is that every time I change language, next-intl navigates me to home page.

lets say I'm in profile page (www.mydomain.com/ru/profile), when I switch the language it navigates me to home page (www.mydomain.com/en), but it should just change the locale (www.mydomain.com/en/profile) not the whole path. Here is my code

"use client";

import { useRouter } from "next/navigation";
import { useTransition } from "react";
import type { MenuProps } from "antd";
import { Dropdown, Space } from "antd";

import {
  GlobeAltIcon} from "@heroicons/react/24/outline";

export default function LocalSwitcher() {
  const items: MenuProps["items"] = [
    {
      label: " English",
      key: "en",
    },
    {
      label: " Русский",
      key: "ru",
    },
    {
      label: " O`zbek",
      key: "uz",
    },
  ];

  const router = useRouter();

  console.log(router);
  const [isPending, startTransition] = useTransition();

  const onClick: MenuProps['onClick'] = ({ key }) => {
    const nextLocale = key;
   
    startTransition(() => {
      router.replace(`/${nextLocale}`);
    });
  };
  
  return (
    <>
      <span>

      <Dropdown
        menu={{
          items,
          onClick,
        }}
        trigger={["click"]}
        
      > 
          <Space>     
            <GlobeAltIcon className="h-6 w-6 cursor-pointer globe-icon"/>
          </Space>
        
      </Dropdown>
      </span>
    </>
  );
}

and here in next-itnl middleware

import createMiddleware from 'next-intl/middleware';
 
export default createMiddleware({
  // A list of all locales that are supported
  locales: ['en', 'ru', 'uz'],
 
  // Used when no locale matches
  defaultLocale: 'en'
});
 
export const config = {
  // Match only internationalized pathnames
    matcher: [
    '/((?!api|_next|_vercel|.*\\..*).*)',
    '/([\\w-]+)?/users/(.+)',
    '/([\\w-]+)?(/beverage/.*)'
  ]
};

P.S. Solutions provided here didn't work for me

1

There are 1 answers

0
Hashan Hemachandra On

The issue you are facing is likely due to, how the language switch is implemented in your LocalSwitcher component.

The router.replace(/${nextLocale}); call in your onClick function effectively navigates the user to the root of the site (the homepage) for the selected locale, but it does not retain the rest of the current URL path beyond changing the locale. To fix this, you should modify this logic to dynamically replace only the locale part of the URL, keeping the rest of the path intact.

I updated your onClick function.

const onClick: MenuProps['onClick'] = ({ key }) => {
  const nextLocale = key;
  
  // Build the new path by replacing the current locale with the nextLocale
  // while keeping the rest of the path unchanged.
  const newPath = router.asPath.replace(/^\/[a-z]{2}(\/|$)/, `/${nextLocale}/`);
  
  startTransition(() => {
    // Use the newPath for navigation instead of just `/${nextLocale}`
    router.replace(newPath, newPath, { locale: nextLocale });
  });
};