Internationalization (i18n)
Add multi-language support. Learn i18n library.
Internationalization (i18n)
Setup
```bash npm install i18n ```
```javascript const i18n = require('i18n');
i18n.configure({ locales: ['en', 'es', 'fr'], defaultLocale: 'en', directory: __dirname + '/locales' });
app.use(i18n.init); ```
Translation Files
```json // locales/en.json { "welcome": "Welcome", "greeting": "Hello, %s!" }
// locales/es.json { "welcome": "Bienvenido", "greeting": "¡Hola, %s!" } ```
Using Translations
```javascript app.get('/', (req, res) => { res.json({ welcome: req.__('welcome'), greeting: req.__('greeting', 'John') }); });
app.get('/lang/:locale', (req, res) => { res.cookie('language', req.params.locale); req.setLocale(req.params.locale); res.redirect('/'); }); ```
Key Takeaway
Store translations in JSON files. Detect language from headers or cookies. Format dates and numbers by locale.