Nearby lessons

10 of 14

πŸ“¦ How To Share Common Code in Multiple Pages in Express JS | EJS Template Includes

πŸ“Œ What is Code Reuse?

πŸ’‘ Understanding Common Code Reuse in Express.js (EJS)

In real-world applications, multiple pages often share the same navigation bar, footer, sidebar, or other repeated UI blocks. Instead of rewriting this code on every page, EJS allows you to include common files and reuse them easily.

This makes your code cleaner, reduces repetition, and simplifies future updates β€” update once, and all pages reflect the change!

πŸ“ Step 1: Project Folder Structure

Create the following folder and file structure inside your project:

πŸ“ project-folder
 ┣ πŸ“ views
 ┃ ┣ πŸ“„ home.ejs
 ┃ ┣ πŸ“„ about.ejs
 ┃ ┣ πŸ“„ contact.ejs
 ┃ β”— πŸ“ common
 ┃     ┣ πŸ“„ header.ejs
 ┃     β”— πŸ“„ footer.ejs
 β”— πŸ“„ index.js
        

βš™οΈ Step 2: Express Setup (index.js)

In your main Express file, set EJS as the view engine and render pages normally:

Express.js Server
NODE RUNTIME
const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());
app.set('view engine', 'ejs');

app.get('/', (req, res) => {
    res.render('home');
});

app.get('/about', (req, res) => {
    res.render('about');
});

app.get('/contact', (req, res) => {
    res.render('contact');
});

app.listen(8080, () => {
    console.log("Server running at http://localhost:8080");
});

Browser Output
Server logs

🧱 Step 3: Create EJS Pages & Include Common Header and Footer

Each page includes header.ejs and footer.ejs using the EJS include feature:

Express.js Server
NODE RUNTIME
const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());
app.set('view engine', 'ejs');

app.get('/', (req, res) => {
    res.render('home');
});

app.get('/about', (req, res) => {
    res.render('about');
});

app.get('/contact', (req, res) => {
    res.render('contact');
});

app.listen(8080, () => {
    console.log("Server running at http://localhost:8080");
});
Browser Output
Server logs

πŸ“˜ How It Works

  • πŸ“Œ EJS include allows reusing common UI parts across multiple pages.
  • 🧩 header.ejs and footer.ejs act as shared components.
  • πŸ”— home.ejs, about.ejs, and contact.ejs include these common sections.
  • πŸš€ Updating navigation or footer once updates all pages automatically.
  • 🧹 Keeps your project clean, structured, and easy to maintain.

🧠 Test Your Knowledge

5 Questions

Progress: 0 / 5
Keep Going!Use Bootstrap in Express.js