import Callout from 'components/Callout'; import {Tab} from 'nextra-theme-docs';
There are a few places in Next.js apps where you might need to apply internationalization outside of React components:
next-intl/server
provides a set of awaitable functions that can be used in these cases.
To internationalize metadata like the page title, you can use functionality from next-intl
in the generateMetadata
function that can be exported from pages and layouts.
import {getTranslations} from 'next-intl/server';
export async function generateMetadata({params: {locale}}) {
const t = await getTranslations({locale, namespace: 'Metadata'});
return {
title: t('title')
};
}
If you need to internationalize content within metadata files, such as an Open Graph image, you can call APIs from next-intl
in the exported function.
import {ImageResponse} from 'next/og';
import {getTranslations} from 'next-intl/server';
export default async function OpenGraphImage({params: {locale}}) {
const t = await getTranslations({locale, namespace: 'OpenGraphImage'});
return new ImageResponse(<div style={{fontSize: 128}}>{t('title')}</div>);
}
You can use next-intl
in Route Handlers too. The locale
can either be received from a search param, a layout segment or by parsing the accept-language
header of the request.
import {NextResponse} from 'next/server';
import {getTranslations} from 'next-intl/server';
export async function GET(request) {
// Example: Receive the `locale` via a search param
const {searchParams} = new URL(request.url);
const locale = searchParams.get('locale');
const t = await getTranslations({locale, namespace: 'Hello'});
return NextResponse.json({title: t('title')});
}