The language is being detected, but the translation feature is not functioning properly with i18n

I've configured the i18n middleware in my Express Node js server as follows:

// server.js
import i18nMiddleware from 'i18next-express-middleware';
import i18n from 'i18next';
import Backend from 'i18next-node-fs-backend';
import { LanguageDetector } from 'i18next-express-middleware';

i18n
.use(Backend)
.use(LanguageDetector)
.init({
    whitelist: ['en', 'my'],
    fallbackLng: 'en',

    // have a common namespace used around the full app
    ns: ['common'],
    defaultNS: 'common',

    debug: false,

    backend: {
        loadPath: './locales/{{lng}}/{{ns}}.json',
        // jsonIndent: 2
    }
});

app.use(i18nMiddleware.handle(i18n))

This is the translation testing file:

// test.js
import i18next from "i18next";

const test = (req, res) =>{
    const t = req.i18n.t.bind(i18next);

    console.log(req.i18n.language) // language set correctly :)
    console.log(t('title')) // translation not working :(
}

The translation for title in English is title and in Malaysian, it's tajuk

According to the express middleware documentation, I'm sending my as the accept-language header, and console.log(req.i18n.language) is correctly displaying it.

However, console.log(t('title')) still shows title instead of tajuk

Answer №1

At first glance, this solution may seem crazy, but it actually worked:

const translate = req.translate;
console.log(translate.get('title'))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Typescript error: Cannot access property "status" on type "never".ts(2339)

Currently, I have a method that utilizes nextjs/auth to sign in with credentials from a form. However, I am encountering a type checking error Object is possibly 'undefined'.ts(2532) const doStuff = async (values: any) => { const result: S ...

I have a JavaScript code stored as a string that I need to transform into plain JavaScript

If I have a variable in string format, for example suppose there is a JavaScript code inside it: var string="function myFunction(a,b){return a*b;}"; I want to convert this into pure JavaScript code format like so: function myFunction(a, b) { return ...

How can I resolve the problem of transferring retrieved data to a POST form?

When it comes to the form, its purpose is to send data fetched from another API along with an additional note. The fetched data was successfully received, as I confirmed by logging it to the console. It seems that the form is able to send both the fetche ...

Safari IOS experiencing issue with element disappearing unexpectedly when input is focused

I am facing a situation similar to the one discussed in the question (iOS 8.3 fixed HTML element disappears on input focus), but my problem differs slightly. My chatbox iframe is embedded within a scrollable parent, and when the iframe is activated, it exp ...

Creating default selection in angular 6 using formControlName in a dropdown menu

I am currently learning MEAN stack with Angular 6 and I have a question regarding selecting the default value in a dropdown using formControlName. When updating a form, I need to have a default value in my dropdown list but I'm only getting a blank op ...

Iterating through elements within a Div will retrieve the initial element exclusively

Is there a way to loop through all elements within the MainDiv Div in order to retrieve their values? Currently, I am only able to retrieve the value of the first element. <div id="MainDiv"> <input type="text" id="MyText"value="Text1" /> ...

An array containing numerous "case" triggers

var message = "hello [[xxx]] bye [[ZZZ]]" var result, re = /\[\[(.*?)\]\]/g; while ((result = re.exec(message)) != null) { switch (result[1].toLowerCase()) { case "xxx": console.log("found xxx"); br ...

A step-by-step guide for setting up SSL on a React Frontend, Nodejs Backend, and Custom Domain using Heroku

Important details about my current setup I am currently in the process of building a web application using React and a NodeJS API that supplies data for this web application. These two components are hosted separately on heroku.com. Additionally, I have o ...

The onChange function is not triggered when the dropdown menu consists of only one item

I am facing an issue with my dynamically populated dropdown menu. When the dropdown contains only one element, the onChange() function of my select tag does not work as expected. It functions perfectly fine when there are multiple elements present. How c ...

Why is npm generating such a large amount of files?

After reviewing this section of the PhpStorm manual, I believe I found a workaround for adding a development tool: If a tool is solely for documentation or testing purposes and not necessary for application reusability, it's best to exclude it from f ...

Utilizing AND and OR operators in Node.js for retrieving data

Hey there! I could use some assistance with the following issue: Objective: I am looking to filter data based on department content. My goal is to retrieve data from MongoDB based on your job title or department. For instance, if I belong to the Email Tea ...

Leveraging clustering in an Express.js application

As I delve into my first node project, I am gaining hands-on experience and have managed to set up a basic server. However, with the app expected to receive heavy traffic, implementing cluster seems like a logical step. Despite piecing together code snippe ...

How to align an image in the center of a circular flex container

I'm facing an issue in my Angular project where I have the following code snippet: onChange(event: any) { var reader = new FileReader(); reader.onload = (event: any) => { this.url = event.target.result; }; reader.readAsData ...

Executing a function within a worker thread in Node.js

This is the worker I am using: const Worker = require('worker_threads'); const worker = new Worker("function hello () { console.log('hello world');}", { eval: true }) worker.hello() // this is incorrect I want to invoke the hello() fu ...

apply a course to the designated element

Alright, I have this piece of code that deals with session and page requests. // Let's start our session session_start(); // Now let's check if there is a page request if (isset($_GET['page'])) { // If there is a requested page, we ...

How can you retrieve command line variables within your code by utilizing npm script in webpack?

I'm trying to access command line parameters from an npm script in my "constants.js" file. While I have been able to access parameters in the webpack.config.js file using process.env, it seems to be undefined in my app source files. The scenario con ...

There seems to be an issue: A callback function is necessary for Route.post()

C:\Users\I ..\OneDrive\ecom-sql\node_modules\express\lib\router\route.js:202 throw new Error(msg); ^ Error: Route.post() requires a callback function but got a [object Undefined] at Route.&l ...

Is there a way to create a list of languages spoken using Angular?

I am in search of a solution to create a <select> that contains all the language names from around the world. The challenge is, I need this list to be available in multiple languages as well. Currently, I am working with Angular 8 and ngx-translate, ...

What is the best way to make changes to a Meteor package from Atmosphere that is not available on GitHub?

I'm currently working on implementing Twitter functionality in my app, specifically focusing on using "Application-Only Authentication." This method requires only the Twitter application credentials to perform GET requests, such as random tweet search ...

The Node.js callback is executed before the entire function has finished executing

const fileSystem = require('fs'); const filePath = require('path'); module.exports.getFiles = function(filepath, callback) { let files = []; fileSystem.exists(filepath, function(exists){ if(exists){ fileSy ...