next-intl
next-intl copied to clipboard
Improve initial render of `Link` for `localePrefix: 'as-necessary'` and make `getPathname` more useful
Is your feature request related to a problem? Please describe.
The localePrefix: 'as-necessary' strategy currently has these drawbacks:
- The initial render of
Linkin RSC always includes a prefix, which we potentially remove during hydration if we detect that no locale prefix should be used. getPathnameis somewhat hard to use, because users have to specify their own logic to check if a prefix should be added.
Describe the solution you'd like
- The navigation APIs should accept
localePrefix,defaultLocaleanddomains, all being expected to be provided in case you use them. We should move all routing config to a sharedRoutingConfigtype that can be shared with the middleware. Linkshould consider the new options for the initial render (see https://github.com/amannn/next-intl/issues/444#issuecomment-1832223775). IfLinkreceiveslocales, we should be able to useusePathnameto see if the current pathname is prefixed and use this information to get the initial SSR render right.getPathnameshould consider the options too and return a final pathname (with/without a locale prefix, with/without domain). Furthermore,getPathnameshould be supported for shared pathnames too.- The remaining navigation APIs should also be checked for which improvements we could make based on the new configuration.
- Navigation APIs could accept a
domainif a user wants to link/redirect to another domain.
This will require a major version to ensure users supply the new options (related to https://github.com/amannn/next-intl/issues/779).
In regard to (2) there's an edge case for localePrefix: 'as-necessary' and domains. The domain is only available at request time, therefore we have to either a) support SSG and potentially patch the href of Link on the client side or b) require dynamic rendering and return a final URL. This is TBD. Note that getPathname only has "one shot" to return a final URL, which would certainly require reading from headers. An idea could be to require dynamic rendering in case domains are configured, but to point users towards the alternative of building a separate app per domain if SSG is important.
Make sure to remove the note in the localePrefix: 'as-needed' docs once this is implemented.
Describe alternatives you've considered
The problems outlined above are mostly related to localePrefix: 'as-necessary'.
You can avoid these by either:
- Using
localePrefix: 'always' - Using
localePrefix: 'never'and supplying this to the navigation factory function (already supported)
@jlalmes Can you provide a screenshot from the Google Search Console issue that shows the issue?
Maybe I was a bit too naive to think that this isn't an issue for Google, since we a) always have a working URL with the redirect and b) patch it up as necessary on the client side.
Here's a screenshot from Google Search Console for a new-ish site I'm working on. It's a non-critical issue because the correct pages are indexed, but this error is also shown for the prefixed paths.
Hmm, I see—thanks! Is maybe localePrefix: 'always' a viable workaround for you for the time being? I'll look into getting this fixed for localePrefix: 'as-necessary' though, but I can't promise an ETA yet!
Small update:
The factory functions for navigation APIs that are being worked on in #426 could help to mitigate this for localePrefix: 'as-necessary'. However, as soon as the user introduces domain configuration, we're again in a position where we don't know if a given pathname should be prefixed or not, since domains can have different default locales.
That means that if the default locale can only be determined in the middleware, we can't statically render different link targets on the server side. If the navigation APIs would also accept domain config, we could check if the user doesn't use domain config to mitigate this, but this gets quite complex and still doesn't fix all cases (i.e. when the user uses a domain config). Also, we have to accept domain config only to detect if the user doesn't use one—seems a bit backward.
I'm wondering if it would be a good idea to flip the default for localePrefix to always, as it doesn't have the issue, and educate users about this side effect when using localePrefix: 'as-necessary'.
Update: With the release candidate, the default for localePrefix was changed to always, which seems to be a better default.
@amannn Could this be fixed more easily for when the localePrefix is set to never?
That's a good point actually. Based on your use case, in https://github.com/amannn/next-intl/commit/18157bc255c0f278e85569c9e367f40d5806b0c1 I've added a note that localeDetection: 'never' is also useful if you have locales per domain.
With that, we could consider:
- Adding an optional
localePrefixtocreateSharedPathnamesNavigationas well ascreateLocalizedPathnamesNavigationthat if set toneverwill not add a prefix to links. With this, onlyas-necessaryneeds the current patching behavior. - Update the docs accordingly:
- Mention in the middleware docs for
localePrefixthat if a value other thanalwaysis chosen, this should be set for the navigation factory function too. - Add a note to the navigation docs about the new property.
- Mention in the middleware docs for
Would you be interested in working on this?
@amannn sounds like a plan! For now I have added a wrapper component that seems to do the trick:
"use client";
import {
type I18nLink,
type LocaleCode,
getPathname,
type pathnames,
} from "@/lib/navigation";
import { useLocale } from "next-intl";
import NextLink from "next/link";
import { type ComponentProps } from "react";
export function Link<Pathname extends keyof typeof pathnames>({
href,
...rest
}: ComponentProps<typeof I18nLink<Pathname>>) {
const locale = useLocale() as LocaleCode;
// @ts-expect-error
const localizedHref = getPathname({ href, locale });
return <NextLink href={localizedHref} {...rest} />;
}
Sounds good! I've started working on an implementation.
@zipme I've addressed your use case in https://github.com/amannn/next-intl/pull/678, this should help!
In regard to this issue: As a second step, if the navigation APIs would accept domains (like the middleware), then we could fix the initial render of Link for localePrefix: 'as-needed' too (if no domains are provided). There could arguably be some additional benefit by accepting a typed domain argument for Link (e.g. <Link href={{pathname: '/', domain: 'ca.example.com'}} />) in case users want to link to other domains. I think that would move us to a good-enough situation, where patching of the href is really only required in case you use domain-based routing and localePrefix: 'as-necessary'.
This would require a major version though to require domains for the navigation APIs in case this feature is being used. I'll leave this here for reference for now, it's TBD if this will be added.
I was fiddling around with the navigation APIs these days, and realised that it seems impossible (at least for me) to make the domains feature in a way that supports SSG, since the domain can't be controlled as static params and is only resolved through middleware (or by manually specifying it). Did you have any ideas on how to solve that issue @amannn ?
Replied here: https://github.com/amannn/next-intl/issues/653#issuecomment-1905948937
When using localePrefix = "as-needed" and no domains, using createLocalizedPathnamesNavigation like
export const {
redirect,
Link
} = createLocalizedPathnamesNavigation({ locales, pathnames, localePrefix });
And calling redirect("/login") would still redirect to /en/login even if en is the default locale. (The same goes for Link https://github.com/amannn/next-intl/issues/808)
I think it's possible and not too difficult if we also pass in the defaultLocale here:
export const {
redirect,
Link
} = createLocalizedPathnamesNavigation({ locales, pathnames, localePrefix, defaultLocale });
To let it redirect correctly right? But indeed, for domains configuration this would still be quite complicated I suppose
I am doing this now as a workaround:
import { type RedirectType, redirect as nextRedirect } from "next/navigation";
import { locales, pathnames, localePrefix, defaultLocale } from './config'
import NextLink from "next/link";
export const {
redirect,
getPathname: getPathname_
} = createLocalizedPathnamesNavigation({ locales, pathnames, localePrefix });
export const getPathname: typeof getPathname_ = ({ href, locale }) => {
const pathname = getPathname_({ href, locale });
let prefix = "";
if (locale !== defaultLocale) {
prefix = `/${locale}`;
}
return `${prefix}${pathname}`;
};
export const redirect: typeof redirect_ = (href, type) => {
const locale = useLocale();
const path = getPathname({ href, locale });
nextRedirect(path, type);
};
export function Link<Pathname extends keyof typeof pathnames>(
{ href, ...rest }: ComponentProps<typeof I18nLink<Pathname>>,
ref: ForwardedRef<ElementRef<typeof NextLink>>,
) {
const locale = useLocale();
// @ts-expect-error this is okay
const localizedHref = getPathname({ href, locale });
return <NextLink href={localizedHref} {...rest} ref={ref} />;
}
Thanks for workarounds. Hope, that fix will be rolled out soon. As there is no point to initially render locale in tag, as it is causing SEO issues.