ℹ️ If you are running Node.js < 13.1.0, you must also install full-icu and start node with --icu-data-dir=node_modules/full-icu or use NODE_ICU_DATA=node_modules/full-icu.
Setup
1. Configure next.config.js
Please configure i18n as explained in the official Next.js docs.
2. Create a root folder named intl to hold translation files:
intl/ en.json pt.json
The intl/en.json file contains the messages for the en locale, like so:
{ "hello": "Hello World"}
3. Wrap your app with withIntlApp() in pages/_app.js:
// pages/_app.jsimport React from 'react';import App from 'next/app';import { withIntlApp } from '@moxy/next-intl';// The example below dynamically downloads translations from your JSON files,// but you may load them from external sources, such as a CMS.// Please note that the result will be cached on the client-side,// to avoid fetching translations on every page change.const loadLocale = async (locale) => { const module = await import(/* webpackChunkName: "intl-messages" */ `../intl/${locale}.json`); return module.default;};export default withIntlApp(loadLocale)(App);
ℹ️ If you are using getServerSideProps(), then it works the same as the examples that use getStaticProps().
FAQ
How can I use this getIntlProps() in my page's getInitialProps()?
// pages/index.jsimport React from 'react';import { getIntlProps } from '@moxy/next-intl';import { FormattedMessage } from 'react-intl';const Home = () => ( <main> <FormattedMessage id="hello" /> </main>);Home.getInitialProps = async ({ locale }) => ({ ...await getIntlProps(locale),});export default Home;
However, the locale parameter will be undefined in the getInitialProps() function above because Next.js doesn't pass it as of now, but there's an open pull-request to resolve it.
To circumvent this, you must override pages/_app.js like so:
⚠️ Please note that adding getInitialProps() to your App will disable Automatic Static Optimization in pages without Static Generation.
How do I load intl polyfills?
In previous versions of this library, all polyfills were automatically downloaded. This is no longer the case. However, you may load any polyfills and locale data inside the loadLocale() function.