Build a static website with Node.js, Express, and Pug

michaelburrows

Michael Burrows

Posted on August 7, 2020

Build a static website with Node.js, Express, and Pug

Express is a minimal and flexible Node.js web application framework.

In this introductory tutorial we’ll be using Express “routes” and “views” to build a simple static website.

Setup project and install Node.js/Express

Before continuing you’ll need to have Node.js installed – if not download and run the installer found here.

With Node.js installed create a project directory called mysite and switch to the newly created directory:

mkdir mysite
cd mysite
Enter fullscreen mode Exit fullscreen mode

Next let’s initiate the project (default values are fine):

npm init -y
Enter fullscreen mode Exit fullscreen mode

Now we’re ready to install Express by running the following command:

npm install express --save
Enter fullscreen mode Exit fullscreen mode

With Express installed let’s create the main entry point for our application index.js:

touch index.js
Enter fullscreen mode Exit fullscreen mode

Add the following code to index.js to create a bare-bones Express app:

const express = require("express");
const app = express();
const port = 3000;

app.get("/", (req, res) => {
  res.send("Hello World!");
});

app.listen(port, () => {
  console.log("Server Started...");
});
Enter fullscreen mode Exit fullscreen mode

When run this will start a server on port 3000 and display “Hello World!” for requests to the root URL (/).

So we don’t have to manually restart the server to view modifications to let’s also install nodemon:

npm install nodemon --save
Enter fullscreen mode Exit fullscreen mode

Once installed modify the “scripts” section of package.json file as follows:

"scripts": {
  "start": "nodemon index.js"    
},
Enter fullscreen mode Exit fullscreen mode

We can now run npm start to start the server, watch files for changes, and restart as required.

At this stage you should see the text “Hello World!” when you visit http://localhost:3000/ in the browser.

Setup routing

As a website grows it makes sense to manage the various routes in individual files rather than in index.js.

Create a /routes folder with a route file for our home page called home.js with the following code:

const express = require('express');
const router = express.Router();

router.get('/', function(req, res, next) {
    res.send("Home Router Test");    
});

module.exports = router;
Enter fullscreen mode Exit fullscreen mode

We then need to remove the old route from index.js and direct Express to our new route file:

// app.get("/", (req, res) => {
//   res.send("Hello World!");
// });

var homeRouter = require('./routes/home');
app.use('/', homeRouter);
Enter fullscreen mode Exit fullscreen mode

Refresh the browser and you should see the text “Home Router Test” from the home.js route.

Setup views

I’ll be using Pug to display the views but Express also supports a variety of different template engines.

To install Pug run the following command:

npm install pug --save
Enter fullscreen mode Exit fullscreen mode

Then in index.js define the path to our view files also specifying the template engine we’re using:

const path = require('path');
app.set('views', path.join(__dirname, '/views'));
app.set('view engine', 'pug');
Enter fullscreen mode Exit fullscreen mode

Next create a layout.pug file in the /views folder that’ll act as the main layout:

doctype html
html
  head
    title= title   
  body
    block content
Enter fullscreen mode Exit fullscreen mode

Then create the view for the home page in /views/home.pug that extends layout.pug:

extends layout

block content
  h1= title
  p Welcome to our website built with Node.js & Express 
  p 
    a(href='/services') View our services
Enter fullscreen mode Exit fullscreen mode

Now instead of sending plain text we’ll render the home view by editing /routes/home.js as follows:

router.get('/', function(req, res, next) {
    //res.send("Home Router Test");
    res.render('home', { title: 'Home' });
});
Enter fullscreen mode Exit fullscreen mode

Adding additional routes & views

If you click the “View our services” link you’ll get en error as we haven’t set up the “services” route yet.

Define the new route in index.js:

const servicesRouter = require('./routes/services');
app.use('/services', servicesRouter);
Enter fullscreen mode Exit fullscreen mode

Create a new file called services.js in the /routes folder:

const express = require('express');
const router = express.Router();

router.get('/', function(req, res, next) {    
    res.render('services', { title: 'Services' });
});

module.exports = router;
Enter fullscreen mode Exit fullscreen mode

Then create a service.pug file and save it in the /views folder:

extends layout

block content
  h1= title
  p Some of our services include:
  ul
  li Website Design
  li Web Development
  li Search Engine Optimisation
Enter fullscreen mode Exit fullscreen mode

You’ll now be able to view the services page at the following URL – http://localhost:3000/services

That concludes this tutorial, hopefully you now understand how simple routes and views work in Express.

Originally published here.

💖 💪 🙅 🚩
michaelburrows
Michael Burrows

Posted on August 7, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related