• Stars
    star
    148
  • Rank 249,983 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 4 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

i18next-http-middleware is a middleware to be used with Node.js web frameworks like express or Fastify and also for Deno.

Introduction

Actions Actions deno Travis npm version

This is a middleware to be used with Node.js web frameworks like express or Fastify and also for Deno.

It's based on the deprecated i18next-express-middleware and can be used as a drop-in replacement. It's not bound to a specific http framework anymore.

Advice:

To get started with server side internationalization, you may also have a look at this blog post also using using i18next-http-middleware.

Getting started

# npm package
$ npm install i18next-http-middleware

wire up i18next to request object

var i18next = require('i18next')
var middleware = require('i18next-http-middleware')
var express = require('express')

i18next.use(middleware.LanguageDetector).init({
  preload: ['en', 'de', 'it'],
  ...otherOptions
})

var app = express()
app.use(
  middleware.handle(i18next, {
    ignoreRoutes: ['/foo'], // or function(req, res, options, i18next) { /* return true to ignore */ }
    removeLngFromUrl: false // removes the language from the url when language detected in path
  })
)

// in your request handler
app.get('myRoute', (req, res) => {
  var lng = req.language // 'de-CH'
  var lngs = req.languages // ['de-CH', 'de', 'en']
  req.i18n.changeLanguage('en') // will not load that!!! assert it was preloaded

  var exists = req.i18n.exists('myKey')
  var translation = req.t('myKey')
})

// in your views, eg. in pug (ex. jade)
div = t('myKey')

Fastify usage

var i18next = require('i18next')
var middleware = require('i18next-http-middleware')
var fastify = require('fastify')

i18next.use(middleware.LanguageDetector).init({
  preload: ['en', 'de', 'it'],
  ...otherOptions
})

var app = fastify()
app.register(i18nextMiddleware.plugin, {
  i18next,
  ignoreRoutes: ['/foo'] // or function(req, res, options, i18next) { /* return true to ignore */ }
})
// or
// app.addHook('preHandler', i18nextMiddleware.handle(i18next, {
//   ignoreRoutes: ['/foo'] // or function(req, res, options, i18next) { /* return true to ignore */ }
// }))

// in your request handler
app.get('myRoute', (request, reply) => {
  var lng = request.language // 'de-CH'
  var lngs = v.languages // ['de-CH', 'de', 'en']
  request.i18n.changeLanguage('en') // will not load that!!! assert it was preloaded

  var exists = request.i18n.exists('myKey')
  var translation = request.t('myKey')
})

Hapi usage

const i18next = require('i18next')
const middleware = require('i18next-http-middleware')
const Hapi = require('@hapi/hapi')

i18next.use(middleware.LanguageDetector).init({
  preload: ['en', 'de', 'it'],
  ...otherOptions
})

const server = Hapi.server({
  port: port,
  host: '0.0.0.0',

await server.register({
  plugin: i18nextMiddleware.hapiPlugin,
  options: {
    i18next,
    ignoreRoutes: ['/foo'] // or function(req, res, options, i18next) { /* return true to ignore
  }
})

// in your request handler
server.route({
  method: 'GET',
  path: '/myRoute',
  handler: (request, h) => {
    var lng = request.language // 'de-CH'
    var lngs = v.languages // ['de-CH', 'de', 'en']
    request.i18n.changeLanguage('en') // will not load that!!! assert it was preloaded

    var exists = request.i18n.exists('myKey')
    var translation = request.t('myKey')
  }
})

Deno usage

abc

import i18next from 'https://deno.land/x/i18next/index.js'
import Backend from 'https://cdn.jsdelivr.net/gh/i18next/i18next-fs-backend/index.js'
import i18nextMiddleware from 'https://deno.land/x/i18next_http_middleware/index.js'
import { Application } from 'https://deno.land/x/abc/mod.ts'
import { config } from 'https://deno.land/x/dotenv/dotenv.ts'

i18next
  .use(Backend)
  .use(i18nextMiddleware.LanguageDetector)
  .init({
    // debug: true,
    backend: {
      // eslint-disable-next-line no-path-concat
      loadPath: 'locales/{{lng}}/{{ns}}.json',
      // eslint-disable-next-line no-path-concat
      addPath: 'locales/{{lng}}/{{ns}}.missing.json'
    },
    fallbackLng: 'en',
    preload: ['en', 'de']
  })

const port = config.PORT || 8080
const app = new Application()
const handle = i18nextMiddleware.handle(i18next)
app.use((next) => (c) => {
  handle(c.request, c.response, () => {})
  return next(c)
})
app.get('/', (c) => c.request.t('home.title'))
await app.start({ port })

ServestJS

import i18next from 'https://deno.land/x/i18next/index.js'
import Backend from 'https://cdn.jsdelivr.net/gh/i18next/i18next-fs-backend/index.js'
import i18nextMiddleware from 'https://deno.land/x/i18next_http_middleware/index.js'
import { createApp } from 'https://servestjs.org/@v1.0.0-rc2/mod.ts'
import { config } from 'https://deno.land/x/dotenv/dotenv.ts'

i18next
  .use(Backend)
  .use(i18nextMiddleware.LanguageDetector)
  .init({
    // debug: true,
    backend: {
      // eslint-disable-next-line no-path-concat
      loadPath: 'locales/{{lng}}/{{ns}}.json',
      // eslint-disable-next-line no-path-concat
      addPath: 'locales/{{lng}}/{{ns}}.missing.json'
    },
    fallbackLng: 'en',
    preload: ['en', 'de']
  })

const port = config.PORT || 8080
const app = createApp()
app.use(i18nextMiddleware.handle(i18next))
app.get('/', async (req) => {
  await req.respond({
    status: 200,
    headers: new Headers({
      'content-type': 'text/plain'
    }),
    body: req.t('home.title')
  })
})
await app.listen({ port })

add routes

// missing keys make sure the body is parsed (i.e. with [body-parser](https://github.com/expressjs/body-parser#bodyparserjsonoptions))
app.post('/locales/add/:lng/:ns', middleware.missingKeyHandler(i18next))
// addPath for client: http://localhost:8080/locales/add/{{lng}}/{{ns}}

// multiload backend route
app.get('/locales/resources.json', middleware.getResourcesHandler(i18next))
// can be used like:
// GET /locales/resources.json
// GET /locales/resources.json?lng=en
// GET /locales/resources.json?lng=en&ns=translation

// serve translations:
app.use('/locales', express.static('locales'))
// GET /locales/en/translation.json
// loadPath for client: http://localhost:8080/locales/{{lng}}/{{ns}}.json

// or instead of static
app.get('/locales/:lng/:ns', middleware.getResourcesHandler(i18next))
// GET /locales/en/translation
// loadPath for client: http://localhost:8080/locales/{{lng}}/{{ns}}

app.get('/locales/:lng/:ns', middleware.getResourcesHandler(i18next, {
  maxAge: 60 * 60 * 24 * 30, // adds appropriate cache header if cache option is passed or NODE_ENV === 'production', defaults to 30 days
  cache: true // defaults to false
}))

add localized routes

You can add your routes directly to the express app

var express = require('express'),
  app = express(),
  i18next = require('i18next'),
  FilesystemBackend = require('i18next-fs-backend'),
  i18nextMiddleware = require('i18next-http-middleware'),
  port = 3000

i18next
  .use(i18nextMiddleware.LanguageDetector)
  .use(FilesystemBackend)
  .init({ preload: ['en', 'de', 'it'], ...otherOptions }, () => {
    i18nextMiddleware.addRoute(
      i18next,
      '/:lng/key-to-translate',
      ['en', 'de', 'it'],
      app,
      'get',
      (req, res) => {
        //endpoint function
      }
    )
  })
app.use(i18nextMiddleware.handle(i18next))
app.listen(port, () => {
  console.log('Server listening on port', port)
})

or to an express router

var express = require('express'),
  app = express(),
  i18next = require('i18next'),
  FilesystemBackend = require('i18next-fs-backend'),
  i18nextMiddleware = require('i18next-http-middleware'),
  router = require('express').Router(),
  port = 3000

i18next
  .use(i18nextMiddleware.LanguageDetector)
  .use(FilesystemBackend)
  .init({ preload: ['en', 'de', 'it'], ...otherOptions }, () => {
    i18nextMiddleware.addRoute(
      i18next,
      '/:lng/key-to-translate',
      ['en', 'de', 'it'],
      router,
      'get',
      (req, res) => {
        //endpoint function
      }
    )
    app.use('/', router)
  })
app.use(i18nextMiddleware.handle(i18next))
app.listen(port, () => {
  console.log('Server listening on port', port)
})

custom http server

Define your own functions to handle your custom request or response

middleware.handle(i18next, {
  getPath: (req) => req.path,
  getUrl: (req) => req.url,
  setUrl: (req, url) => (req.url = url),
  getQuery: (req) => req.query,
  getParams: (req) => req.params,
  getBody: (req) => req.body,
  setHeader: (res, name, value) => res.setHeader(name, value),
  setContentType: (res, type) => res.contentType(type),
  setStatus: (res, code) => res.status(code),
  send: (res, body) => res.send(body)
})

language detection

Detects user language from current request. Comes with support for:

  • path
  • cookie
  • header
  • querystring
  • session

Based on the i18next language detection handling: https://www.i18next.com/misc/creating-own-plugins#languagedetector

Wiring up:

var i18next = require('i18next')
var middleware = require('i18next-http-middleware')

i18next.use(middleware.LanguageDetector).init(i18nextOptions)

As with all modules you can either pass the constructor function (class) to the i18next.use or a concrete instance.

Detector Options

{
  // order and from where user language should be detected
  order: [/*'path', 'session', */ 'querystring', 'cookie', 'header'],

  // keys or params to lookup language from
  lookupQuerystring: 'lng',
  lookupCookie: 'i18next',
  lookupHeader: 'accept-language',
  lookupHeaderRegex: /(([a-z]{2})-?([A-Z]{2})?)\s*;?\s*(q=([0-9.]+))?/gi,
  lookupSession: 'lng',
  lookupPath: 'lng',
  lookupFromPathIndex: 0,

  // cache user language, you can define if an how the detected language should be "saved" => 'cookie' and/or 'session'
  caches: false, // ['cookie']

  ignoreCase: true, // ignore case of detected language

  // optional expire and domain for set cookie
  cookieExpirationDate: new Date(),
  cookieDomain: 'myDomain',
  cookiePath: '/my/path',
  cookieSecure: true, // if need secure cookie
  cookieSameSite: 'strict' // 'strict', 'lax' or 'none'
}

Options can be passed in:

preferred - by setting options.detection in i18next.init:

var i18next = require('i18next')
var middleware = require('i18next-http-middleware')

i18next.use(middleware.LanguageDetector).init({
  detection: options
})

on construction:

var middleware = require('i18next-http-middleware')
var lngDetector = new middleware.LanguageDetector(null, options)

via calling init:

var middleware = require('i18next-http-middleware')

var lngDetector = new middleware.LanguageDetector()
lngDetector.init(options)

Adding own detection functionality

interface

module.exports = {
  name: 'myDetectorsName',

  lookup: function (req, res, options) {
    // options -> are passed in options
    return 'en'
  },

  cacheUserLanguage: function (req, res, lng, options) {
    // options -> are passed in options
    // lng -> current language, will be called after init and on changeLanguage
    // store it
  }
}

adding it

var i18next = require('i18next')
var middleware = require('i18next-http-middleware')

var lngDetector = new middleware.LanguageDetector()
lngDetector.addDetector(myDetector)

i18next.use(lngDetector).init({
  detection: options
})

Don't forget: You have to add the name of your detector (myDetectorsName in this case) to the order array in your options object. Without that, your detector won't be used. See the Detector Options section for more.


Gold Sponsors

More Repositories

1

react-i18next

Internationalization for react done right. Using the i18next i18n ecosystem.
JavaScript
9,188
star
2

i18next

i18next: learn once - translate everywhere
JavaScript
7,594
star
3

next-i18next

The easiest way to translate your NextJs apps.
TypeScript
5,429
star
4

i18next-browser-languageDetector

language detector used in browser environment for i18next
JavaScript
842
star
5

i18next-scanner

Scan your code, extract translation keys/values, and merge them into i18n resource files.
JavaScript
554
star
6

i18next-parser

Parse your code to extract translation keys/values and manage your catalog files
JavaScript
468
star
7

i18next-http-backend

i18next-http-backend is a backend layer for i18next using in Node.js, in the browser and for Deno.
JavaScript
434
star
8

i18next-node

[deprecated] can be replaced with v2 of i18next
JavaScript
261
star
9

i18next-xhr-backend

[deprecated] can be replaced with i18next-http-backend
JavaScript
254
star
10

i18next-express-middleware

[deprecated] can be replaced with i18next-http-middleware
JavaScript
207
star
11

i18next-gettext-converter

converts gettext .mo or .po to 18next json format and vice versa
JavaScript
193
star
12

next-app-dir-i18next-example

Next.js 13/14 app directory feature in combination with i18next
JavaScript
169
star
13

jquery-i18next

jQuery-i18next is a jQuery based Javascript internationalization library on top of i18next. It helps you to easily internationalize your web applications.
HTML
168
star
14

i18next-gitbook

HTML
163
star
15

ng-i18next

translation for AngularJS using i18next
JavaScript
161
star
16

next-app-dir-i18next-example-ts

Next.js 13/14 app directory feature in combination with i18next
TypeScript
105
star
17

react-i18next-gitbook

CSS
95
star
18

i18next-fs-backend

i18next-fs-backend is a backend layer for i18next using in Node.js and for Deno to load translations from the filesystem.
JavaScript
92
star
19

i18next-localstorage-backend

This is a i18next cache layer to be used in the browser. It will load and cache resources from localStorage and can be used in combination with the chained backend.
JavaScript
83
star
20

i18next-icu

i18nFormat plugin to use ICU format with i18next
JavaScript
79
star
21

i18next-vue

Internationalization for Vue 2 & 3 using the i18next ecosystem
TypeScript
70
star
22

i18next-node-fs-backend

[deprecated] can be replaced with i18next-fs-backend
JavaScript
65
star
23

i18next-chained-backend

An i18next backend to chain multiple backends (add fallbacks, caches, ...)
JavaScript
64
star
24

i18nextify

enables localization of any page with zero effort.
JavaScript
61
star
25

next-language-detector

This package helps to handle language detection in next.js when using static servers only.
JavaScript
57
star
26

i18next-resources-to-backend

This package helps to transform resources to an i18next backend
JavaScript
53
star
27

i18next-android

i18next internationalization library for Android
Java
42
star
28

i18next-webtranslate

[deprecated] Translation User Interface for i18next - successor locize.com
JavaScript
41
star
29

i18next-resources-for-ts

This package helps to transform resources to be used in a typesafe i18next project.
JavaScript
31
star
30

i18next-ios

i18next internationalization library for iOS
Objective-C
29
star
31

i18next-sprintf-postProcessor

sprintf post processor for i18next
JavaScript
28
star
32

i18next-localStorage-cache

[deprecated] caching layer for i18next using browsers localStorage
JavaScript
25
star
33

i18next-intervalPlural-postProcessor

post processor for i18next enabling interval plurals
JavaScript
25
star
34

i18next-fluent

i18nFormat plugin to use mozilla fluent format with i18next
JavaScript
22
star
35

i18next-multiload-backend-adapter

This is a i18next backend to enable another backend's multiload behaviour of loading multiple lng-ns combinations with one request.
JavaScript
16
star
36

next-app-dir-i18next-no-locale-path-example

JavaScript
15
star
37

i18next-emoji-postprocessor

This is a postProcessor plugin for i18next using in Node.js and in the browser that replaces all words with emojis.
JavaScript
10
star
38

i18next-v4-format-converter

This package helps to convert old i18next translation resources to the new i18next v4 json format.
JavaScript
9
star
39

i18next.com

[obsolete] was replaced by i18next-gitbook! i18next.com website
JavaScript
7
star
40

grunt-i18next

Bundle language resource files for i18next.
JavaScript
6
star
41

i18next-translation-parser

parses i18next translations to AST
JavaScript
6
star
42

i18next-node-remote-backend

[deprecated] can be replaced with i18next-http-backend
JavaScript
6
star
43

omi-i18n

omi-i18n solution for omi.js using i18next ecosystem
JavaScript
5
star
44

i18next-fluent-backend

i18next backend to load fluent formatted .ftl files via xhr
JavaScript
4
star
45

i18next-polyglot

i18nFormat plugin to use airbnb/polyglot.js format with i18next
JavaScript
4
star
46

i18next-cli-app-example

i18next in a cli app
JavaScript
2
star
47

bs-react-i18next

Bucklescript + ReasonReact binding for react-i18next components.
OCaml
1
star