Globals View in Express JS
Last Updated :
04 Apr, 2024
Express.js is a popular web framework for Node.js that simplifies the process of building web applications and APIs. One of the features provided by Express.js is the ability to define and use global variables within your application's views.
In this article, we'll explore what globals views are, how to set them up in Express.js, and best practices for using them effectively.
What is a Global View?
Global views in Express.js refer to the practice of making certain variables accessible across all views within an Express application. These variables can hold data that needs to be shared globally, such as user information, configuration settings, or constant values. By using global views, you can avoid repetitive data passing and enhance the overall organization of your application.
Common Globals in Express.js:
- req: Holds incoming request data like URLs, parameters, and headers.
- res: Sends back the HTTP response to the client.
- app: Represents the Express application, used for setup and configuration.
- locals: Stores variables specific to each request.
- __dirname: Gives the directory name of the current module.
- __filename: Gives the filename of the current module.
Setting Up Global Views
To set up global views in Express.js, you can utilize middleware functions provided by the framework. Middleware functions have access to the request (req
) and response (res
) objects, allowing you to modify data or behavior before sending a response to the client. Here's an example of how you can set up global views:
// Import required modules
const express = require('express');
const app = express();
// Define global variables middleware
app.use((req, res, next) => {
res.locals.currentUser = req.user; // Example: storing user information
res.locals.appName = 'MyApp'; // Example: application name
next();
});
// Route handling
app.get('/', (req, res) => {
res.render('index'); // Render index view with global variables
});
// Start the server
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Explanation: In this above example, We use app.use
to create a middleware function that sets global variables using res.locals
.
res.locals.currentUser
and res.locals.appName
are examples of global variables that can be accessed in any view.
Accessing Global Variables in Views
Once global variables are set up, you can access them directly within your views. Popular templating engines like EJS, Pug, and Handlebars can render these variables seamlessly. Here's an example using EJS:
<!-- views/index.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= appName %></title>
</head>
<body>
<h1>Welcome <%= currentUser.username %></h1>
<!-- Other HTML content -->
</body>
</html>
Explanation: In this EJS template, <%= appName %>
displays the application name.
<%= currentUser.username %>
accesses the username of the current user.
Best Practices for Using Global Variables
To ensure efficient and secure usage of global views, consider the following best practices:
- Limited Scope: Use global variables sparingly and only for data that truly needs to be shared across views.
- Security Measures: Avoid storing sensitive information in global variables, especially in client-side accessible views.
- Clear Naming: Choose descriptive names for global variables to improve code readability and maintenance.
- Middleware Order: Pay attention to the order of middleware functions to ensure global variables are set before rendering views.
Steps to Setup Application
Step 1: Create a express application by using this command
npm init
Step 2: Install the necessary packages/libraries in your project using the following commands.
npm install express ejs
Folder Structure:

The updated dependencies in package.json file will look like:
"dependencies": {
"ejs": "^3.1.9",
"express": "^4.18.3",
}
Example: Illustartipon to showcase the use of global views.
HTML
//index.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Global View Example</title>
</head>
<body>
<h1>
<%= globalVariable %>
</h1>
</body>
</html>
JavaScript
const express = require('express');
const app = express();
app.set('view engine', 'ejs');
app.use((req, res, next) => {
res.locals.globalVariable = 'Hello, Global!';
next();
});
app.get('/', (req, res) => {
res.render('index');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Step to Run Application: Run the application using the following command from the root directory of the project
node .\index.js
Output: Your project will be shown in the URL http://localhost:3000/

Conclusion
Global views in Express.js provide a convenient way to manage shared data across views in your web application. By setting up global variables using middleware and following best practices, you can enhance code organization, reduce redundancy, and improve overall development efficiency. Leveraging global views responsibly can lead to more maintainable and scalable Express.js applications.
Similar Reads
How to use Global functions in Express JS?
In this article, we will learn the global function of Express. Express JS is a web application framework for Node JS. This framework runs on the server-side framework. It is a trendy Express JS framework for building scalable web applications. There are many functions available in Express JS that ar
2 min read
Express.js | res.format() Function
The res.format() function performs content negotiation on the Accept HTTP header on the request object if it is present. This function checks the Accept HTTP request header and then invokes the corresponding handler depending on the Accept value. Syntax: res.format(object) Installation of the expres
2 min read
Express.js req.is() Function
The req.is() function returns the matching content-type if the incoming requestâs 'Content-Type' HTTP header field matches with the MIME type that has been specified by the type parameter and it returns null if the request has no body otherwise it returns false. Syntax: req.is( type ) Parameter: The
2 min read
Print hello world using Express JS
In this article, we will learn how to print Hello World using Express jS. Express JS is a popular web framework for Node.js. It provides various features that make it easy to create and maintain web applications. Express Js Program to Print Hello world:"Hello, World!" in Express JS serves as an exce
2 min read
Express res.locals Property
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.localsParameter: No parameters. Return V
2 min read
Express.js express.raw() Function
The express.raw() function is a built-in middleware function in Express. It parses incoming request payloads into a Buffer and is based on body-parser. Syntax: express.raw( [options] )Parameter: The options parameter contains various properties like inflate, limit, type, etc. Return Value: It return
2 min read
How to handle redirects in Express JS?
Express JS uses redirects to send users from one URL to another. This can be done for various reasons, such as handling outdated URLs or guiding users through a process. In ExpressJS, you define routes and use them to direct users to the desired URL. It's a way to keep your application organized and
2 min read
Middleware in Express
Middleware in Express refers to functions that process requests before reaching the route handlers. These functions can modify the request and response objects, end the request-response cycle, or call the next middleware function. Middleware functions are executed in the order they are defined. They
6 min read
What is Express Generator ?
Express Generator is a Node.js Framework like ExpressJS which is used to create express Applications easily and quickly. It acts as a tool for generating express applications. In this article, we will discuss the Express Generator. Express GeneratorExpress Generator is a command-line tool for quickl
3 min read
What is Middleware in Express.js ?
Middleware functions have access to the request object and the response object and also the next function in the application request-response lifecycle. Middlewares are used for: Change the request or response object.Execute any program or codeEnd the request-response lifecycleCall the next middlewa
2 min read