How to globally display data from a database in EJS templates?

To globally display data from a database in EJS templates, you can use middleware in your Express.js application. Middleware allows you to execute functions before the routes are processed. In your middleware, you can fetch the required data from the database and make it available to all your EJS templates. Here's how you can achieve this:

Step 1: Create a Middleware.

In your Express.js application file (e.g., app.js or server.js), create a middleware function that fetches the data from the database and attaches it to the response locals.

const express = require('express');
const app = express();

// ... Other app configurations ...

// Middleware to fetch data and make it available in templates
app.use(async (req, res, next) => {
  try {
    // Fetch data from the database
    const globalData = await fetchDataFromDatabase();

    // Make the data available to all templates
    res.locals.globalData = globalData;

    // Move to the next middleware or route handler
  } catch (error) {

// ... Define your routes ...

app.listen(3000, () => {
  console.log('Server is running on port 3000');

Step 2: Access Data in EJS Templates.

With the middleware in place, the data fetched from the database will be available in the res.locals object. You can access it in your EJS templates like any other local variable.

<!-- Your EJS template -->
    <title>Global Data Example</title>
    <h1>Welcome to our website</h1>
    <p>Site name: <%= globalData.siteName %></p>
    <p>Latest blog post: <%= globalData.latestPost %></p>
    <!-- ... other template content ... -->

In this example, globalData.siteName and globalData.latestPost correspond to the properties you fetched from the database.

By using this middleware approach, the data fetched from the database will be available globally to all your EJS templates, making it easier to display dynamic content throughout your website.

Muhammad Alfaiz
Alfaiz 6 months ago
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x