Search code examples
webpacknext.jsserver-side-renderingreact-intl

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.


Solution

  • 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');
      }
    }