Render HTML file in ExpressJS

ExpressJS allows you to develop a custom web server according to your need. The express project can be extended by installing various node modules. However, you don’t need to install multiple packages to handle HTML files and to render them in the response.

In this short tutorial, I am going to explain to you how to render HTML files in ExpressJS response. You don’t need to install any extra modules to render an HTML file in Express. Just install express and you are good to go.

Step 1: Install Express

Create a new folder and initialize a new Node project using the following command.

npm init --y

Let’s install Express.

npm install --save express

Great. let’s move forward and learn about the function we are going to use to render HTML file in Express.

Step 2: Using sendFile() function

ExpressJS provides sendFile() function which will basically send HTML files to browser which then automatically interpreted by browser. All we need to do is in every route to deliver an appropriate HTML file.

For.eg :
When user hit main URL deliver index.html :

//assuming app is express Object.
app.get('/',function(req,res) {
  res.sendFile('index.html');
});

This code is for example purpose. It will cause directory resolution error.

Step 3: Render HTML in Express

I am going to develop simple website consist of 3 pages i.e Home page, about page, site link page. I will use Bootstrap for designing and jQuery for event handling.

Directory structure :

----- node_modules
|--+express
---+ index.html
---+ about.html
---+ index.html
--- app.js
----package.json
package.json
{
    "name": "htmlRender",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "test": ""
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "dependencies": {
        "express": "^4.16.4"
    }
}

Here is our express Server code.

app.js
const express = require('express');
const app = express();
const path = require('path');
const router = express.Router();

router.get('/',function(req,res){
  res.sendFile(path.join(__dirname+'/index.html'));
  //__dirname : It will resolve to your project folder.
});

router.get('/about',function(req,res){
  res.sendFile(path.join(__dirname+'/about.html'));
});

router.get('/sitemap',function(req,res){
  res.sendFile(path.join(__dirname+'/sitemap.html'));
});

//add the router
app.use('/', router);
app.listen(process.env.port || 3000);

console.log('Running at Port 3000');

Here is our HTML files. I am going to show index.html only.

index.html
<html>
<head>
  <title>Express HTML</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
</head>
<body>
  <div style="margin:100px;">
    <nav class="navbar navbar-inverse navbar-static-top">
  <div class="container">
    <a class="navbar-brand" href="/">Express HTML</a>
    <ul class="nav navbar-nav">
      <li class="active">
        <a href="/">Home</a>
      </li>
      <li>
        <a href="/about">About</a>
      </li>
      <li>
        <a href="/sitemap">Sitemap</a>
      </li>
    </ul>
  </div>
</nav>
    <div class="jumbotron"  style="padding:40px;">
      <h1>Hello, world!</h1>
      <p>This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.</p>
      <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a></p>
    </div>
  </div>
</body>
</html>

Here is the output.
homepage

Step 4: Render Dynamic HTML using templating engine

In the code shown above, we render static HTML files. However, there are scenarios where we need to render dynamic HTML templates. Before you get confused between static and dynamic templates, let me explain a difference quickly.

In a static templates, we cannot pass custom variables and customize the template based on our need. In dynamic templates, we can pass dynamic variables and render HTML files with different values.

Let’s build a simple project to understand the templating in Express. I am going to use pug templating engine which is very popular and recommended by Express as well. We use Pug for this website as well, in fact this page is rendered using Pug templates.

Let’s install our dependencies.

npm i --S express pug

Here is our Express server code.

app.js
const express = require("express");
const app = express();
const path = require("path");
const router = express.Router();

app.set("view engine", "pug");
app.set("views", path.join(__dirname, "views"));

router.get("/", (req, res) => {
  res.render("index");
});

router.get("/about", (req, res) => {
  res.render("about", { title: "Hey", message: "Hello there!" });
});

app.use("/", router);
app.listen(process.env.port || 3000);

console.log("Running at Port 3000");

Observe in routers, we are passing dynamic values to Pug templates. Here is the code of Pug templates residing in the views directory.

index.pug
html
  head
    title Render HTML using PUG
  body
    h1 Welcome
about.pug
html
  head
    title= title
  body
    h1= message

After running this code, navigate your browser to localhost:3000/about, you should see a HTML output rendered using Pug templates.

Awesome. These values can be feteched from database or any other source and rendered using Pug templates.

Related articles about Databases: Database Tutorials

Further reading

Read some of our best tutorials.

Conclusion:

There are scenarios where you need to develop a web server that delivers HTML files like how your apache does. However, this is not the optimal use of Node.js but you can use such a feature to achieve custom web server for your own application.

Bonus

If you are new to Node and Express then I highly recommend you to enroll on our Node course. Its FREE!