#AD Top Online Web Development & Programming Courses | Udemy
Newsletter Screenshot

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

Last modified October 14th 2020 | GitHub Source Code [GitHub] | #node

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 open the terminal and create a project directory called mysite and switch to the newly created directory with the following commands:

mkdir mysite
cd mysite

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

npm init -y

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

npm install express --save

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

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...");
});Code language: PHP (php)

Let’s also install nodemon to monitor file changes and automatically restart the server:

npm install nodemon --save

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

"scripts": {
  "start": "nodemon index.js"    
},Code language: JavaScript (javascript)

We can now run npm start to start the server with nodemon activated. At this stage if everything was setup correctly 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 new /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;Code language: JavaScript (javascript)

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

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

var homeRouter = require('./routes/home');
app.use('/', homeRouter);Code language: PHP (php)

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

Setup views

I’ll be using Pug as the template engine for displaying the views but Express also supports a variety of different template engines. To install Pug run the following command:

npm install pug --save

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');Code language: JavaScript (javascript)

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

doctype html
html
  head
    title= title   
  body
    block content

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 servicesCode language: JavaScript (javascript)

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' });
});Code language: JavaScript (javascript)

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);Code language: PHP (php)

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;Code language: JavaScript (javascript)

Then create a services.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 OptimisationCode language: PHP (php)

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

You should now have the basis for a static site that you can build out with additional pages as required. Hopefully you’ve gained an insight into how routes and views work in Express.

Related Posts

#AD Shop Web Developer T-Shirts