Utilize i18next Localization in a Function Instead of App.js

Currently, I am utilizing ExpressJS and i18next.

Within app.js

var express = require('express')
  , i18n = require('i18next')
  , user = require('./routes/user')
...
//internationalization
i18n.init({
  lng: 'en-US',
  saveMissing: true,
  debug: true
});
...  
app.use(i18n.handle);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
...
i18n.registerAppHelper(app);
...
app.post('/users/save', user.save);

You can easily access translations in jade:

t('app.title')

But how can you access the translation in routes.user.js

exports.save = function(req, res){
    //t('app.title')
}

Answer №1

Whenever you need to access t in your route handlers, simply refer to it as res.locals.t. This method is compatible with both Express 3 and 2.

Answer №2

i18next-express-middleware allows for easy access to the translation function using req.i18n.t or simply req.t. Additionally, the function can also be found under res.locals.t for template accessibility.

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

"Attempting to access a variable defined in one pipe results in it being undefined in a

Currently, I am utilizing gulp to process pages for a website. Some of these pages are PHP files, however, after going through the template engine, they all end up with a .html file extension. My intention is to add a property to each file indicating if it ...

Guide to making a batch file in Windows 10 that opens a Node app stored locally

I am working on creating a .bat file to run two separate applications locally on my Windows 10 operating system - a React app and the Strapi service it depends on. Here is what I have tried so far: echo Starting React C:\Windows\System32\cm ...

Incorporating a for loop, ExpressJS and Mongoose repeatedly utilize the create method to generate

When users input tags separated by commas on my website, ExpressJS is supposed to search for those tags and create objects if they don't already exist. Currently, I am using a for loop to iterate through an array of tags, but only one object is being ...

What is the best way to trigger an email from NodeMailer only upon confirmation of payment?

After confirming the payment and verifying it, I have set up NodeMailer to send an email to a specific email address obtained from req.body.email. However, I am encountering an error where the payment is processed without the email being sent. We are util ...

Encountered Error : Uncaught Rejection (SyntaxError): JSON data ended unexpectedly

I'm facing a challenge with fetching in React as I attempt to connect my Node API running on port 8000. Everything was working smoothly initially until I introduced a fetch for another function, resulting in the following error message: const API_URL ...

Is it possible to use webpack with multiple instances of express?

I am working on an application where multiple express servers are created, each serving as endpoints simultaneously. Each server serves a react app that depends on the API from its corresponding express server. I need to figure out how to use webpack to ...

Any suggestions on how to handle outdated npm modules when using express generator?

Working on my express website and encountered some warnings: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d575c59587d0c130c0c130d">[email protected]</a>: Jade is now pug, please update to th ...

Eliminate embedded document elements using $pull operation

Trying to implement a functionality in ExpressJS and Mongoose that involves removing items from subdocuments. Currently, only the first item is getting removed instead of all sub items. The goal is to delete "subitem 2" from the messages Array. Here is th ...

What situations warrant the use of unescaped !{} in pug for string interpolation?

Is there a practical application for utilizing !{} - string interpolation in an unescaped format, despite the potential risks associated with its use? I have reviewed the information provided at these sources: Using !{ } and #{ } interpolation in a jade ...

Encountering an error while trying to run a Next.js application on Linux Mint

View the error screenshot After creating a new Next.js app with npx create-next-app, I ran npm run dev and encountered the following error message ...

Encountering issues while attempting to run Linux commands from NodeJs

While working with NodeJS to execute Linux commands, I encountered an issue. When attempting to execute a command that generates a file called "myWaveFile.wav" and this file already exists, it should prompt the user whether they want to overwrite it or n ...

`To incorporate a collection within an array of objects in MongoDB, follow these steps:`

I have a collection named notifications containing documents like this: [ { _id: 4f6a686ad4821115c0b4a721, title: "title 1" comments: [ { comment: 'test 1', client_id: '1664158 ...

Isolating Express.js Requests for Enhanced Security

In my Node.js Express app, multiple users send requests to the server for various actions such as earning points, changing email addresses, and interacting with other users. My server code utilizes several setTimeouts, leading me to question whether diffe ...

Experiencing a 403 Error while using request-promise to extract price data from a website

My current challenge involves using request-promise to scrape the price of an item from Asos.com. Whenever I try to execute the code provided below, I encounter a 403 error. Could it be possible for this error to occur even though the URL I am attempting t ...

What is the best way to invoke the first exported function from the second exported function?

I am looking to create a file containing four or five exported functions. exports.firstFunction = function() { // some code }; exports.secondFunction = function() { // need to call firstFunction }; My issue is that I want the second expo ...

Encountering the "ERR_INVALID_ARG_TYPE" issue when attempting to add entries to an Mssql database using Typeorm

Currently, I am utilizing Nestjs for a specific project where I aim to input values into an Mssql database via Typeorm. However, I have encountered an error during the insertion process: TypeError [ERR_INVALID_ARG_TYPE]: The "string" argument must be of t ...

The internal cjs loader in node threw an error at line 1078

I'm encountering an error on Windows 10 when running the npm command: node:internal/modules/cjs/loader:1063 throw err; ^ Error: Cannot find module 'D:\mobile-version portfolio\ at Module._resolveFilename (node:internal/modules/cjs/load ...

Jade is not revealing the outcomes from the mysql database

I am implementing a project using node.js, express, jade, and mysql. \\app.js var db_config = { host: 'localhost', port: '3306', [redacted] }; var connection = mysql.createConnection(db_config); ... app.get('/events&ap ...

Node.js: The REST client delivers the response even before it has been officially returned

I've been experimenting with the node-rest-client REST client in Node.js. However, I'm facing an issue where when I run the code snippet below, it returns a value of null. Oddly enough, the response is printed to the console after that. Is there ...

Utilize the power of Elasticsearch in Node.js by executing a direct query using the Node

Searching with the NodeJS Elasticsearch library is possible (https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/quick-start.html). Is it feasible to run raw queries on indices? Can I execute a command like this: PUT index { "se ...