Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: Getting started with all messages on the client side #1046

Merged
merged 7 commits into from
May 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 23 additions & 15 deletions docs/pages/docs/environments/server-client-components.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ Moving internationalization to the server side unlocks new levels of performance

**Benefits of server-side internationalization:**

1. Your messages never leave the server and don't need to be serialized for the client side
1. Your messages never leave the server and don't need to be passed to the client side
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe less scary.

2. Library code for internationalization doesn't need to be loaded on the client side
3. No need to split your messages, e.g. based on routes or components
4. No runtime cost on the client side
Expand Down Expand Up @@ -123,7 +123,22 @@ In regard to performance, async functions and hooks can be used very much interc

## Using internationalization in Client Components

Depending on your situation, you may need to handle internationalization in Client Components as well. There are several options for using translations or other functionality from `next-intl` in Client Components, listed here in order of recommendation.
Depending on your situation, you may need to handle internationalization in Client Components as well. While providing all messages to the client side is typically the easiest way to [get started](/docs/getting-started/app-router#layout) and a reasonable approach for many apps, you can be more selective about which messages are passed to the client side if you're interested in optimizing the performance of your app.

<Details id="client-messages-performance">
<summary>How does loading messages on the client side relate to performance?</summary>

Depending on the requirements for your app, you might want to monitor your [Core Web Vitals](https://web.dev/articles/vitals) to ensure your app meets your performance goals.

If you pass messages to `NextIntlClientProvider`, Next.js will emit them during the streaming render to the markup of the page so that they can be used by Client Components. This can contribute to the [total blocking time](https://web.dev/articles/tbt), which in turn can relate to the [interaction to next paint](https://web.dev/articles/inp) metric. If you're seeking to improve these metrics in your app, you can be more selective about which messages are passed to the client side.

However, as the general rule for optimization goes: Always measure before you optimize. If your app already performs well, there's no need for optimization.

Note that an automatic, compiler-driven approach for automatically splitting messages is being evaluated in [`next-intl#1`](https://github.com/amannn/next-intl/issues/1).

</Details>

There are several options for using translations from `next-intl` in Client Components, listed here in order of enabling the best performance:

### Option 1: Passing translations to Client Components

Expand Down Expand Up @@ -221,15 +236,15 @@ To keep internationalization on the server side, it can be helpful to structure
```tsx filename="app/register/page.tsx"
import {useTranslations} from 'next-intl';

// A Client Component, so that it can use `useFormState` to
// potentially display errors received after submission.
// A Client Component, so that `useFormState` can be used
// to potentially display errors received after submission.
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reads slightly better IMO.

import RegisterForm from './RegisterForm';

// A Client Component, so that it can use `useFormStatus`
// A Client Component, so that `useFormStatus` can be used
// to disable the input field during submission.
import FormField from './FormField';

// A Client Component, so that it can use `useFormStatus`
// A Client Component, so that `useFormStatus` can be used
// to disable the submit button during submission.
import FormSubmitButton from './FormSubmitButton';

Expand Down Expand Up @@ -310,14 +325,12 @@ export default function Counter() {
}
```

In case you prefer to make all messages available to the client side, you can [configure `NextIntlClientProvider` in the root layout](#option-4-providing-all-messages) instead.
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is covered in the very next headline.


<Details id="messages-client-namespaces">
<summary>How can I know the messages I need to provide to the client side?</summary>

Currently, the messages you select for being passed to the client side need to be picked based on knowledge about the implementation of the wrapped components.

An automatic, compiler-driven approach is being evaluated in [`next-intl#2`](https://github.com/amannn/next-intl/issues/1).
An automatic, compiler-driven approach is being evaluated in [`next-intl#1`](https://github.com/amannn/next-intl/issues/1).

</Details>

Expand Down Expand Up @@ -347,11 +360,6 @@ export default function LocaleLayout({children, params: {locale}}) {
}
```

<Callout type="warning">
Note that this is a tradeoff in regard to performance (see the bullet points
at the top of this page).
</Callout>
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Too dramatic IMO, we already told the user everything relevant at the top of the page :).

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Definitely agree, the wording scared me off a bit when I read this for the first time 😁


## Troubleshooting

### "Failed to call `useTranslations` because the context from `NextIntlClientProvider` was not found." [#missing-context]
Expand Down Expand Up @@ -404,4 +412,4 @@ export default function MyCustomNextIntlClientProvider({

By doing this, your custom provider will already be part of the client-side bundle and can therefore define and pass functions as props.

**Important:** Be sure to pass explicit `locale`, `timeZone` and `now` props to `NextIntlClientProvider` in this case, since the props aren't automatically inherited from a Server Component when you import `NextIntlClientProvider` from a Client Component.
**Important:** Be sure to pass explicit `locale`, `formats`, `timeZone` and `now` props to `NextIntlClientProvider` in this case, since the props aren't automatically inherited from a Server Component when you import `NextIntlClientProvider` from a Client Component.
30 changes: 16 additions & 14 deletions docs/pages/docs/getting-started/app-router.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import Details from 'components/Details';

# Next.js App Router Internationalization (i18n)

The Next.js App Router introduces support for [React Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components) and unlocks [many benefits](/docs/environments/server-client-components) when handling internationalization on the server side.

## Getting started

If you haven't done so already, [create a Next.js app](https://nextjs.org/docs/getting-started/installation) that uses the App Router.
Expand Down Expand Up @@ -56,8 +54,6 @@ Now, set up the plugin which creates an alias to provide your i18n configuration
<Tabs items={['next.config.mjs', 'next.config.js']}>
<Tab>

If you're using ECMAScript modules for your Next.js config, you can use the plugin as follows:
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not really necessary IMO.


```js filename="next.config.mjs"
import createNextIntlPlugin from 'next-intl/plugin';

Expand All @@ -72,8 +68,6 @@ export default withNextIntl(nextConfig);
</Tab>
<Tab>

If you're using CommonJS for your Next.js config, you can use the plugin as follows:
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as above.


```js filename="next.config.js"
const createNextIntlPlugin = require('next-intl/plugin');

Expand All @@ -90,7 +84,7 @@ module.exports = withNextIntl(nextConfig);

### `i18n.ts` [#i18nts]

`next-intl` creates a configuration once per request. Here you can provide messages and other options depending on the locale of the user.
`next-intl` creates a request-scoped configuration object that can be used to provide messages and other options depending on the locale of the user for usage in Server Components.

```tsx filename="src/i18n.ts"
import {notFound} from 'next/navigation';
Expand Down Expand Up @@ -148,24 +142,36 @@ export const config = {

### `app/[locale]/layout.tsx` [#layout]

The `locale` that was matched by the middleware is available via the `locale` param and can be used to configure the document language.
The `locale` that was matched by the middleware is available via the `locale` param and can be used to configure the document language. Additionally, we can use this place to pass configuration from `i18n.ts` to Client Components via `NextIntlClientProvider`.
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Always somewhat of a balance to include necessary information in the getting started guide, but be rather to the point here. We can save many details for later IMO.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In which part of the docs is there more information on this?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The global configuration docs have all the details about this.

I'd prefer to be quite selective about which links to include in the getting started docs and therefore not link to this page at this point. Links tend to create branches of user flows where a developer is just trying to get something up and running.

In the latest iteration I've now removed all links that would create "branches" and instead only used them if prerequisite knowledge is required (e.g. what a dynamic segment like [locale] is in Next.js).

Once the user has finished the setup, we can help the developer continue with the links in the "Next steps" section.

Does that sound reasonable to you?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I completely agree. I think that the getting started steps should be as simple as possible to allow users to get things working and then provide links later to allow for more exploration. Otherwise, as you said, users can get a bit distracted reading into things and perhaps confused.


```tsx filename="app/[locale]/layout.tsx"
export default function LocaleLayout({
import {getMessages} from 'next-intl/server';

export default async function LocaleLayout({
children,
params: {locale}
}: {
children: React.ReactNode;
params: {locale: string};
}) {
// Providing all messages to the client
// side is the easiest way to get started
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inline comments are often copied along to user apps, so this could be a reminder when revisiting this code at a later stage of the project.

const messages = await getMessages();
Copy link
Owner Author

@amannn amannn May 3, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This component could also use useMessages, but I think we can reasonably suggest implementing LocaleLayout as an async Server Component. A minor benefit is that this ensures that NextIntlClientProvider is rendered from a Server Component now.

While this is a subtle difference from the users' perspective, it enables automatically inheriting configuration from i18n.ts. If the user makes the root layout a Client Component, this wouldn't be possible and more wiring is needed.


return (
<html lang={locale}>
<body>{children}</body>
<body>
<NextIntlClientProvider messages={messages}>
{children}
</NextIntlClientProvider>
</body>
</html>
);
}
```

Note that `NextIntlClientProvider` automatically inherits most configuration from `i18n.ts` here.

### `app/[locale]/page.tsx` [#page]

Use translations in your page components or anywhere else!
Expand All @@ -191,10 +197,6 @@ In case you ran into an issue, have a look at [the App Router example](https://n

<ul className="ml-4 list-disc">
<li>[Usage guide](/docs/usage): Format messages, dates and times</li>
<li>
[Environments](/docs/environments): Explore usage in Server & Client
Components and the Metadata API
</li>
<li>
[Routing](/docs/routing): Integrate i18n routing with `<Link />` & friends
</li>
Expand Down
78 changes: 52 additions & 26 deletions docs/pages/docs/usage/configuration.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,11 @@ The configuration object is created once for each request by internally using Re
`NextIntlClientProvider` can be used to provide configuration for **Client Components**.

```tsx filename="app/[locale]/layout.tsx" /NextIntlClientProvider/
import {NextIntlClientProvider, useMessages} from 'next-intl';
import {NextIntlClientProvider} from 'next-intl';
import {getMessages} from 'next-intl/server';

export default function LocaleLayout({children, params: {locale}}) {
const messages = useMessages();
export default async function LocaleLayout({children, params: {locale}}) {
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similar reasoning as above.

const messages = await getMessages();

return (
<html lang={locale}>
Expand All @@ -56,13 +57,18 @@ export default function LocaleLayout({children, params: {locale}}) {
}
```

`NextIntlClientProvider` inherits the props `locale`, `now` and `timeZone` when the component is rendered from a Server Component. Other configuration like `messages` and `formats` can be provided as necessary.
These props are inherited if you're rendering `NextIntlClientProvider` from a Server Component:

1. `locale`
2. `now`
3. `timeZone`

In contrast, these props can be provided as necessary:

<Callout>
Before passing all messages to the client side, learn more about the options
you have to [use internationalization in Client
Components](/docs/environments/server-client-components).
</Callout>
1. `messages` (see [Internationalization in Client Components](/docs/environments/server-client-components#using-internationalization-in-client-components))
2. `formats`
3. `defaultTranslationValues`
4. `onError` and `getMessageFallback`

## Messages

Expand Down Expand Up @@ -95,29 +101,37 @@ export default getRequestConfig(async ({locale}) => {
});
```

To read configured messages in a component, you can use the `useMessages` hook:
After messages are configured, they can be used via `useTranslations`.

In case you require access to messages in a component, you can use a convenience API to read them from your configuration:

```tsx
// Regular components
import {useMessages} from 'next-intl';

const messages = useMessages();

// Async Server Components
import {getMessages} from 'next-intl/server';
const messages = await getMessages();
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getMessages might be more common than useMessages. This is in contrast to all other APIs from next-intl, like useTranslations/getTranslations etc.

Due to this, it might be a good idea to briefly mention this API on this page too. To be consistent, I've included them for the other config options below as well.

```

</Tab>
<Tab>

```tsx
import {NextIntlClientProvider, useMessages} from 'next-intl';
import {NextIntlClientProvider} from 'next-intl';
import {getMessages} from 'next-intl/server';

// Read messages configured via `i18n.ts`. Alternatively,
// messages can be fetched from any other source too.
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reading from other sources shouldn't be relevant here (see also "How can I load messages from remote sources?" above).

const messages = useMessages();
async function Component({children}) {
// Read messages configured via `i18n.ts`
const messages = await getMessages();

return (
<NextIntlClientProvider messages={messages}>
{children}
</NextIntlClientProvider>
);
return (
<NextIntlClientProvider messages={messages}>
{children}
</NextIntlClientProvider>
);
}
```

</Tab>
Expand Down Expand Up @@ -211,12 +225,16 @@ const timeZone = 'Europe/Vienna';

The available time zone names can be looked up in [the tz database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones).

To read the time zone in a component, you can use the `useTimeZone` hook:
The configured time zone can be read from components:

```tsx
// Regular components
import {useTimeZone} from 'next-intl';
const messages = useTimeZone();

const timeZone = useTimeZone();
// Async Server Components
import {getTimeZone} from 'next-intl/server';
const timeZone = await getTimeZone();
```

The time zone in Client Components is automatically inherited from the server
Expand Down Expand Up @@ -261,12 +279,16 @@ const now = new Date('2020-11-20T10:36:01.516Z');
</Tab>
</Tabs>

To read the now value in a component, you can use the `useNow` hook:
The configured `now` value can be read from components:

```tsx
// Regular components
import {useNow} from 'next-intl';

const now = useNow();

// Async Server Components
import {getNow} from 'next-intl/server';
const now = await getNow();
```

Similarly to the `timeZone`, the `now` value in Client Components is
Expand Down Expand Up @@ -527,12 +549,16 @@ function getMessageFallback({namespace, key, error}) {

The current locale of your app is automatically incorporated into hooks like `useTranslations` & `useFormatter` and will affect the rendered output.

In case you need to use this value in other places of your app, you can read it via the `useLocale` hook:
In case you need to use this value in other places of your app, you can read it in components:

```tsx
// Regular components
import {useLocale} from 'next-intl';

const locale = useLocale();

// Async Server Components
import {getLocale} from 'next-intl/server';
const locale = await getLocale();
```

<Details id="locale-change">
Expand Down
Loading