Tribute to Swissted — Part I: Setting up a Node.js Web App with Koa and Nunjucks
Tags: node, koa, beginners
Published: 2019-05-12 17:59:11

---
title: Tribute to Swissted — Part I: Setting up a Node.js Web App with Koa and Nunjucks
published: true
description: Setting up a Node.js web app with Koa and Nunjucks
tags: nodejs, koa, beginners
series: Tribute to Swissted, My First Node Web App
---

In the first part of [this series](https://dev.to/ekafyi/tribute-to-swissted-introduction-2c6i), I will be creating a _basic Node web app that renders an HTML template file with server-side data_. At this stage, we are not dealing with the actual website content yet. 

The app below is what we are going to build, which I'm going to describe step-by-step shortly.

{% glitch eka-nodejs-koa-starter %}

**Libraries**
- [Koa](https://koajs.com/)
- Koa middleware: [koa-static](https://github.com/koajs/static), [koa-router](https://github.com/ZijianHe/koa-router), [koa-views](https://github.com/queckezz/koa-views)
- [Nunjucks](https://mozilla.github.io/nunjucks/)

**Table of Content**
1. Create a new Node app
2. Install Koa 
3. Install and setup Koa middleware and Nunjucks
4. Display our index page

Let’s begin!

---

## 1. Create a new Node app

> For detailed walkthrough of setting up a Node app on Glitch, check out [“An exercise in progressive enhancement” by Chen Hui Jing](https://dev.to/huijing/an-exercise-in-progressive-enhancement-lk1), which inspired this project.

I'm going to describe how to do this on [Glitch](https://glitch.com). If you use a different environment, please skip to step 2.

Create an account or log in to Glitch, then click on __New Project__ on the top right and choose `hello-express`. It will automagically ✨ create a Node project and take you to the Editor view. The project uses a random auto-generated name, which you can change by clicking on the name at the top left.

![Glitch editor view showing new hello-express project](https://thepracticaldev.s3.amazonaws.com/i/0fugjsrk33swdgtmem0o.png)

We are removing Express because we are using Koa, a different library. To do that, click on __Tools__ at the bottom left corner and open the __Console__, which is just like the Command Line Interface on your machine.

💡 **Tips:** Clicking __Console__ opens it in full-screen view (in a new tab), while clicking __Logs__ opens a split-screen at the bottom of the editor where you can see _Logs_, _Debugger_, and _Console_.

![Glitch editor with Console split-screen at the bottom](https://thepracticaldev.s3.amazonaws.com/i/z9tgn0wsudurswy8bgii.png)

Run this command in the Console to uninstall Express. (Glitch uses `pnpm` package manager instead of `npm`.)

```bash
pnpm uninstall express --save
```

## 2. Install Koa

Now we are installing Koa, a modern web framework for Node. You can [learn more in their official docs](https://koajs.com/).

To install Koa and reload your application, run the following in the console:

```bash
pnpm install koa --save
refresh
```

We still have Glitch's default Express server code, though, which results in an error. Let's fix it by deleting everything (😱) in `server.js` and replacing it with the code below.

```js
// server.js

// initialize Koa app
const Koa = require('koa')
const port = process.env.PORT || 3000
const app = new Koa()

app.use(async ctx => {
  ctx.body = 'Hello new Koa app!'
})

const listener = app.listen(port, function() {
  console.log('Your app is listening on port ' + listener.address().port)
})
```
The error should be gone, and you should see the _“Your app is listening on port 3000”_ message again. You can click __🕶 Show__ on the top bar to see the live site, which prints the text _“Hello new Koa app!”_

![Glitch Editor screen with Koa server code](https://thepracticaldev.s3.amazonaws.com/i/ln9xj3eq2soa3adpjjpw.png)

## 3. Install and setup Koa middleware and Nunjucks

Koa keeps its core framework lean by separating functionalities into _middleware_, that we can install depending on our app's needs.

**Middleware** is software that _“facilitates client-server connectivity, forming a middle layer in your application’s stack that acts as glue between the app(s) and the network”_ ([Upwork](https://www.upwork.com/hiring/development/koa-js-a-future-proof-javascript-middleware-framework/)). A middleware in Node is defined in [this article](https://hackernoon.com/middleware-the-core-of-node-js-apps-ab01fee39200) as _“a function that will the receive the Request and Response objects”_.

We are installing three Koa middleware packages plus Nunjucks templating engine by running the command below in the console.

```bash
pnpm install koa-static koa-router koa-views nunjucks --save
```

### 3a) Configure koa-static

We use [koa-static](https://github.com/koajs/static) to serve static assets, such as CSS and client-side JS files. Load `koa-static` and define `public` as our static assets folder by adding the following code after the line `new Koa()`.

```js
// server.js

// const Koa = require('koa') ... etc

// serve static assets with koa-static
const serve = require('koa-static')
app.use(serve('./public'))
```

### 3b) Configure koa-router

As the name suggests, [koa-router](https://github.com/ZijianHe/koa-router) takes care of the routing in our app. Our usage is identical to the [“Basic usage” example](https://github.com/ZijianHe/koa-router#router-) in their docs.

Here we load `koa-router`, create a router instance, then use `router.get` to handle the GET request—in this case to the home/root path (`/`).

```js
// server.js

// const Koa = require('koa') ... etc
// const serve = require('koa-static') ... etc

// initialize routing with koa-router
const Router = require('koa-router')
const router = new Router()

// ! remove these three lines
// app.use(async ctx => {
//   ctx.body = 'Hello new Koa app!'
// })

// ! add the lines below
// GET request for root
router.get('/', (ctx, next) => {
  ctx.body = 'Hello new Koa app with routing!'
})

// Add the given middleware function to this app
app
  .use(router.routes())
  .use(router.allowedMethods());

// const listener ... etc
```

Again, click __🕶 Show__ on the top bar to see the live site. It should now print *“Hello new Koa app with routing!”*

What if we want to render an HTML file instead of returning text like we just did? Go on to the next step.

### 3c) Configure koa-views and Nunjucks

We use [koa-views](https://github.com/queckezz/koa-views) to render our view files. The term “view” refers to the _presentation_ or the _user interface_ templates in web applications, in this case our HTML file.

Here we load `koa-views`, define our views directory (`/views`) where `koa-views` will look for our files, and define Nunjucks as our templating engine. [Nunjucks](https://mozilla.github.io/nunjucks/) is a templating engine for Javascript that we are going to use in our HTML file. It has features like conditionals and loops, which will help us display our data.

```js
// server.js

// const Koa = require('koa') ... etc
// const serve = require('koa-static') ... etc
// const Router = require('koa-router') ... etc

// intialize view rendering with koa-views
const views = require('koa-views')

// define HTML templating engine
app.use(views('./views', { map: { html: 'nunjucks' }}))
```

After that, let’s modify the function in the GET request  from the previous step to _render our HTML file_. Replace the `ctx.body` line with a `ctx.render` function, like so:

```js
// server.js

// GET request
router.get('/', (ctx, next) => {
  // ! remove this line
  // ctx.body = 'Hello new Koa app with routing!'

  // ! add this line
  return ctx.render('./index')
})
```

Now, when users access the root path (`/`), our app will render the file `views/index.html`. Let’s work on that in the next step.

## 4. Display our index page

🍎 **Note:** If you use Glitch, you should already have the default HTML and CSS files, `views/index.html` and `public/style.css`. If you use a different environment, create those files before proceeding.

### 4a) Prepare our HTML and CSS files 

Add the heading title and body text below to your file’s `<body>`. If you use Glitch, you can leave the `<head>` content and the footer as they are; just replace the body content. Make sure you link to your CSS file in the document `<head>`.

```html
<!-- views/index.html -->
<html lang="en">
  <head>
    <title>My New Node App</title>
    <link rel="stylesheet" href="/style.css">
  </head>
  <body>
    <h1>Hello</h1>
    <p>Have a good day!</p>
    <!-- Include Glitch's default footer and button -->
  </body>
</html>
```

Next, we are going to write our CSS file. Feel free to style your page any way you want.

```css
/** public/style.css */
h1 {
  font-style: italic;
  color: #373fff;
}
```

Reload your page, and you should see your new page.

![A page containing the title 'Hello' and body text 'Have a good day'](https://thepracticaldev.s3.amazonaws.com/i/sohi7ajqa9b6mqmjn0w8.png)

### 4b) Render view with data

Now we are going to pass data from the server to our view. The first step is getting the data and passing it to the template file from `server.js`. We are hardcoding the data `name: 'Eka'` (feel free to use your own name!) and sending it to our HTML template by passing an object to the `ctx.render` function.

```js
// server.js

// GET request
router.get('/', (ctx, next) => {
  return ctx.render('./index', { 
    name: 'Eka', 
  })
})
```

The next step is to display the data in our template file. Open `index.html` and change the heading text to display the `name`.

```html
<!-- views/index.html -->
<html lang="en">
  <head>
    <title>My New Node App</title>
    <link rel="stylesheet" href="/style.css">
  </head>
  <body>
    <h1>
      Hello {{ name }}
    </h1>
    <p>Have a good day!</p>
    <!-- Include Glitch's default footer and button -->
  </body>
</html>
```

Reload your page and you can see the heading text now displays your name.

![Same page as above, but with the title saying "Hello Eka" instead of "Hello"](https://thepracticaldev.s3.amazonaws.com/i/uaohd0pxg3haitao0bn6.png)

We have made a Node web app that renders an HTML file with data passed from the server! 🎉 

---

## 📝 My Notes

What I learned after going through the steps in this post: _(Bear in mind these are my subjective opinions!)_

* Glitch is soooo helpful to get you started building Node.js web apps. It removes the barrier of having to set up the environment; and it’s designed in such a way to make it easy for you to develop _from your web browser_. 😻
* Node.js for front-end seems to have reasonably low learning curve. Basic Javascript knowledge should be enough to get you started. To be fair, I learned about what packages to install from [this post](https://dev.to/huijing/an-exercise-in-progressive-enhancement-lk1) and might not have known where to start otherwise. But once I knew the packages and browsed their websites or repositories, they generally have detailed documentation that would enable me to go beyond the post I learned from.

---

In the next post, we are going to “scrape” and parse data from the Swissted and Codepen websites with Cheerio.

Happy building!