res.locals Property in Express.js


The res.locals is an object that contains the local variables for the response which are scoped to the request only and therefore just available for the views rendered during that request or response cycle.

This property is useful while exposing the request-level information such as the request path name, user settings, authenticated user, etc.

Syntax

res.locals

Example 1

Create a file with the name "resLocals.js" and copy the following code snippet. After creating the file, use the command "node resLocals.js" to run this code as shown in the example below −

// res.locals Property Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Defining an endpoint
app.get('/api', function (req, res) {
   res.locals = 'Welcome to TutorialsPoint';
   console.log(res.locals);
   res.end(res.locals);
});
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Hit the following Endpoint with a GET request − localhost:3000/api

Output

C:\home
ode>> node resLocals.js Server listening on PORT 3000 Welcome to TutorialsPoint

Example 2

Let's take a look at one more example.

// res.locals Property Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Defining an endpoint
app.get('/api', function (req, res) {

   // Defininf multiple locals
   res.locals.name = 'Mayank';
   res.locals.age = 21;
   res.locals.gender = 'Male'
   console.log(res.locals);
   res.send(res.locals);
});
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Hit the following Endpoint with a GET Request − localhost:3000/api

Output

C:\home
ode>> node resLocals.js Server listening on PORT 3000 [Object: null prototype] { name: 'Mayank', age: 21, gender: 'Male' }

Updated on: 29-Jan-2022

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements