### Installation command
Source: https://github.com/amannn/next-intl/blob/main/packages/use-intl/README.md
Command to install the `use-intl` package.
```bash
npm install use-intl
```
--------------------------------
### IntlProvider and useTranslations example
Source: https://github.com/amannn/next-intl/blob/main/packages/use-intl/README.md
Example demonstrating how to set up `IntlProvider` and use `useTranslations` in a React application.
```jsx
import {IntlProvider, useTranslations} from 'use-intl';
// You can get the messages from anywhere you like. You can also
// fetch them from within a component and then render the provider
// along with your app once you have the messages.
const messages = {
App: {
hello: 'Hello {firstName}!'
}
};
function Root() {
return (
);
}
function App({user}) {
const t = useTranslations('App');
return
{t('hello', {firstName: user.firstName})}
;
}
```
--------------------------------
### PO Format Example (Manual Key)
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/plugin.mdx
An example of a message catalog using the PO format with a manually defined key, including description and file reference.
```po
#. Advance to the next slide
#: src/components/Carousel.tsx
msgid "carousel.next"
msgstr "Right"
```
--------------------------------
### JSON Format Example (Manual Key)
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/plugin.mdx
An example of a message catalog using the JSON format with a manually defined key.
```json
{
"greeting": "Hello"
}
```
--------------------------------
### PO Format Example (Auto-generated Key)
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/plugin.mdx
An example of a message catalog using the PO format with an auto-generated key, typically when using `useExtracted`, including description and file reference.
```po
#. Advance to the next slide
#: src/components/Carousel.tsx
msgid "5VpL9Z"
msgstr "Right"
```
--------------------------------
### Stricter domains configuration example
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/blog/next-intl-4-0.mdx
Example demonstrating the new stricter `domains` configuration with `defineRouting`, specifying `locales` for each domain and using `localePrefix: 'as-needed'`.
```tsx
import {defineRouting} from 'next-intl/routing';
export const routing = defineRouting({
locales: ['sv-SE', 'en-SE', 'no-NO', 'en-NO'],
defaultLocale: 'en-SE',
localePrefix: {
mode: 'as-needed',
prefixes: {
'en-SE': '/en',
'en-NO': '/en'
}
},
domains: [
{
domain: 'example.se',
defaultLocale: 'sv-SE',
locales: ['sv-SE', 'en-SE']
},
{
domain: 'example.no',
defaultLocale: 'no-NO',
locales: ['no-NO', 'en-NO']
}
]
});
```
--------------------------------
### Implement generateStaticParams
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/routing/setup.mdx
Example of using `generateStaticParams` to define locales for static rendering at build time.
```tsx
import {routing} from '@/i18n/routing';
export function generateStaticParams() {
return routing.locales.map((locale) => ({locale}));
}
```
--------------------------------
### JSON Format Example (Auto-generated Key)
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/plugin.mdx
An example of a message catalog using the JSON format with an auto-generated key, typically when using `useExtracted`.
```json
{
"NhX4DJ": "Hello"
}
```
--------------------------------
### GNU gettext .po file example
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/blog/use-extracted.mdx
An example of a .po file showing how context (description, file reference) is provided alongside the message ID and translation.
```po
#. Greeting shown to user when logging back in
#: src/app/(auth)/login/page.tsx
msgid "0MXX5B"
msgstr "Welcome back!"
```
--------------------------------
### src/proxy.ts
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/routing/setup.mdx
Example of how to customize the matcher in `src/proxy.ts` to include pathnames that contain dots, such as user profiles.
```tsx
// ...
export const config = {
matcher: [
// Match all pathnames except for
// - … if they start with `/api`, `/trpc`, `/_next` or `/_vercel`
// - … the ones containing a dot (e.g. `favicon.ico`)
'/((?!api|trpc|_next|_vercel|.*\..*).*)',
// Match all pathnames within `{/:locale}/users`
'/([\w-]+)?/users/(.+)'
]
};
```
--------------------------------
### `srcPath` for monorepo
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/plugin.mdx
Example of `srcPath` configuration for a monorepo with multiple packages.
```tsx
// Monorepo with multiple packages
srcPath: ['./src', '../ui'],
```
--------------------------------
### Using the format function
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/blog/precompilation.mdx
An example call to the `format` function, which is the minimal runtime.
```tsx
format(compiled, 'en', {count: 2});
```
--------------------------------
### `srcPath` for `src` folder
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/plugin.mdx
Example of `srcPath` configuration when using a `src` folder.
```tsx
// Using a `src` folder
srcPath: './src',
```
--------------------------------
### Install next-intl
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/getting-started/app-router.mdx
Install the `next-intl` package.
```sh
npm install next-intl
```
--------------------------------
### Configuring a Custom Format
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/plugin.mdx
Example of how to reference a custom codec and its extension in the `next.config.ts` file.
```tsx
const withNextIntl = createNextIntlPlugin({
experimental: {
messages: {
format: {
codec: './CustomCodec.ts',
extension: '.json'
}
// ...
}
}
});
```
--------------------------------
### Formatting display names
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/display-name.mdx
Example demonstrating how to use `format.displayName` for regions, languages, currencies, and scripts.
```js
import {useFormatter} from 'next-intl';
function Component() {
const format = useFormatter();
// Renders "United States"
format.displayName('US', {type: 'region'});
// Renders "English"
format.displayName('en', {type: 'language'});
// Renders "US Dollar"
format.displayName('USD', {type: 'currency'});
// Renders "Latin"
format.displayName('Latn', {type: 'script'});
}
```
--------------------------------
### `srcPath` with external dependency
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/plugin.mdx
Example of `srcPath` configuration including an external dependency on a package.
```tsx
// External dependency on a package
srcPath: ['./src', './node_modules/@acme/components'],
```
--------------------------------
### Compiling a simple message
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/blog/precompilation.mdx
Example of `compile` function with a simple message.
```tsx
compile('Hello {name}!');
```
--------------------------------
### `srcPath` without `src` folder
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/plugin.mdx
Example of `srcPath` configuration when not using a `src` folder.
```tsx
// Not using a `src` folder
srcPath: './',
```
--------------------------------
### en.json message file example
Source: https://github.com/amannn/next-intl/blob/main/README.md
An example of an English message file (`en.json`) defining translations for the `UserProfile` namespace, including ICU message syntax for plurals and date formatting.
```js
// en.json
{
"UserProfile": {
"title": "{firstName}'s profile",
"membership": "Member since {memberSince, date, short}",
"followers": "{count, plural, \n =0 {No followers yet} \n =1 {One follower} \n other {# followers} \n }"
}
}
```
--------------------------------
### Upgrade next-intl
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/blog/next-intl-3-0.mdx
Command to install the latest version of the next-intl package.
```bash
npm install next-intl@latest
```
--------------------------------
### Formatting a number with useFormatter
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/numbers.mdx
This example shows how to use the `useFormatter` hook to format a plain number as currency.
```js
import {useFormatter} from 'next-intl';
function Component() {
const format = useFormatter();
// Renders "$499.90"
format.number(499.9, {style: 'currency', currency: 'USD'});
}
```
--------------------------------
### Formatting date and time ranges
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/dates-times.mdx
Example of using `format.dateTimeRange` to format a date range.
```js
import {useFormatter} from 'next-intl';
function Component() {
const format = useFormatter();
const dateTimeA = new Date('2020-11-20T08:30:00.000Z');
const dateTimeB = new Date('2021-01-24T08:30:00.000Z');
// Renders "Nov 20, 2020 – Jan 24, 2021"
format.dateTimeRange(dateTimeA, dateTimeB, {
year: 'numeric',
month: 'short',
day: 'numeric'
});
}
```
--------------------------------
### Using `NavigationLink` Component
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/routing/navigation.mdx
Example demonstrating how to use the custom `NavigationLink` component within a navigation bar.
```tsx
```
--------------------------------
### Basic Usage of `createNavigation`
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/blog/next-intl-3-22.mdx
Demonstrates how to import and use `createNavigation` with `defineRouting` to set up Link, redirect, usePathname, and useRouter.
```tsx
import {createNavigation} from 'next-intl/navigation';
import {defineRouting} from 'next-intl/routing';
export const routing = defineRouting(/* ... */);
export const {Link, redirect, usePathname, useRouter} =
createNavigation(routing);
```
--------------------------------
### Example Entry in a Portable Object (.po) Catalog
Source: https://github.com/amannn/next-intl/blob/main/rfcs/001-message-extraction.md
This snippet demonstrates a .po file entry, including comments for contextual descriptions and file path references, which are crucial for providing translator context and maintaining key validity.
```po
#. Advance to the next slide
#: src/components/Carousel.tsx
msgid "5VpL9Z"
msgstr "Right"
...
```
--------------------------------
### Add setRequestLocale to Page
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/routing/setup.mdx
Example of `setRequestLocale` in `app/[locale]/page.tsx` to enable static rendering before utilizing `next-intl` hooks.
```tsx
import {use} from 'react';
import {setRequestLocale} from 'next-intl/server';
import {useTranslations} from 'next-intl';
export default function IndexPage({params}) {
const {locale} = use(params);
// Enable static rendering
setRequestLocale(locale);
// Once the request locale is set, you
// can call hooks from `next-intl`
const t = useTranslations('IndexPage');
return (
// ...
);
}
```
--------------------------------
### Add setRequestLocale to Layout
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/routing/setup.mdx
Example of `setRequestLocale` in `app/[locale]/layout.tsx` to enable static rendering and validate the incoming locale.
```tsx
import {setRequestLocale} from 'next-intl/server';
import {hasLocale} from 'next-intl';
import {notFound} from 'next/navigation';
import {routing} from '@/i18n/routing';
type Props = {
children: React.ReactNode;
params: Promise<{locale: string}>;
};
export default async function LocaleLayout({children, params}: Props) {
const {locale} = await params;
if (!hasLocale(routing.locales, locale)) {
notFound();
}
// Enable static rendering
setRequestLocale(locale);
return (
// ...
);
}
```
--------------------------------
### Using global formats for display names
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/display-name.mdx
Example showing how to use a globally configured format by name and how to optionally override options.
```js
// Use a global format
format.displayName('US', 'region');
// Optionally override some options
format.displayName('US', 'region', {style: 'narrow'});
```
--------------------------------
### Redirect to default locale for static export
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/routing/middleware.mdx
Example of a root page ("app/page.tsx") that redirects users to the default locale when "/" is requested in a static export setup.
```tsx
import {redirect} from 'next/navigation';
// Redirect the user to the default locale when `/` is requested
export default function RootPage() {
redirect('/en');
}
```
--------------------------------
### Opting out of NextIntlClientProvider inheritance
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/blog/next-intl-4-0.mdx
Example demonstrating how to explicitly opt-out of inheriting `messages` and `formats` by setting them to `null`.
```tsx
...
```
--------------------------------
### Plain string precompilation
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/blog/precompilation.mdx
Demonstrates that plain strings have no precompilation overhead.
```text
"Welcome!" → "Welcome!"
```
--------------------------------
### Right-to-Left Text Example
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/translations.mdx
An example of text written in a right-to-left language (Arabic).
```text
النص في اللغة العربية _مثلا_ يُقرأ من اليمين لليسار
```
--------------------------------
### Example `t()` call with count argument
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/blog/next-intl-4-0.mdx
An example of calling the `t()` function with a `count` argument.
```tsx
t('followers', {count: 30000});
```
--------------------------------
### useTranslations example
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/workflows/typescript.mdx
Example showing type safety for message keys using useTranslations.
```tsx
function About() {
// ✅ Valid namespace
const t = useTranslations('About');
// ✖️ Unknown message key
t('description');
// ✅ Valid message key
t('title');
}
```
--------------------------------
### Using global number formats
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/numbers.mdx
This example demonstrates how to reference a globally configured number format by name, and how to optionally override some of its options.
```js
// Use a global format
format.number(499.9, 'precise');
// Optionally override some options
format.number(499.9, 'price', {currency: 'USD'});
```
--------------------------------
### useLocale example
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/workflows/typescript.mdx
Example showing how useLocale returns a strictly typed locale after augmentation.
```tsx
import {useLocale} from 'next-intl';
// ✅ 'en' | 'de'
const locale = useLocale();
```
--------------------------------
### i18n-check Output Example
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/workflows/messages.mdx
Example output from i18n-check showing detected missing keys.
```text
Found missing keys!
┌────────────────────┬───────────────────────────────┐
│ file │ key │
├────────────────────┼───────────────────────────────┤
│ messages/de.json │ NewsArticle.title │
└────────────────────┴───────────────────────────────┘
```
--------------------------------
### Link component example
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/workflows/typescript.mdx
Example showing Link component validation with a strictly typed locale.
```tsx
import {Link} from '@/i18n/routing';
// ✅ Passes the validation
;
```
--------------------------------
### `next.config.js` setup
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/getting-started/app-router.mdx
Setup the `next-intl` plugin in `next.config.js` for JavaScript projects.
```js
const createNextIntlPlugin = require('next-intl/plugin');
const withNextIntl = createNextIntlPlugin();
/** @type {import('next').NextConfig} */
const nextConfig = {};
module.exports = withNextIntl(nextConfig);
```
--------------------------------
### Configure `experimental.messages`
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/plugin.mdx
Setting up `experimental.messages` to define where messages are stored and how they are loaded, including path, format, and precompile options.
```tsx
const withNextIntl = createNextIntlPlugin({
experimental: {
messages: {
path: './messages',
format: 'json',
// Optional
precompile: true
}
}
});
```
--------------------------------
### `next.config.ts` setup
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/getting-started/app-router.mdx
Setup the `next-intl` plugin in `next.config.ts` for TypeScript projects.
```js
import {NextConfig} from 'next';
import createNextIntlPlugin from 'next-intl/plugin';
const nextConfig: NextConfig = {};
const withNextIntl = createNextIntlPlugin();
export default withNextIntl(nextConfig);
```
--------------------------------
### UserProfile.tsx component example
Source: https://github.com/amannn/next-intl/blob/main/README.md
An example of a React component using `useTranslations` from `next-intl` to display localized user profile information.
```jsx
// UserProfile.tsx
import {useTranslations} from 'next-intl';
export default function UserProfile({user}) {
const t = useTranslations('UserProfile');
return (
);
}
```
--------------------------------
### Basic Usage of NextIntlClientProvider
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/configuration.mdx
Shows how to wrap the application with NextIntlClientProvider in a RootLayout.
```tsx
import {NextIntlClientProvider} from 'next-intl';
import {getMessages} from 'next-intl/server';
export default async function RootLayout(/* ... */) {
// ...
return (
...
);
}
```
--------------------------------
### Running ESLint and Prettier from the command line
Source: https://github.com/amannn/next-intl/blob/main/CONTRIBUTORS.md
Commands to manually run ESLint for code issue detection and Prettier for code formatting within a package.
```sh
cd packages/next-intl
pnpm eslint src --fix
pnpm prettier src --write
```
--------------------------------
### Using global formats with `dateTime`
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/dates-times.mdx
Shows how to reference a globally configured format by passing its name as the second argument to `format.dateTime`, with an option to override specific formatting options.
```js
// Use a global format
format.dateTime(dateTime, 'short');
// Optionally override some options
format.dateTime(dateTime, 'short', {year: 'numeric'});
```
--------------------------------
### Using the client-side provider in RootLayout
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/configuration.mdx
Shows how to integrate the `IntlErrorHandlingProvider` within the `NextIntlClientProvider` in `RootLayout`.
```tsx
import {NextIntlClientProvider} from 'next-intl';
import {getLocale} from 'next-intl/server';
import IntlErrorHandlingProvider from './IntlErrorHandlingProvider';
export default async function RootLayout({children}) {
const locale = await getLocale();
return (
{children}
);
}
```
--------------------------------
### messages.json
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/workflows/typescript.mdx
Example messages.json file structure.
```json
{
"About": {
"title": "Hello"
}
}
```
--------------------------------
### Enabling `messages.precompile`
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/plugin.mdx
Configuration for `createNextIntlPlugin` to enable precompilation of messages during the build process, resulting in smaller bundles and faster runtime formatting.
```tsx
const withNextIntl = createNextIntlPlugin({
experimental: {
messages: {
path: './messages',
format: 'json',
precompile: true
}
// ...
}
});
```
--------------------------------
### Strictly-typed ICU arguments examples
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/blog/next-intl-4-0.mdx
Examples demonstrating type inference for ICU message arguments using `t()` and `t.rich()` functions, showing inferred types for various argument types like string, Date, number, union types, and ReactNode for rich text.
```tsx
// "Hello {name}"
t('message', {});
// ^? {name: string}
// "It's {today, date, long}"
t('message', {});
// ^? {today: Date}
// "Page {page, number} out of {total, number}"
t('message', {});
// ^? {page: number, total: number}
// "You have {count, plural, =0 {no followers yet} one {one follower} other {# followers}}."
t('message', {});
// ^? {count: number}
// "Country: {country, select, US {United States} CA {Canada} other {Other}}"
t('message', {});
// ^? {country: 'US' | 'CA' | (string & {})}
// "Please refer to the guidelines."
t.rich('message', {});
// ^? {link: (chunks: ReactNode) => ReactNode}
```
--------------------------------
### UserProfile.tsx
Source: https://github.com/amannn/next-intl/blob/main/packages/use-intl/README.md
Example React component demonstrating `useTranslations` for internationalization.
```jsx
// UserProfile.tsx
import {useTranslations} from 'use-intl';
export default function UserProfile({user}) {
const t = useTranslations('UserProfile');
return (
);
}
```
--------------------------------
### Enabling precompilation
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/blog/precompilation.mdx
Configuration snippet for `next.config.ts` to enable precompilation.
```tsx
import createNextIntlPlugin from 'next-intl/plugin';
const withNextIntl = createNextIntlPlugin({
experimental: {
messages: {
path: './messages',
format: 'json',
// Enable precompilation
precompile: true
}
}
});
export default withNextIntl();
```
--------------------------------
### Minified AST for simple message
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/blog/precompilation.mdx
The minified AST representation of 'Hello {name}!' using arrays with positional entries.
```json
["Hello ", ["name"], "!"]
```
--------------------------------
### Interpolation of arguments
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/translations.mdx
Example of defining a message with a dynamic value and using it with `t()`.
```json
"message": "Hello {name}!"
```
```js
t('message', {name: 'Jane'}); // "Hello Jane!"
```
--------------------------------
### Disable alternateLinks
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/routing/configuration.mdx
Example of disabling `alternateLinks` in `next-intl` routing configuration.
```tsx
import {defineRouting} from 'next-intl/routing';
export const routing = defineRouting({
// ...
alternateLinks: false
});
```
--------------------------------
### Enable `createMessagesDeclaration`
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/plugin.mdx
Configuring `createMessagesDeclaration` to enable type-safe message arguments by pointing to a sample messages file.
```tsx
const withNextIntl = createNextIntlPlugin({
experimental: {
// Provide the path to the messages that you're using in `AppConfig`
createMessagesDeclaration: './messages/en.json'
}
// ...
});
```
--------------------------------
### Turn off localeCookie
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/routing/configuration.mdx
Example demonstrating how to disable the locale cookie entirely.
```tsx
import {defineRouting} from 'next-intl/routing';
export const routing = defineRouting({
// ...
localeCookie: false
});
```
--------------------------------
### Importing precompiled messages
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/plugin.mdx
Example showing how messages are imported when `messages.precompile` is enabled, indicating they will be processed by a Turbo- or Webpack loader.
```tsx
// ✅ Will be pre-processed by a Turbo- or Webpack loader
const messages = (await import(`../../messages/en.json`)).default;
```
--------------------------------
### Basic usage
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/environments/core-library.mdx
Example demonstrating basic usage of `use-intl` in a React app, including `IntlProvider` and `useTranslations` for message translation.
```tsx
import {IntlProvider, useTranslations} from 'use-intl';
// You can get the messages from anywhere you like. You can also
// fetch them from within a component and then render the provider
// along with your app once you have the messages.
const messages = {
App: {
hello: 'Hello {username}!'
}
};
function Root() {
return (
);
}
function App({user}) {
const t = useTranslations('App');
return
{t('hello', {username: user.name})}
;
}
```
--------------------------------
### Usage
Source: https://github.com/amannn/next-intl/blob/main/packages/icu-minify/README.md
Example demonstrating how to compile and format ICU messages using `icu-minify`.
```ts
import compile from 'icu-minify/compile';
import format from 'icu-minify/format';
// At build time
const compiled = compile('Hello {name}!');
// ["Hello ", ["name"], "!"]
console.log(compiled);
// At runtime
format(compiled, 'en', {name: 'World'});
```
--------------------------------
### global.ts
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/workflows/typescript.mdx
Initial example of AppConfig augmentation for Locale, Messages, and Formats.
```tsx
import {routing} from '@/i18n/routing';
import {formats} from '@/i18n/request';
import messages from './messages/en.json';
declare module 'next-intl' {
interface AppConfig {
Locale: (typeof routing.locales)[number];
Messages: typeof messages;
Formats: typeof formats;
}
}
```
--------------------------------
### Example Entry in a Structured JSON Catalog
Source: https://github.com/amannn/next-intl/blob/main/rfcs/001-message-extraction.md
This snippet illustrates a structured JSON format where each message key includes a dedicated 'description' field, providing explicit context for the message 'Right'.
```json
{
"5VpL9Z": {
"description": "Advance to the next slide",
"message": "Right"
}
}
```
--------------------------------
### Customizing the unit
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/dates-times.mdx
Example of using `format.relativeTime` with a specific unit.
```js
import {useFormatter} from 'next-intl';
function Component() {
const format = useFormatter();
const dateTime = new Date('2020-03-20T08:30:00.000Z');
const now = new Date('2020-11-22T10:36:00.000Z');
// Renders "247 days ago"
format.relativeTime(dateTime, {now, unit: 'day'});
}
```
--------------------------------
### Merging split message files
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/configuration.mdx
Example demonstrating how to merge messages from multiple files at runtime if you prefer to split them for organizational reasons.
```tsx
const messages = {
...(await import(`../../messages/${locale}/login.json`)).default,
...(await import(`../../messages/${locale}/dashboard.json`)).default
};
```
--------------------------------
### Exporting global formats
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/workflows/typescript.mdx
Example of exporting 'Formats' from 'next-intl' for type safety.
```ts
import {Formats} from 'next-intl';
export const formats = {
dateTime: {
short: {
day: 'numeric',
month: 'short',
year: 'numeric'
}
},
number: {
precise: {
maximumFractionDigits: 5
}
},
list: {
enumeration: {
style: 'long',
type: 'conjunction'
}
},
displayName: {
region: {
type: 'region'
}
}
} satisfies Formats;
// ...
```
--------------------------------
### New navigation APIs
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/blog/next-intl-3-0.mdx
Migration from old navigation imports to `createSharedPathnamesNavigation` factory function.
```diff
- import Link from 'next-intl/link';
- import {useRouter, usePathname} from 'next-intl/client';
- import {redirect} from 'next-intl/server';
+ import {createSharedPathnamesNavigation} from 'next-intl/navigation';
+
+ const locales = ['en', 'de'] as const;
+ const {Link, useRouter, usePathname, redirect} = createSharedPathnamesNavigation({locales});
```
--------------------------------
### Using type-safe formats
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/workflows/typescript.mdx
Examples of 'useFormatter' with and without type-safe format strings.
```tsx
function Component() {
const format = useFormatter();
// ✖️ Unknown format string
format.dateTime(new Date(), 'unknown');
// ✅ Valid format
format.dateTime(new Date(), 'short');
// ✅ Valid format
format.number(2, 'precise');
// ✅ Valid format
format.list(['HTML', 'CSS', 'JavaScript'], 'enumeration');
// ✅ Valid format
format.displayName('US', 'region');
}
```
--------------------------------
### Using type-safe message arguments
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/workflows/typescript.mdx
Example of 'useTranslations' with and without a type-safe argument.
```tsx
function UserProfile({user}) {
const t = useTranslations('UserProfile');
// ✖️ Missing argument
t('title');
// ✅ Argument is provided
t('title', {firstName: user.firstName});
}
```
--------------------------------
### Using the `useNow` hook
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/dates-times.mdx
Demonstrates the usage of the `useNow` hook to retrieve the current date and time, which is useful for relative time formatting.
```tsx
import {useNow, useFormatter} from 'next-intl';
function FormattedDate({date}) {
const now = useNow();
const format = useFormatter();
format.relativeTime(date, now);
}
```
--------------------------------
### Message with type-safe argument
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/workflows/typescript.mdx
Example JSON message definition with a placeholder for 'firstName'.
```json
{
"UserProfile": {
"title": "Hello {firstName}"
}
}
```
--------------------------------
### Using Global Formats with useFormatter
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/usage/configuration.mdx
This example shows how to use the defined global formats (short date, precise number, enumeration list, region display name) in a component via the useFormatter hook.
```tsx
import {useFormatter} from 'next-intl';
function Component() {
const format = useFormatter();
format.dateTime(new Date('2020-11-20T10:36:01.516Z'), 'short');
format.number(47.414329182, 'precise');
format.list(['HTML', 'CSS', 'JavaScript'], 'enumeration');
format.displayName('US', 'region');
}
```
--------------------------------
### Configuring Localized Pathnames
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/routing/configuration.mdx
This example demonstrates how to use `defineRouting` with the `pathnames` option to map localized external paths to shared internal paths, supporting static, dynamic, and catch-all segments.
```tsx
import {defineRouting} from 'next-intl/routing';
export const routing = defineRouting({
locales: ['en-US', 'en-UK', 'de'],
defaultLocale: 'en-US',
// The `pathnames` object holds pairs of internal and
// external paths. Based on the locale, the external
// paths are rewritten to the shared, internal ones.
pathnames: {
// If all locales use the same pathname, a single
// external path can be used for all locales
'/': '/',
'/blog': '/blog',
// If locales use different paths, you can
// specify the relevant external pathnames
'/services': {
de: '/leistungen'
},
// Encoding of non-ASCII characters is handled
// automatically where relevant
'/about': {
de: '/über-uns'
},
// Dynamic params are supported via square brackets
'/news/[articleSlug]': {
de: '/neuigkeiten/[articleSlug]'
},
// Static pathnames that overlap with dynamic segments
// will be prioritized over the dynamic segment
'/news/just-in': {
de: '/neuigkeiten/aktuell'
},
// Also (optional) catch-all segments are supported
'/categories/[...slug]': {
de: '/kategorien/[...slug]'
}
}
});
```
--------------------------------
### `messages/en.json`
Source: https://github.com/amannn/next-intl/blob/main/docs/src/pages/docs/getting-started/app-router.mdx
Example JSON file for English translations.
```json
{
"HomePage": {
"title": "Hello world!"
}
}
```