#AD "Ten++ Ways to Make Money as a Developer" eBook by Florin Pop
#node

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

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

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

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:

touch index.js
Code language: plaintext (plaintext)

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)

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

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

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

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

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 the /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 services
Code 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 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
Code language: PHP (php)

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.

Related Posts