Implementing Custom Middleware
Custom middleware functions in Express.js allow developers to manipulate the request or response objects before passing them to subsequent middleware functions or routes. By setting variables in res.locals within a custom middleware, developers can ensure the availability of those variables in all views rendered during that request.
Syntax:
app.use(function(req, res, next) {
res.locals.variableName = value;
next();
});
Explanation:
- Custom middleware functions are functions that have access to the request, response, and the next middleware function in the application’s request-response cycle.
- By calling app.use() with a custom middleware function, you can define global variables that will be available in all routes and views for each request.
- This approach offers flexibility and control over when and how global variables are set, allowing for dynamic data manipulation based on the request.
Example: Illustration to create global variable via middleware.
<!-- 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');
// Custom middleware function to set global variable pageTitle
app.use(function (req, res, next) {
res.locals.pageTitle = 'My Express App';
next();
});
// Example route
app.get('/', (req, res) => {
res.render('index', { pageTitle: res.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