next-intl redirects to home page when i change the language

I am using next-intl in my Next.js project. Everything works fine except when the user changes the language, the webpage changes the language and redirects to the homepage. How can I make it so that when the user changes the language, it doesn’t redirect to the homepage?

For example, let’s say I’m on the page domain.com/ru/profile/data. When the user changes to English, the page should show domain.com/en/profile/data, but it redirects me to domain.com/en instead.

Here is my code:

middleware.ts

import createMiddleware from 'next-intl/middleware';
 
export default createMiddleware({
  locales: ['en', 'ru', 'uz'],
 
  defaultLocale: 'ru',
});
 
export const config = {

  matcher: [
    '/((?!api|_next|_vercel|.*\\..*).*)',
    '/([\\w-]+)?/users/(.+)'
  ]
};

i18n.ts

import {notFound} from 'next/navigation';
import {getRequestConfig} from 'next-intl/server';
 
// Can be imported from a shared config
const locales = ['en', 'ru', 'uz'];
 
export default getRequestConfig(async ({locale}) => {
  // Validate that the incoming `locale` parameter is valid
  if (!locales.includes(locale as any)) notFound();
 
  return {
    messages: (await import(`../messages/${locale}.json`)).default
  };
});

Header.tsx

  <Link
      locale="en"
      href="/"
      onClick={() => setSelectedLanguage('en')} 
      className={classNames(
      active ? 'bg-gray-100 text-gray-900' : 'text-gray-700',
      'block px-4 py-2 text-sm'
      )}
     >
    <span className="fi fi-gb h-4"></span> English
   </Link>

P.S. the solutions here didnt work for me. Thank you in advance

You are literally asking it to go to href="/" What do you expect?

  <Link
      locale="en"
      href="/"
      onClick={() => setSelectedLanguage('en')} 
     >
    English
   </Link>

to redirect back to the same page. You could use usePathname

"use client";

import {usePathname} from "@/navigation";

function LanguageSwitcher() {
  const pathname = usePathname();

  return (
  <Link
    locale="en"
    href={pathname}
   >
    English
  </Link>
  )
}

Leave a Comment