
Research
Security News
The Growing Risk of Malicious Browser Extensions
Socket researchers uncover how browser extensions in trusted stores are used to hijack sessions, redirect traffic, and manipulate user behavior.
next-intl
Advanced tools
The next-intl package is designed to provide internationalization (i18n) support for Next.js applications. It allows developers to easily manage translations, handle locale routing, and format dates, numbers, and other content according to locale-specific rules.
Translation Management
This feature allows you to manage translations for different components. The `useTranslations` hook is used to fetch the translations for a specific namespace, and you can then use the translation keys to display localized text.
import { useTranslations } from 'next-intl';
export default function MyComponent() {
const t = useTranslations('MyComponent');
return <p>{t('hello')}</p>;
}
Locale Routing
This feature allows you to handle locale-specific routing in your Next.js application. By using the `useRouter` hook, you can programmatically change the locale and update the URL accordingly.
import { useRouter } from 'next/router';
export default function LocaleSwitcher() {
const router = useRouter();
const changeLocale = (locale) => {
router.push(router.pathname, router.asPath, { locale });
};
return (
<div>
<button onClick={() => changeLocale('en')}>English</button>
<button onClick={() => changeLocale('fr')}>French</button>
</div>
);
}
Date and Number Formatting
This feature allows you to format dates, numbers, and other content according to locale-specific rules. The `useIntl` hook provides methods like `formatDate` to format dates in a localized manner.
import { useIntl } from 'next-intl';
export default function DateFormatter() {
const intl = useIntl();
const formattedDate = intl.formatDate(new Date(), { year: 'numeric', month: 'long', day: 'numeric' });
return <p>{formattedDate}</p>;
}
react-intl is a popular library for internationalizing React applications. It provides similar functionalities to next-intl, such as translation management and date/number formatting. However, it does not offer built-in support for Next.js-specific features like locale routing.
i18next is a powerful internationalization framework that can be used with various JavaScript libraries, including React. It offers extensive features for managing translations, handling pluralization, and more. While it is more versatile, it requires additional setup to integrate with Next.js compared to next-intl.
next-translate is another Next.js-specific internationalization library. It provides similar functionalities to next-intl, such as translation management and locale routing. However, next-translate uses a different approach for loading translations and may have different performance characteristics.
Minimal, but complete solution for managing translations in Next.js apps.
Next.js has built-in support for internationalized routing, but doesn't have an opinion about how you should handle your translations.
This is my attempt at providing a minimal, but complete solution that fills in the missing pieces.
function LatestFollower({user}) {
const t = useTranslations('LatestFollower');
return (
<>
<Text>{t('latestFollower', {username: user.name})}</Text>
<IconButton aria-label={t('followBack')} icon={<FollowIcon />} />
</>
);
}
// en.json
{
"LatestFollower": {
"latestFollower": "{username} started following you",
"followBack": "Follow back"
}
}
react-intl
), this library is a thin wrapper around high-quality APIs for i18n.children
as well as for attributes which expect strings.next-intl
in your project_app.js
import {NextIntlProvider} from 'next-intl';
import NextApp from 'next/app';
export default function App({Component, messages, pageProps}) {
return (
<NextIntlProvider messages={messages}>
<Component {...pageProps} />
</NextIntlProvider>
);
}
App.getInitialProps = async function getInitialProps(context) {
const {locale} = context.router;
// You can get the messages from anywhere you like, but the recommended
// pattern is to put them in JSON files separated by language and read
// the desired one based on the `locale` received from Next.js. You
// can also separate your messages further (e.g. by page) and read
// them based on the current route.
const messages = locale ? require(`messages/${locale}.json`) : undefined
return {...(await NextApp.getInitialProps(context)), messages};
};
// en.json
{
// The recommended approach is to group messages by components.
"Component": {
"static": "Hello",
// See https://formatjs.io/docs/core-concepts/icu-syntax/#simple-argument
"interpolation": "Hello {name}",
// See https://formatjs.io/docs/core-concepts/icu-syntax/#number-type
"number": "{price, number, ::currency/EUR}",
// See https://formatjs.io/docs/intl-messageformat#datetime-skeleton
"date": "{now, date, medium}",
// See https://formatjs.io/docs/core-concepts/icu-syntax/#plural-format
"plural": "You have {numMessages, plural, =0 {no messages} =1 {one message} other {# messages}}.",
// See https://formatjs.io/docs/core-concepts/icu-syntax/#select-format
"select": "{gender, select, male {He} female {She} other {They}} is online.",
// See https://formatjs.io/docs/core-concepts/icu-syntax/#selectordinal-format
"selectordinal": "It's my cat's {year, selectordinal, one {#st} two {#nd} few {#rd} other {#th}} birthday!",
// See https://formatjs.io/docs/core-concepts/icu-syntax/#rich-text-formatting
// and https://formatjs.io/docs/intl-messageformat/#rich-text-support
"richText": "This is <important><very>very</very> important</important>",
// Messages can be used in attributes
"attributeUrl": "https://example.com",
// Use nesting to provide more structure
"nested": {
"label": "Nested"
}
},
// You don't have to group messages by components. Use whatever suits your use case.
"generic": {
"cancel": "Cancel"
},
// You can also put your components behind namespaces.
"fancyComponents": {
"FancyComponent": {
"hello": "Hello"
}
}
}
function Component() {
const t = useTranslations('Component');
return (
<p>{t('static')}</p>
<p>{t('interpolation', {name: 'Jane'})}</p>
<p>{t('number', {price: 31918.231})}</p>
<p>{t('date', {date: new Date('2020-11-20T10:36:01.516Z')})}</p>
<p>{t('plural', {date: new Date('2020-11-20T10:36:01.516Z')})}</p>
<p>{t('selectordinal', {year: 1})}</p>
<p>
{t('richText', {
important: (children: ReactNode) => <b>{children}</b>,
very: (children: ReactNode) => <i>{children}</i>,
})}
</p>
// TypeScript note: You have to cast the attribute to a string, since it
// can potentially return a `ReactNode`: `String(t('attributeUrl'))`
<a href={t('attributeUrl')}>Link</a>
<p>{t('nested.label')}</p>
);
}
function AllTranslations() {
// You can get all translations if you omit the namespace path.
const t = useTranslations();
}
function FancyComponent() {
// Or you can get messages from a nested namespace. The way the library works
// is that there's a static path of the messages that is resolved in the hook
// and should supply all necessary translations for the component. The remaining
// hierarchy can be resolved by passing the respective path to the `t` function.
const t = useTranslations('fancyComponents.FancyComponent');
}
FAQs
Internationalization (i18n) for Next.js
The npm package next-intl receives a total of 569,766 weekly downloads. As such, next-intl popularity was classified as popular.
We found that next-intl demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover how browser extensions in trusted stores are used to hijack sessions, redirect traffic, and manipulate user behavior.
Research
Security News
An in-depth analysis of credential stealers, crypto drainers, cryptojackers, and clipboard hijackers abusing open source package registries to compromise Web3 development environments.
Security News
pnpm 10.12.1 introduces a global virtual store for faster installs and new options for managing dependencies with version catalogs.