DEV Community

Eka
Eka

Posted on • Edited on

Tribute to Swissted — Part I: Setting up a Node.js Web App with Koa and Nunjucks

In the first part of this series, 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.

Libraries

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, which inspired this project.

I'm going to describe how to do this on Glitch. 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

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

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

pnpm uninstall express --save
Enter fullscreen mode Exit fullscreen mode

2. Install Koa

Now we are installing Koa, a modern web framework for Node. You can learn more in their official docs.

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

pnpm install koa --save
refresh
Enter fullscreen mode Exit fullscreen mode

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.

// 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)
})
Enter fullscreen mode Exit fullscreen mode

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

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). A middleware in Node is defined in this article 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.

pnpm install koa-static koa-router koa-views nunjucks --save
Enter fullscreen mode Exit fullscreen mode

3a) Configure koa-static

We use koa-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().

// server.js

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

// serve static assets with koa-static
const serve = require('koa-static')
app.use(serve('./public'))
Enter fullscreen mode Exit fullscreen mode

3b) Configure koa-router

As the name suggests, koa-router takes care of the routing in our app. Our usage is identical to the “Basic usage” example 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 (/).

// 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
Enter fullscreen mode Exit fullscreen mode

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 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 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.

// 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' }}))
Enter fullscreen mode Exit fullscreen mode

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:

// 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')
})
Enter fullscreen mode Exit fullscreen mode

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>.

<!-- 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>
Enter fullscreen mode Exit fullscreen mode

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

/** public/style.css */
h1 {
  font-style: italic;
  color: #373fff;
}
Enter fullscreen mode Exit fullscreen mode

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

A page containing the title 'Hello' and body text 'Have a good day'

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.

// server.js

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

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

<!-- 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>
Enter fullscreen mode Exit fullscreen mode

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

Same page as above, but with the title saying

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 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!

Top comments (0)