Home > OS >  Export JSON from i18next to the client
Export JSON from i18next to the client

Time:05-11

I'm trying to export a JSON locale file from i18next to a link as an API to use on the client. The problem is that it only exports the locale that is specified in "fallbackLng", which is 'en'. How can I make it detect the locale from the "detection_options" so that the right locale is loaded and exported on the API?

// app.js

var detection_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',
    lookupSession: 'lng',
    lookupPath: 'lng',
    lookupFromPathIndex: 0,

    // cache user language
    caches: false,
}

// i18next configuration
const i18next = require('i18next');
const Backend = require('i18next-fs-backend');
const middleware = require('i18next-http-middleware');
i18next.use(Backend)
    .use(middleware.LanguageDetector)
    .init({
        debug: true, // debug option shows that "zh-hant" is loaded correctly when the Chinese site is accessed.
        detection: detection_options,
        fallbackLng: ['en', 'zh'],
        backend: {
            loadPath(lng, ns) {
                if (lng === 'zh' || lng === 'zh-HK' || lng === 'zh-TW') {
                    return path.join(__dirname, 'locales/zh-hant.json');
                } else if (lng === 'en-US') {
                    return path.join(__dirname, 'locales/en.json');
                }
                return path.join(__dirname, 'locales/{{lng}}.json');
            }
        }
    })
app.use(middleware.handle(i18next));

const localeController = require('../controllers/locale');
app.get('/locale', localeController.getLocale);
// locale.js
exports.getLocale = async (req, res, next) => {
    var i18next = require('i18next');
    res.status(200).json(
        i18next.t('tree', { returnObjects: true })
    )
}

CodePudding user response:

Use the t function from within the request object, like:

https://github.com/i18next/i18next-http-middleware/issues/51#issuecomment-1094851968

  • Related