Open In App

Express res.locals Property

Last Updated : 18 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The `res.locals` property is an object that holds response local variables specific to the current request. It has a scope limited to the request and is accessible only to the view(s) rendered during that particular request/response cycle, if any. 

Syntax:

res.locals

Parameter: No parameters. 

Return Value: Object 

Steps to Create the Application:

Step 1: Initialising the Node App using the below command:

npm init -y

Step 2: Installing the required packages:

npm i express body-parser

Project Structure:

NodeProj

The updated dependencies in package.json file will look like:

"dependencies": {
"body-parser": "^1.20.2",
"express": "^4.18.2",
}

Example 1: Below is the basic example of the res.locals property:

Javascript




const express = require('express');
const app = express();
const PORT = 3000;
 
app.get('/',
    function (req, res) {
        res.locals.user = 'GeeksforGeeks';
        console.log(res.locals);
        res.end();
    });
 
app.listen(PORT,
    function (err) {
        if (err) console.log(err);
        console.log(
            "Server listening on PORT",
            PORT
        );
    });


Steps to run the program:

node index.js

Output: go to http://localhost:3000/, now you can see the following output on your console:

Server listening on PORT 3000
[Object: null prototype] { user: 'GeeksforGeeks' }

Example 2: Below is the basic example of the res.locals property:

Javascript




const express = require('express');
const app = express();
const PORT = 3000;
 
app.get('/',
    function (req, res) {
 
        // Sending multiples locals
        res.locals.name = 'Gourav';
        res.locals.age = 13;
        res.locals.gender = 'Male'
        console.log(res.locals);
        res.end();
    });
 
app.listen(PORT,
    function (err) {
        if (err) console.log(err);
        console.log(
            "Server listening on PORT",
            PORT
        );
    });


Steps to run the program:

node index.js

Output: make a GET request to http://localhost:3000:

Server listening on PORT 3000
[Object: null prototype] { name: 'Gourav', age: 13, gender: 'Male' }

We have a complete reference article on response methods, where we have covered all the response methods to check those please go through Response Complete Reference article



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads