Security News
Input Validation Vulnerabilities Dominate MITRE's 2024 CWE Top 25 List
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
express-rest-i18n
Advanced tools
Dead simple i18n middleware for Express REST APIs.
Easy usage, no dependencies, simple integration and well tested.
npm install express-rest-i18n
You can also create a module that exports you instance, if you prefer.
const i18nCreate = require('express-rest-i18n');
const i18n = i18nCreate({
defaultLocale: 'en',
warn: false, // optional
allowFallback: true, // optional
messages: {
'en': {
hello: 'Hello',
nested: {
world: 'World'
}
},
'pt-br': {
hello: 'Olá',
nested: {
world: 'Mundo'
}
}
},
});
const express = require('express');
const app = express();
app.use(i18n.middleware);
Attention: if are using body-parser
, add the i18n middleware AFTER the body parser addition, so the i18n will recognize it.
app.get('*', (req, res) => {
const helloWorld = `${res.i18n.t('hello')} ${res.i18n.t('nested.world')}`;
res.status(200).send(helloWorld);
});
The i18n
instance contains the t()
method which does the translations for you. When you add the i18n.middleware
to your express, the t()
method is exposed on your req
and res
objects. This is the t()
method signature
function t(keypath: string, locale?:string) : str | any
When using the t() method on your i18n instance:
i18n.t('hello'); // will output "Hello"
i18n.t('hello', 'pt-br'); // will outout "Olá"
When inside the express (as a middleware), the t() method is exposed on your req and res objects. The locale is automatically infered from the request, or the defaultLocale will be used:
app.get('*', (req, res) => {
/*
if the request doesnt specify any locale, the const hello will be "Hello",
if specify a locale, the result will be in the given local, for pt-br
for example, would be "Olá", for a non-existent locale or if the given locale
doesnt contains the "hello" key, it will be fallbacked to the defaultLocale
*/
const hello = res.i18n.t('hello');
res.status(200).send(hello); // will output hello
});
You can also force a locale even using it as a middleware
app.get('*', (req, res) => {
const hello = res.i18n.t('hello', 'pt-br'); // will return "Olá" no matter the request locale
res.status(200).send(hello);
});
You can specify nested paths to translate from your messages
i18n.t('nested.world'); // will output "World"
When a key is not found on the given or default locale, or the argument passed is not a string, the t() method will return the argument untouched:
i18n.t('non.existing.key'); // will output "non.existing.key"
i18n.t({ test: "test"}); // will output object { test: "test"}
Your messages
are passed to the i18n instance
using the messages
key on options.
A common approach is to put the messages in a separated file. In the messages object,
the first key level is the locale, and the nested keys are the messages. Example:
// messages.js file
module.exports = {
'en': { // locale
hello: 'Hello',
nested: {
world: 'World'
}
},
'pt-br': { // locale
hello: 'Olá',
nested: {
world: 'Mundo'
}
}
}
Then on your instance creation:
const message = require('./messages.js');
const i18n = i18nCreate({
messages: messages,
defaultLocale: 'pt-br'
});
If you dont pass any locale, your defaultLocale
will be used as the translation language. Anyway, you can specify a locale to your API in 3 different ways. When specifying the locale on your request you dont need to do anything server-side, the i18n.t()
will automatically handle the response using the locale passed via request.
You can pass the API language (locale) from the request headers, just set the application-language
on headers passing the desired locale, in the example below, we are saying that we want the results in "en" language:
fetch('http://api-address.com/', {
headers: { 'application-language': 'en' }
})
.then(response => { ... })
.catch(err => { ... });
You can pass the desired locale via address query. In the example below you will be setting the results to "en" language:
fetch('http://api-address.com/?locale=en')
.then(response => { ... })
.catch(err => { ... });
You can also pass the desired locale on your request body. You must be using body-parser
on your express to use this option:
fetch('http://api-address.com/', {
method: 'post',
body: JSON.stringify({ locale: 'en' })
})
.then(response => { ... })
.catch(err => { ... });
The defaultLocale
will be used as a fallback when you:
messages
key
to be translated which doesn't exists on the current locale (not the default)You can pass the following options to the instance:
const i18n = i18nCreate({
defaultLocale: 'pt-br', // required, set the default locale
warn: false, // optional // show warns on fallbacks and errors
allowFallback: true, // if no fallback
messages: {}, // your locales and messages
});
Ask for translations. Ex:
i18n.t('hello'); // will output "Hello"
Return the current locale being used on instance
i18n.locale(); // will output "en"
Overrides options on the fly. Example for change default locale and warn levels:
i18n.setOptions({
warn: true,
defaultLocale: 'pt-br',
});
The sources are in src
folder. Start with npm install
, then:
npm run build
npm run test
Express Rest i18n by Felippe Regazio
FAQs
Dead simple i18n middleware for Express REST APIs
The npm package express-rest-i18n receives a total of 21 weekly downloads. As such, express-rest-i18n popularity was classified as not popular.
We found that express-rest-i18n demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.