How to use app.locals In NodeJS
app.locals in Express.js allows developers to define variables that are accessible throughout the application’s lifecycle. Once defined, these variables can be accessed in all views across your application without needing to pass them explicitly in each route handler or view render function.
Syntax:
app.locals.variableName = value;
Explanation
- app.locals is an object that represents application-level variables.
- By assigning a value to app.locals.variableName, you create a global variable that can be accessed anywhere in your Express application.
- This approach is particularly useful for storing static data or configurations that are common across all views or routes.
Example: Illustration to create global variable using app.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 path = require('path');
const app = express();
// Set EJS as the view engine
app.set('view engine', 'ejs');
// Define global variable pageTitle
app.locals.pageTitle = 'My Express App';
// Example route
app.get('/', (req, res) => {
res.render('index', { pageTitle: app.locals.pageTitle });
});
// Other routes and middleware...
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