Skip to content

Instantly share code, notes, and snippets.

@sscovil
Last active June 14, 2020 08:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sscovil/656aef8301b11b370261d36a9b524521 to your computer and use it in GitHub Desktop.
Save sscovil/656aef8301b11b370261d36a9b524521 to your computer and use it in GitHub Desktop.
Node Express server with i18next. Language files go in a `locales/` directory.
{
"home": {
"title": "Hello World!"
}
}
{
"home": {
"title": "Hola Mundo!"
}
}
'use strict';
const express = require('express');
const fs = require('fs');
const i18n = require('i18next');
const i18nFsBackend = require('i18next-node-fs-backend');
const i18nMiddleware = require('i18next-express-middleware');
const app = express();
const port = process.env.PORT || 8080;
i18n
.use(i18nFsBackend)
.use(i18nMiddleware.LanguageDetector)
.init({
backend: {
loadPath: __dirname + '/locales/{{lng}}.json',
addPath: __dirname + '/locales/{{lng}}.missing.json'
},
fallbackLng: 'en',
lowerCaseLng: true,
preload: ['en', 'es'],
saveMissing: true
});
app.use(i18nMiddleware.handle(i18n, {
removeLngFromUrl: false
}));
app.get('/', (req, res) => {
res.send(req.t('home.title'));
});
module.exports = app.listen(port, (err) => {
if (err) {
console.log(err);
process.exit(1);
} else {
console.log(`Server is listening on port ${port}`);
}
});
{
"name": "i18n-server",
"version": "1.0.0",
"description": "Node Express server with i18next.",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"author": "Shaun Scovil <sscovil@gmail.com>",
"license": "ISC",
"dependencies": {
"express": "4.15.2",
"i18next": "8.2.1",
"i18next-express-middleware": "1.0.5",
"i18next-node-fs-backend": "1.0.0"
}
}
@repiatx
Copy link

repiatx commented Mar 30, 2020

Thx bro :)

@valikonen
Copy link

Was better if you add complete example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment