Installations
npm install @ladjs/i18n
Developer Guide
Typescript
No
Module System
CommonJS
Min. Node Version
>=14
Node Version
16.18.1
NPM Version
8.19.2
Score
95.7
Supply Chain
96.7
Quality
81.5
Maintenance
100
Vulnerability
98.4
License
Releases
Contributors
Unable to fetch Contributors
Languages
JavaScript (99.45%)
Shell (0.55%)
Developer
Download Statistics
Total Downloads
21,860,957
Last Day
19,806
Last Week
97,790
Last Month
396,532
Last Year
5,852,519
GitHub Statistics
10 Stars
168 Commits
9 Forks
5 Watching
5 Branches
10 Contributors
Bundle Size
412.40 kB
Minified
114.98 kB
Minified + Gzipped
Package Meta Information
Latest Version
8.0.3
Package Id
@ladjs/i18n@8.0.3
Unpacked Size
22.76 kB
Size
7.79 kB
File Count
4
NPM Version
8.19.2
Node Version
16.18.1
Total Downloads
Cumulative downloads
Total Downloads
21,860,957
Last day
-5.8%
19,806
Compared to previous day
Last week
-15.4%
97,790
Compared to previous week
Last month
16%
396,532
Compared to previous month
Last year
42.5%
5,852,519
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
11
@ladjs/i18n
i18n wrapper and Koa middleware for Lad
Table of Contents
Install
npm:
1npm install @ladjs/i18n
Usage
1const I18N = require('@ladjs/i18n'); 2const phrases = { 'HELLO': 'Hello there!' }; 3const i18n = new I18N({ phrases }); 4 5// ... 6 7app.use(i18n.middleware); 8app.use(i18n.redirect); 9 10// ... routes go here ... 11 12app.listen();
API
i18n.translate(key, locale, ...args)
Returns translation for phrase key
with the given locale
. Optionally pass additional arguments, e.g. format specifier replacements for use in the phrase. For example if you have a phrase of "An error occurred %s" with a key of "ERROR_OCCURRED", and you use it as such i18n.translate('ERROR_OCCURRED', 'en', 'some error message')
then it would return 'An error occurred some error message
.
i18n.translateError(key, locale, ...args)
Returns the same string as i18n.translate
, but wrapped with a new Error
object with a property no_translate
set to true
.
This is an extremely useful method if you are using koa-better-error-handler
package in the Lad framework – as it will prevent a double translation from occurring.
i18n.middleware(ctx, next)
This middleware uses custom locale detection (in order of priority):
- Check URL (e.g. if
/de
or/de/
then it's ade
locale - as long asde
is a supported locale) - Use the custom function (if provided by the
detectLocale
parameter) for locale detection - Check the
"locale"
cookie value (or whatever thecookie
option is defined as) - Check
Accept-Language
header
It also exposes the following:
ctx.pathWithoutLocale
- thectx.path
without the locale in it (this is used by koa-meta)ctx.request
- with all ofi18n
API methods (e.g.ctx.request.t
,ctx.request.tn
, ...)ctx.locale
- set to the value ofctx.request.locale
(the current user's locale)ctx.state
- with all ofi18n
API methods (e.g.ctx.request.t
,ctx.request.tn
, ...)ctx.state.l
- a shorthand method that accepts a path and returns a localized path (e.g.ctx.state.l('/contact')
will output/en/contact
if the locale is "en")ctx.state.availableLanguages
(Array) - which is useful for adding a dropdown to select from an available languagectx.state.currentLanguage
(String) - the current locale's language in native language using country-language'sgetLanguage
methodctx.translate
(Function) - a helper function for callingi18n.api.t
ori18n.t
to translate a given phrase by its property key name from thephrases
object option (same asi18n.translate
except it throws actx.throw
error using Boom)ctx.translateError
(Function) - same asctx.translate
except it returns an Error object with a propertyno_translate
set totrue
(similar toi18n.translateError
)
If the given locale was not available then it will redirect the user to the detected (or default/fallback) locale.
i18n.redirect(ctx, next)
Inspired by node's language support.
Redirects user with permanent 302
redirect to their detected locale if a valid language was not found for them.
NOTE: As of v1.2.2 we have added a ignoredRedirectGlobs
option you can pass to new I18N({ ... })
which will ignore these paths for locale redirection. This is incredibly useful if you are using authentication providers and the passport
library, e.g. you want to set /auth/github/ok
as the callback URL for GitHub, but a redirect to /en/auth/github/ok
would have occurred, thus causing authentication to fail due to a bad code. In this case, you would set { ignoredRedirectGlobs: [ '/auth/**/*' ] }
or simply [ '/auth/google/ok' ]
. This package uses multimatch internally which supports an Array, therefore you could negate certain paths if needed. See the documentation for multimatch for more insight.
It also sets the cookie locale
for future requests to their detected locale.
This also stores the last_locale
(or whatever you configure the property name to be in the config option lastLocaleField
) for a user via ctx.state.user.save()
.
NOTE: As of v3.0.0 we have added a redirectIgnoresNonGetMethods
(Boolean) option (defaults to true
) which you can pass to new I18N({ ... })
which will ignore non-GET methods on redirection.
Options
We use i18n options per https://github.com/mashpie/i18n-node#list-of-all-configuration-options
Default options are as follows and can be overridden:
1const i18n = new I18N({ 2 phrases: {}, 3 logger: console, 4 directory: resolve('locales'), 5 locales: ['en', 'es', 'zh'], 6 cookie: 'locale', 7 cookieOptions: { 8 // Disable signed cookies in NODE_ENV=test 9 signed: process.env.NODE_ENV !== 'test' 10 }, 11 expiryMs: 31556952000, // one year in ms 12 indent: ' ', 13 defaultLocale: 'en', 14 // `process.env.I18N_SYNC_FILES` 15 syncFiles: true, 16 // `process.env.I18N_AUTO_RELOAD` 17 autoReload: false, 18 // `process.env.I18N_UPDATE_FILES` 19 updateFiles: true, 20 api: { 21 __: 't', 22 __n: 'tn', 23 __l: 'tl', 24 __h: 'th', 25 __mf: 'tmf' 26 }, 27 register: i18n.api, 28 lastLocaleField: 'last_locale', 29 ignoredRedirectGlobs: [], 30 redirectIgnoresNonGetMethods: true, 31 // <https://github.com/ljharb/qs> 32 stringify: { 33 addQueryPrefix: true, 34 format: 'RFC1738', 35 arrayFormat: 'indices' 36 }, 37 redirectTLDS: true, 38 // function that allows using a custom logic for locale detection (can return promise) 39 detectLocale: null 40});
If you wish to bind logDebugFn
, logWarnFn
, and logErrorFn
per i18n options:
1const i18n = new I18N({
2 logDebugFn: console.log,
3 logWarnFn: console.log,
4 logErrorFn: console.log
5});
We recommend to use CabinJS for all your logging needs.
For a list of all available locales see i18n-locales.
Redirect exceptions
If the path has an extension, then it is not redirected.
However if redirectTLDS
option is true
(which is true
by default as of v4.0.0), then if the path basename ends with a valid TLD, then it is redirected.
We came across this missing feature and added it after our discovery through Forward Email.
Contributors
Name | Website |
---|---|
Nick Baugh | http://niftylettuce.com/ |
shadowgate15 | https://github.com/shadowgate15 |
License
MIT © Nick Baugh
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
security policy file detected
Details
- Info: security policy file detected: github.com/ladjs/.github/SECURITY.md:1
- Info: Found linked content: github.com/ladjs/.github/SECURITY.md:1
- Info: Found disclosure, vulnerability, and/or timelines in security policy: github.com/ladjs/.github/SECURITY.md:1
- Info: Found text in security policy: github.com/ladjs/.github/SECURITY.md:1
Reason
Found 2/28 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:18: update your workflow using https://app.stepsecurity.io/secureworkflow/ladjs/i18n/ci.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:20: update your workflow using https://app.stepsecurity.io/secureworkflow/ladjs/i18n/ci.yml/master?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/ci.yml:25
- Info: 0 out of 2 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 1 npmCommand dependencies pinned
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/ci.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 5 are checked with a SAST tool
Score
4.1
/10
Last Scanned on 2025-01-27
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to @ladjs/i18n
@greendeck/ladjs-i18n
i18n wrapper and Koa middleware for Lad
@hishpr/dolor-neque
[![build status](https://img.shields.io/travis/ladjs/@hishpr/dolor-neque.svg)](https://travis-ci.org/ladjs/@hishpr/dolor-neque) [![code coverage](https://img.shields.io/codecov/c/github/ladjs/@hishpr/dolor-neque.svg)](https://codecov.io/gh/ladjs/@hishpr/d