ssr-fatigue-intl

1.1.0-alpha.19 • Public • Published

ssr-fatigue-intl

An Express middleware for setting up react-intl for an server side rendered app.

Installation

$ npm i ssr-fatigue-intl

Usage

const express = require('express')
const intlSSR = require('ssr-fatigue-intl')
const { resolve } = require('path')

const app = express();

app.use(
    intlSSR({
        messagesDir: resolve(__dirname, '..', 'build', 'i18n'),
        defaultLocale = 'en',
        requestLocale = (req, supported) => req.get('x-lang'),
    })

app.get('*', (req, res) => {
    res.send(`
        <!doctype html>
        <html lang=${req.locale}>
            <head>
                <title>Hello</title>
                <script src="react-intl.bundle.js"></script>
            </head>
            <body>
                <script>
                    ${req.localeDataScript}
                </script>
                <script>
                    window.locale = "${req.locale}";
                    window.messages = ${JSON.stringify(req.messages)};

                    if (window.ReactIntlLocaleData) {
                        Object.keys(window.ReactIntlLocaleData).forEach(lang => {
                            ReactIntl.addLocaleData(window.ReactIntlLocaleData[lang]);
                        });
                    }
                </script>

                <!-- ...app contents -->
            </body>
        </html>
    `)
})

The middleware will now scan the messagesDir for supported locales and install a handler, that will determine the requested locale using the requestLocale callback, load the required messages (or using the defaultLocale in case the requested locale is not supported), and decorate all request objects with the locale, messages and, localeDataScript properties.

Readme

Keywords

none

Package Sidebar

Install

npm i ssr-fatigue-intl

Weekly Downloads

0

Version

1.1.0-alpha.19

License

ISC

Unpacked Size

6.6 kB

Total Files

5

Last publish

Collaborators

  • andban