amannn / next-intl

🌐 Internationalization (i18n) for Next.js
https://next-intl-docs.vercel.app
MIT License
2.58k stars 236 forks source link

Localized search/query params #1270

Closed ferares closed 2 months ago

ferares commented 3 months ago

Is your feature request related to a problem? Please describe.

I'm posting this as a feature request since I could not find any references on how to do this on the docs.

I'd like for my app to be able to localize search params keys on the URL when switching locales:

/en/search?days=mo,tu
/es/buscar?dias=lu,ma

(I know I'm also translating the values on this example but I'm not sure that's something reasonable to expect next-intl to do. I guess I'd do that manually if I really want to localize search param values)

Describe the solution you'd like

It'd be ideal for the current router.replace function to do this automatically when being called with a query:

router.replace(
      // @ts-expect-error -- TypeScript will validate that only known `params`
      // are used in combination with a given `pathname`. Since the two will
      // always match for the current route, we can skip runtime checks.
      { pathname, params, query },
      { locale: localeOption },
)

Maybe a queryParams object could be defined somewhat like this (in a similar manner to how pathnames get defined for localized paths) :

import { QueryParams } from "next-intl/routing"
export const locales = ["es", "en"] as const
export const queryParams: QueryParams<typeof locales> = {
  "days": {
    es: "dias",
    en: "days",
  },
}

And then passed down when creating the middleware:

const intlMiddleware = createMiddleware({
  defaultLocale,
  locales,
  localePrefix,
  pathnames,
  queryParams,
})

Describe alternatives you've considered

I haven't looked at alternatives yet but I think I could manually parse the search params and translate their keys to the target locale before passing them down to router.replace.

amannn commented 2 months ago

Thank you for the question! While next-intl only allows to localize pathnames, you can choose to localize search params in your app code.

Example:

import {useLocale} from 'next-intl';

type Props = {
  params: {
    page?: string;
    pagina?: string;
  };
};

export default function SearchPage({params}: Props) {
  const locale = useLocale();
  const page = params[{
    en: 'page',
    es: 'pagina'
  }[locale]] || '1';

  return <div>Page {page}</div>;
}

As you've also mentioned, translating values of search params might be relevant too, therefore this is currently out-of-scope for next-intl to support out-of-the-box. Also note that search params are bound to a particular page, therefore accepting it in a global fashion might be error-prone.

Hope this helps!