|
| 1 | +// Polyfill Node with `Intl` that has data for all locales. |
| 2 | +// See: https://formatjs.io/guides/runtime-environments/#server |
| 3 | +const IntlPolyfill = require('intl') |
| 4 | +Intl.NumberFormat = IntlPolyfill.NumberFormat |
| 5 | +Intl.DateTimeFormat = IntlPolyfill.DateTimeFormat |
| 6 | + |
| 7 | +const {readFileSync} = require('fs') |
| 8 | +const {basename} = require('path') |
| 9 | +const {createServer} = require('http') |
| 10 | +const accepts = require('accepts') |
| 11 | +const glob = require('glob') |
| 12 | +const next = require('next') |
| 13 | + |
| 14 | +const dev = process.env.NODE_ENV !== 'production' |
| 15 | +const app = next({dev}) |
| 16 | +const handle = app.getRequestHandler() |
| 17 | + |
| 18 | +// Get the supported languages by looking for translations in the `lang/` dir. |
| 19 | +const languages = glob.sync('./lang/*.json').map((f) => basename(f, '.json')) |
| 20 | + |
| 21 | +// We need to expose React Intl's locale data on the request for the user's |
| 22 | +// locale. This function will also cache the scripts by lang in memory. |
| 23 | +const localeDataCache = new Map() |
| 24 | +const getLocaleDataScript = (locale) => { |
| 25 | + const lang = locale.split('-')[0] |
| 26 | + if (!localeDataCache.has(lang)) { |
| 27 | + const localeDataFile = require.resolve(`react-intl/locale-data/${lang}`) |
| 28 | + const localeDataScript = readFileSync(localeDataFile, 'utf8') |
| 29 | + localeDataCache.set(lang, localeDataScript) |
| 30 | + } |
| 31 | + return localeDataCache.get(lang) |
| 32 | +} |
| 33 | + |
| 34 | +// We need to load and expose the translations on the request for the user's |
| 35 | +// locale. These will only be used in production, in dev the `defaultMessage` in |
| 36 | +// each message description in the source code will be used. |
| 37 | +const getMessages = (locale) => { |
| 38 | + return require(`./lang/${locale}.json`) |
| 39 | +} |
| 40 | + |
| 41 | +app.prepare().then(() => { |
| 42 | + createServer((req, res) => { |
| 43 | + const accept = accepts(req) |
| 44 | + const locale = accept.language(dev ? ['en'] : languages) |
| 45 | + req.locale = locale |
| 46 | + req.localeDataScript = getLocaleDataScript(locale) |
| 47 | + req.messages = dev ? {} : getMessages(locale) |
| 48 | + handle(req, res) |
| 49 | + }).listen(3000, (err) => { |
| 50 | + if (err) throw err |
| 51 | + console.log('> Read on http://localhost:3000') |
| 52 | + }) |
| 53 | +}) |
0 commit comments