Serving Static HTML files in Node
In web development, serving HTML files traditionally happens on the client side, rendering content in users' browsers. However, there are scenarios where serving HTML files from the server side becomes necessary. In this article, we'll explore how to achieve this using Node.js and the Express.js framework.
Installation
To begin, let's create a new project named static-pages-express.
Open your terminal and run the following commands:
npm init -y
npm install express
This sets up a basic Node.js project and installs the Express.js package, simplifying the process of serving static files.
Creating the Project Structure
Inside your project folder, create a "public" directory. In this directory, add four HTML files: index.html
, about-us.html
, contact-us.html
, and services.html
. These files will be served from the server side. Feel free to write your pages to your liking and also apply some styling.
Below is an example of the index.html
file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>
17th - 18th Weekend Challenge - Serving a Static HTML Site from an Express
Application
</title>
<link rel="stylesheet" href="./styles.css" />
</head>
<body>
<header>
<h1>Weekend Challenge 1</h1>
</header>
<nav>
<a href="/about">About</a>
<a href="/services">Services</a>
<a href="/contact">Contact</a>
</nav>
<footer>
© Weekend Challenge 1 (17th-18th Feb 2024). All rights reserved.
</footer>
</body>
</html>
Writing the Server Code
Now, let's create the main.js
file, which will define our server logic. Use your preferred code editor and write the following code:
const express = require("express");
const path = require("path");
const app = express();
const port = 3000;
// Serve static files from the "public" directory
app.use(express.static(__dirname + "/public"));
// Define routes for each HTML file
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "public/index.html"));
});
app.get("/about", (req, res) => {
res.sendFile(path.join(__dirname, "public/about-us.html"));
});
app.get("/contact", (req, res) => {
res.sendFile(path.join(__dirname, "public/contact-us.html"));
});
app.get("/services", (req, res) => {
res.sendFile(path.join(__dirname, "public/services.html"));
});
// Start the server
app.listen(port, () => {
console.log(`Server is running on Port: ${port}`);
});
Understanding the Code
We use Express.js to simplify our server setup.
The
express.static()
middleware is crucial for serving static files. In this case, it points to the "public" directory.Routes are defined for each HTML file, and the
res.sendFile()
method sends the corresponding file when a route is accessed.The server listens on port 3000.
Running the Application
In your terminal, run:
node main.js
Visit http://localhost:3000
in your browser, and you should see your index.html. Navigate to other routes like /about
, /contact
, and /services
to explore other pages.
Deployment
We have seen how to run the project in local development therefore, in this section, we are going to be deploying the project to Vercel which helps us publish our project publicly.
First, you need to Sign Up, and then afterwards, you need to download Vercel CLI globally in your machine like so:npm i -g vercel
Once you've installed Vercel, we need to create a vercel.json
file, this file is a config file that is used by Vercel to configure how your application is going to run. Remember, this is a Node JS application, so it needs to be deployed to serveless functions which Vercel readily provides.
Configure your vercel.json file as follows:
{
"version": 2,
"builds": [
{
"src": "main.js",
"use": "@now/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "main.js"
}
]
}
Explanation...
"version": 2
: This indicates that the configuration is using version 2 of the Vercel configuration format."builds": [...]
: This section defines how the application should be built and run."src": "main.js"
: This specifies the entry point for your Node.js application. The filemain.js
is the main file that Vercel should run."use": "@now/node"
: This specifies that the deployment should use the@now/node
builder, which is suitable for Node.js applications.
"routes": [...]
: This section defines how incoming requests should be routed."src": "/(.*)"
: This regular expression captures any path (/(.*)
) requested."dest": "main.js"
: This specifies that requests should be directed to themain.js
file.
With this, Vercel will use this configuration file for building our Node JS application. Now, we can deploy our application to Vercel by running: vercel --prod
.
Access your Vercel Dashboard to see your deployments. One is given a free subdomain to use by Vercel. For example, mine is: https://week-1-nine.vercel.app/, and with that, your application is successfully deployed!
Conclusion
This article has walked you through serving static HTML files from a Node.js server using Express.js and deploying it to Vercel. Feel free to explore the provided GitHub repository and experiment further, perhaps extending the project to serve images or additional content. Thank you for reading, and stay tuned for more web development insights!