Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intl Polyfill + Next.js SSR application

How can I polyfill intl on a Next.js application? Some Chinese browsers still don't have it, and we use react-intl, which requires Intl.

like image 450
Matthew I Avatar asked Mar 11 '26 08:03

Matthew I


1 Answers

polyfills in Next.js (in general)

Next.js has some examples for polyfills in general:
https://github.com/vercel/next.js/tree/canary/examples/with-polyfills

Next.js recommends to import the needed polyfill(s) inside the <App> component, or in the individual component that uses the polyfill(s).

E.g.:

// /pages/_app.js

import 'polyfill_some_feature';

function MyApp({ Component, pageProps }){
  return <Component { ...pageProps } />
}

export default MyApp

polyfills for the Intl API

formatjs / react-intl provides some polyfills for the Intl API.

The features that you need, like Intl.getCanonicalLocales, Intl.Locale, Intl.PluralRules, ..., have to be imported seperately.

Note that the polyfills depend on each other, so the order in which they are called matters.
E.g. the polyfill for Intl.getCanonicalLocales checks if typeof Intl === 'undefined', but the polyfill for Intl.Locale relies on the existence of Intl already.

Here is one of their examples (this one is for implementing getCanonicalLocales):
https://formatjs.io/docs/polyfills/intl-getcanonicallocales/#dynamic-import--capability-detection

npm i @formatjs/intl-getcanonicallocales
import { shouldPolyfill } from '@formatjs/intl-getcanonicallocales/should-polyfill';

async function polyfill() {
  if( shouldPolyfill() ){
    await import('@formatjs/intl-getcanonicallocales/polyfill');
  }
}
like image 64
kca Avatar answered Mar 13 '26 00:03

kca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!