How to render HTML file in Express JS

Dynamite Technology
2 min readJul 23, 2023

To render an HTML file in Express.js, you can use the built-in templating engine or serve the static HTML file directly. Here are two common approaches:

1. Using the Built-in Templating Engine (Example: EJS)

  1. First, make sure you have installed Express and a templating engine like EJS:
npm install express ejs

2. Set up your Express application and configure the templating engine (EJS in this case):

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

// Set EJS as the view engine
app.set('view engine', 'ejs');

// Define the directory where your HTML files (views) are located
app.set('views', path.join(__dirname, 'views'));

// Optionally, you can define a static files directory (CSS, JS, images, etc.)
app.use(express.static(path.join(__dirname, 'public')));

// Define a route to render the HTML file
app.get('/', (req, res) => {
res.render('index'); // Assuming you have an "index.ejs" file in the "views" directory
});

// Start the server
app.listen(3000, () => {
console.log('Server started on http://localhost:3000');
});

3. Create an index.ejs file in the "views" directory:

<!DOCTYPE html>
<html>
<head>
<title>My Express App</title>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>

4. When you visit http://localhost:3000 in your browser, the “index.ejs” file will be rendered.

2. Serving Static HTML File

  1. Create a directory (e.g., “public”) in your project folder and place your HTML file (e.g., “index.html”) inside it.
  2. Set up your Express application to serve static files:
const express = require('express');
const app = express();

// Define the directory where your static files (including HTML) are located
app.use(express.static(path.join(__dirname, 'public')));

// Start the server
app.listen(3000, () => {
console.log('Server started on http://localhost:3000');
});

When you visit http://localhost:3000/index.html in your browser, the “index.html” file will be served.

Choose the appropriate approach based on your needs. The first method with a templating engine is more suitable when you want to dynamically render HTML with data from your server, whereas the second method is useful when you have static HTML files to serve.

--

--

Dynamite Technology
0 Followers

Dynamite Technology Private Limited is a software development company and digital marketing agency based in Mumbai India.