Utilizing res.locals
Unlike app.locals
, which stores application-level variables accessible across all requests, res.locals
is specific to the current request and response cycle. Once defined, variables set in res.locals
can be accessed within the current request’s route handler and any subsequent middleware functions that are part of that request chain.
Syntax:
res.locals.variableName = value;
Explanation:
- res.locals is an object that represents request-specific variables.
- By assigning a value to res.locals.variableName, you create a local variable that is available only within the current request-response cycle.
- This approach is useful for passing dynamic data to views based on each request, such as user authentication status or request-specific information.
Example: Illustration to create global variable using res.locals
<!-- index.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>MERN</title>
</head>
<body>
<h1>
Welcome to <%= pageTitle %>
</h1>
</body>
</html>
<!-- server.js -->
const express = require('express');
const app = express();
// Set EJS as the view engine
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
// Define local variable pageTitle for this request
res.locals.pageTitle = 'Home Page';
res.render('index', { pageTitle: res.locals.pageTitle });
});
app.get('/gfg', (req, res) => {
res.render('index', { pageTitle: res.locals.pageTitle });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Output:
How to Create Global Variables Accessible in all Views using Express/NodeJS ?
In Express.js, global variables can be immensely useful for sharing data across multiple views or middleware functions. Whether it’s storing user authentication status, site-wide configurations, or any other frequently accessed data, global variables streamline development and enhance code organization.
Table of Content
- Using app.locals
- Utilizing res.locals
- Implementing Custom Middleware