How to Render EJS file in Express JS

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. Make sure you have installed nodejs before starting this project. Download Nodejs from its official website.
  2. 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)

//server.js
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 a index.ejs file in the "views" directory

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

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

4. 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:
  3. Here, you can add your images, CSS, and JavaScript files, which are available globally.
    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.


Similar Articles