We generally use ExpressJS for building backend APIs. However, we can also use it to serve static HTML pages for our web applications. In this post, we will learn how to serve HTML page using ExpressJS.

The concept behind sending a HTML file is same as building an Express route handler. However, we need to properly resolve the directory structure of our project.

If you are totally new to ExpressJS, you can start with the post on getting started with Express.

1 – Creating Static HTML file

First step is create the static HTML files.

For demo purposes, we will create a home page or landing page.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Send Message</title>
</head>
<body>
    <header>
        <nav>
            <ul>
                <li><a href="/">Home</a></li>
                <li><a href="/send-message">Send Message</a></li>
            </ul>
        </nav>
    </header>
    <main>
        <h1>Welcome to Message Sender</h1>
    </main>
</body>
</html>

Apart from a normal welcome message, we also have a simple navigation bar on this page.

Second, we create another page for placing the message sending form. This page also has the navigation bar and a basic form for the user to enter the message.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Send Message</title>
</head>
<body>
    <header>
        <nav>
            <ul>
                <li><a href="/">Home</a></li>
                <li><a href="/send-message">Send Message</a></li>
            </ul>
        </nav>
    </header>
    <main>
        <form action="/send-message" method="POST">
            <input type="text" name="message">
            <button type="submit">Send</button>     
        </form>
    </main>
</body>
</html>

Both of these pages is within the views folder in our project directory.

2 – Serve HTML Page using ExpressJS

Once the pages are ready, we need to implement the ExpressJS route handlers to serve these pages.

See below:

const path = require('path');

const express = require('express');

const router = express.Router();

router.get('/', (req, res, next) => {
    res.sendFile(path.join(__dirname, '../', 'views', 'home.html'));
})

module.exports = router;

As you can see, we are using the ExpressJS router. Within the handler callback function, we call res.sendFile() function.

This function takes the path of the static HTML file as input. However, we need to account for our application running on different file systems such as Windows, Linux or Mac.

To have multi-platform support, we use the NodeJS core module named path. We call the path.join() function to build the file path. The __dirname variable provides access to the current working directory (in this case, the /routes directory).

Since the views directory is a sibling to the routes directory, we use ../ to traverse one level up in the folder hierarchy and then access views directory.

Similar to the home.html file, we can also serve the send-message.html file by creating another route handler for the same. See below:

const path = require('path');

const express = require('express');

const router = express.Router();

router.get('/send-message', (req, res, next) => {
    res.sendFile(path.join(__dirname, '../', 'views', 'send-message.html'));
})

module.exports = router;

Here also, we import the path module and then use res.sendFile() to serve the static HTML file using ExpressJS.

Conclusion

With this, we have successfully learnt how to serve HTML page using ExpressJS. Instead of using res.send(), we are using res.sendFile() to handle static HTML pages.

Want to serve dynamic pages using Node and Express? Check out this post on templating using Express and Pug view engine.

If you have any comments or queries about this post, please feel free to mention them in the comments section below.


Saurabh Dashora

Saurabh is a Software Architect with over 12 years of experience. He has worked on large-scale distributed systems across various domains and organizations. He is also a passionate Technical Writer and loves sharing knowledge in the community.

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *