next-intl icon indicating copy to clipboard operation
next-intl copied to clipboard

Geting rid of `setRequestLocale`

Open amannn opened this issue 1 year ago β€’ 34 comments
trafficstars

As mentioned in the static rendering docs, setRequestLocale is intended as a stopgap solution to be removed at some point. I've started a discussion for the relevant feature on the Next.js side here: https://github.com/vercel/next.js/discussions/58862

If you'd like to help simplify the usage of next-intl, please join the discussion there and upvote the comment!

amannn avatar Nov 24 '23 13:11 amannn

image Some components need to use "use client", and I want to output static files. There is a conflict between the two. How should I solve it?

xie392 avatar Dec 12 '23 17:12 xie392

You don’t need to call the function in client-only pages.

amannn avatar Dec 12 '23 17:12 amannn

I'm curious about whether calling setRequestLocale at the top level app/[locale]/layout.tsx will apply to the whole app or not?

When exporting generateStaticParams at the layout all sub routes are affected by it.

AhmedBaset avatar Jan 04 '24 20:01 AhmedBaset

Unfortunately not, please see the corresponding docs: Add unstable_setRequestLocale to all layouts and pages. It might work in some cases, but there's a race condition. To work reliably, you should add it to every layout and every page that you wish to enable static rendering for.

amannn avatar Jan 09 '24 09:01 amannn

We'll probably introduce support for providing a locale to next-intl as an alternative to having to use the middleware to negotiate this (see https://github.com/amannn/next-intl/pull/1017). If your app only supports a single locale, this will enable static rendering without workarounds.

amannn avatar May 01 '24 14:05 amannn

A realization while working on https://github.com/amannn/next-intl/pull/1017: We currently support a defaultLocale that is used as a fallback when matching locales in the middleware. However, the defaultLocale only applies to this particular case.

Developers have previously asked why the defaultLocale isn't used when using next-intl APIs outside of the [locale] folder (see e.g. https://github.com/amannn/next-intl/discussions/1067, but also others).

In case the developer could manage the reading of the locale from params manually in i18n.ts, this would also enable returning a fallback locale for cases like this.

Ideally, something like this would be possible:

import {notFound} from 'next/navigation';
import {getRequestConfig} from 'next-intl/server';
import {getParams} from '???';
 
// Can be imported from a shared config
const locales = ['en', 'de'];
 
export default getRequestConfig(async () => {
  let {locale} = getParams();
  if (!locale) locale = 'en';

  // Validate that the incoming `locale` parameter is valid
  if (!locales.includes(locale as any)) notFound();
 
  return {
    locale,
    messages: (await import(`../messages/${locale}.json`)).default
  };
});

amannn avatar May 13 '24 09:05 amannn

Hello. I recently used next-intl in a job project and now I've rolled it back. As I've worked on such a thing I know the importance of feedback)

A bit late comment, just to add to the value of this issue)

setRequestLocale loses context. At random moments. There are 2 pages - one works perfectly with translations, the other loses them. Both have a similar structure, both use client and server components, client contexts on top. Loses in a random place. That is, three component levels have translations, but everything below in the tree lost, and they were correctly passed to the clients (I initialize NextIntlClientProvider at the root of the page).

I have a feeling that it breaks when it render some clients components (but I can't confirm this in any way). I saw somewhere recommendation to use my context - it has the same problem. Apparently, there are something of component rendering in React.

Although in the case of my context, you can set the build to one process and everything will be correct, and the context in case of something is lost immediately on the entire page. So the reasons are different.

However, I see an update came out these days, that locale can be set the way you want to (where would I get the getParams method πŸ€”πŸ˜) - thank you, will try it.

Overall, thanks for the package, cool API!

alexdln avatar May 16 '24 14:05 alexdln

Hey @vordgi! Nice to hear from you here, been following your work with nimpl-getters! :)

Can you by chance provide a reproduction where you observe that the context is lost? The important part for setRequestLocale to work correctly is that it's added to each and every layout and page where you're using APIs from next-intl. It should receive the locale from params as soon as rendering starts and before any APIs from next-intl are called.

Are you using any more exotic features from Next.js? E.g. I could imagine that PPR could potentially conflict with this.

Btw. in case you're interested, I had a look at what it'd take for native support from Next.js for providing a "server context" yesterday: https://github.com/vercel/next.js/discussions/58862#discussioncomment-9446295. Leave a comment there if you have additional context!

amannn avatar May 16 '24 16:05 amannn

The parameters have been added everywhere. I will try to create an repro, but basically, it looks like this:

const Page: React.FC<{ params: { lang: string } }> = async ({ params }) => {
	if (!validLocales.includes(params.lang)) return notFound();

	unstable_setRequestLocale(params.lang);
	const messages = await getMessages();

	return (
		<NextIntlClientProvider messages={messages}>
			{/* Client component with context.provider inside */}
			<ContextProvider value={{key1: [],key2: ''}}>
				<script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify('...')}} />
				{/* Asynchronous server component, translations are only at the top level of this component, below they are lost */}
				<Layout>
					{/* server component whithout translates */}
					<Block1 />
				</Layout>
			</ContextProvider>
		</NextIntlClientProvider>
	);
};

Yes, there are indeed risks with PPR. But I think that if functionality is unavailable in part of next.js - just block the functionality in that part. That is, I will add the error "Do not use this in PPR". I hope such an opportunity will be. But in fact, with the current structure of next.js, it is very difficult to find out what the component is inside and it is difficult to rewrite this logic (I tried).

I am now looking at the possibility of adding the ability to create a page context. But still only at the beginning of the research

alexdln avatar May 16 '24 16:05 alexdln

Wish me luck)

getPageContext PR

alexdln avatar May 17 '24 18:05 alexdln

Regarding PPR: On a second thought, maybe this is not an issue at all, since PPR is about pre-rendering as much as possible statically with inner parts remaining dynamic. Dynamic rendering was always the easy part since we can just read a header from the middleware there. Let's see what Next.js 14 brings next week, maybe there are news in regard to PPR and we could do a few first tests.

getPageContext PR

Oh interesting, thanks for looking into this! As far as I understand the proposal, this would still require providing the locale for every page where you intend to read it, right? In that regard the ergonomics would be similar to unstable_setRequestLocale.

I think ideally Next.js should really have a built-in capability to read params deeply in RSC.

amannn avatar May 18 '24 12:05 amannn

In Next.js, you can add parameters to their internal context and then read it the same way I read in getPathname. But Next.js stubbornly doesn't want to go that way. So I'm trying to offer them alternatives.

Yes, it will need to be added for each page, it's something comparable to getStaticProps before, but you can read from anywhere. In general, this is close to Next.js API and I hope to push some solution.

alexdln avatar May 18 '24 12:05 alexdln

Yep, definitely a good idea to discuss which options we have! I think a tricky part about the story with params is that they can be different per layout/page. A single render might consist of multiple layouts that render and a single page. Theoretically there could be different params at every level (e.g. /[locale]/[tenant]/page.tsx).

amannn avatar May 18 '24 12:05 amannn

Since they want to render the layout separately (this needs to be technically done at first because it works differently now) - I think in the layout the get-params functionality should be blocked or fixed with params higher in the tree. This is logical in such a situation - it was assembled as a segment once - where it lies.

alexdln avatar May 18 '24 13:05 alexdln

I think in the layout the get-params functionality should be blocked or fixed with params higher in the tree.

Currently, you can already read params in the layout via the params prop. There would be no need to call getParams there. If you did, it should return the same value as the prop.

AhmedBaset avatar May 18 '24 13:05 AhmedBaset

Decided to make a PR with the implementation of get-params (what I talked about above, in the basic version - a very simple change).

alexdln avatar May 18 '24 13:05 alexdln

Currently, you can already read params in the layout via the params prop

Yes, but what about components 10 levels deeper. They now have no idea - they are inside layout or page. And with the current next.js architecture, it's unreal to find out. So I think next.js need to render layout separately and then we can understand what is being rendered and depending on it, return the necessary params or block the API (although it looks like there shouldnt be any problems with issuance). But it's still not clear how it would be with PPR, yes...

alexdln avatar May 18 '24 13:05 alexdln

Hello @amannn. I have to say sorry for incorrect conclusions. The cache works well.

The problem was that I used setRequestLocale in not-found (and there defined it dynamically or gave a default). And this could overwrite what is written at the page level.

The most annoying thing is that I knew that <NotFound /> is rendered with the page.

I rewrote it in not-found on prop drilling and everything works well.

So, in general, it is always necessary to consider that the cache, unlike the context (and AsyncLocalStorage), is precisely a global storage. And since Layout, NotFound, Error, and Page are rendered as a whole, such situations can arise when there are discrepancies.

alexdln avatar May 20 '24 07:05 alexdln

Any update on getting rid of this?

suitux avatar Jul 03 '24 17:07 suitux

How about writing a SWC plugin to automatically inject unstable_setRequestLocale into all layouts and pages?

Then people would just have to add it to experimental.swcPlugins in the next.config.js (or it could be added by withNextIntl). The plugin should ignore pages/layouts that use "use client" or are not under the route /[locale]. The name of the prop should be configurable to support /[lang], /[language], ... and default to locale (or maybe to ['locale', 'lang', 'language'] to work with all 3). The plugin would also have to detect the routes in route groups (/(test)/[locale]), parallel routes, intercepting routes, ....

darthmaim avatar Jul 03 '24 18:07 darthmaim

Certainly an interesting idea! I don't have experience with writing SWC plugins, but if there's a community effort to build this as a separate package I'd be happy to follow along and potentially explore adding it to the docs or if the approach proves to work well, we could consider adding it to the core. I'm unsure currently if there are edge cases, so this might need so experimentation.

The ideal solution would still require support from the Next.js side I believe: https://github.com/vercel/next.js/discussions/58862. But if we can improve the current workaround for the time being, I'd be all for it.

amannn avatar Jul 04 '24 14:07 amannn

Here's an SWC plugin that could be used for inspiration: css-variable/swc (usage in Next.js)

amannn avatar Jul 10 '24 09:07 amannn

This is only tangentially related, but I also feel it does not deserve a separate issue: if you have a root layout outside [locale] eg. to render a global non-localized not-found as specified in the docs , then Next will opt-out of static rendering on every page, since the root layout does not (and cannot) have the mandatory unstable_setRequestLocale call. I don't think there's a way to solve this without removing the root layout altogether, does anyone have any ideas?

nevnein avatar Aug 05 '24 14:08 nevnein

This is only tangentially related, but I also feel it does not deserve a separate issue: if you have a root layout outside [locale] eg. to render a global non-localized not-found as specified in the docs , then Next will opt-out of static rendering on every page, since the root layout does not (and cannot) have the mandatory unstable_setRequestLocale call. I don't think there's a way to solve this without removing the root layout altogether, does anyone have any ideas?

I am having the same issues with you. Once I remove the layout.tsx and not-found.tsx that outside [locale]. next build command is successfully built. Any ideas?

WenLonG12345 avatar Aug 09 '24 16:08 WenLonG12345