- Express.js Basics
- Express.js HOME
- Express.js Introduction
- Express.js Installation
- Express.js Basic App
- Express.js Routing
- Basics Routing
- Route Parameters
- Handling Query Strings
- Router Middleware
- Middleware
- What is Middleware?
- Application-Level Middleware
- Router-Level Middleware
- Built-In Middleware
- Error-Handling Middleware
- Third-Party Middleware
- Express.js HTTP
- Handling GET Requests
- Handling POST Requests
- Handling PUT Requests
- Handling DELETE Requests
- Templating Engines
- Using Templating Engines
- Setting Up EJS
- Setting Up Handlebars
- Setting Up Pug
- Request/Response
- Request Object
- Response Object
- Handling JSON Data
- Handling Form Data
- Static Files
- Serving Static Files
- Setting Up Static Folders
- Managing Assets
- Express.js Advanced
- Middleware Stack
- CORS in Express.js
- JWT Authentication
- Session Handling
- File Uploads
- Error Handling
- Databases
- Express.js with MongoDB
- MongoDB CRUD Operations
- Express.js with MySQL
- MySQL CRUD Operations
- Deployment
- Deploying Express.js Apps to Heroku
- Deploying Express.js Apps to AWS
- Deploying Express.js Apps to Vercel
Express.js Setting Up EJS
EJS, or Embedded JavaScript, is one of the most popular templating engines for Node.js. It allows you to build dynamic websites where the content changes based on data from your server, but it does so using a syntax that looks almost exactly like standard HTML. If you know HTML and basic JavaScript, you can start using EJS in minutes.
Key Features of EJS
- Embedded JavaScript Syntax: You don't need to learn a new language. Use standard JavaScript logic (like
ifstatements andforloops) directly inside your HTML tags. - Template Inheritance (Partials): EJS makes it easy to create reusable components like navigation bars, headers, and footers. You write them once and include them in every page.
- Dynamic Content: Whether you are pulling user profiles from a database or displaying search results, EJS lets you inject that data into your UI seamlessly.
- Fast Rendering: EJS is lightweight and highly optimized for performance, making it suitable for high-traffic applications.
Steps to Set Up EJS in Express.js
1. Install EJS
To get started, you need to add the EJS package to your project. Use npm (Node Package Manager) to install it:
npm install ejs
2. Set EJS as the View Engine
Express needs to know which templating engine you plan to use. You configure this using the app.set method. This tells Express that whenever you call res.render(), it should look for .ejs files.
In your main entry file (usually app.js or server.js), add the following:
const express = require('express');
const app = express();
// Set EJS as the view engine
app.set('view engine', 'ejs');
// Optionally, specify the views folder (defaults to './views')
app.set('views', './views');
views folder at the root of your project. While you can change the path, keeping it named "views" is the standard convention that other developers will expect to see.
3. Create Views Folder
Create a folder named views in your project's root directory. This is where Express will automatically look for your templates when you try to render a page.
4. Create EJS Templates
Inside your views folder, create a file named index.ejs. Notice that we use the <%= %> tag to output data. This escapes the HTML to prevent Cross-Site Scripting (XSS) attacks.
Example views/index.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<h1>Welcome to <%= title %>!</h1>
<p>The current server time is: <%= new Date().toLocaleTimeString() %></p>
</body>
</html>
<%= %> (escapes HTML) and <%- %> (renders raw HTML). Never use <%- %> with data provided by users, as it can leave your site vulnerable to malicious scripts.
5. Render Views in Express Routes
To display your template, use res.render() inside your route handler. You don't need to include the .ejs extension; Express finds it automatically.
Example route:
app.get('/', (req, res) => {
// We pass an object containing the data we want to use in the template
res.render('index', { title: 'My Express Application' });
});
6. Run the Application
Start your server to see the result:
node app.js
Navigate to http://localhost:3000. Express will take the index.ejs file, inject the "title" variable, and send the final HTML to your browser.
Using EJS Partials
Partials allow you to break your UI into smaller, manageable chunks. This is essential for maintaining large projects. Instead of copying your navigation bar onto every single page, you create it once and "include" it.
Create a Partial Template
Create a subfolder called views/partials and add a file named header.ejs:
<header style="background: #f4f4f4; padding: 10px;">
<nav>
<a href="/">Home</a> | <a href="/about">About</a>
</nav>
</header>
Include the Partial in Other Templates
In your index.ejs (or any other view), use the include function:
<%- include('partials/header') %>
<main>
<h2>Main Content Area</h2>
<p>This content is unique to this page.</p>
</main>
include requires the <%- tag (with a dash) rather than <%= (with an equals sign) because you are rendering raw HTML from another file.
Passing Data to EJS Templates
In a real-world scenario, you'll often pass arrays or objects—for example, a list of products from a database.
Example of passing an array of objects:
app.get('/users', (req, res) => {
const users = [
{ name: 'Alice', role: 'Admin' },
{ name: 'Bob', role: 'Editor' },
{ name: 'Charlie', role: 'User' }
];
res.render('users', { userList: users });
});
In views/users.ejs, you can use a JavaScript forEach loop to display the data:
<h1>User Directory</h1>
<ul>
<% userList.forEach(function(user) { %>
<li><strong><%= user.name %></strong> - <%= user.role %></li>
<% }); %>
</ul>
<% %> (no equals sign) for control flow logic like loops and if-statements that don't directly output text to the screen.
Summary
Setting up EJS in Express.js is a powerful way to transition from static HTML files to dynamic web applications. By installing the EJS package, setting the view engine, and organizing your files in a views folder, you gain the ability to inject server-side data directly into your UI. Using partials further improves your workflow by keeping your code "DRY" (Don't Repeat Yourself). With these basics covered, you are ready to start building data-driven websites with Express.