How to Set Up Nunjucks with ExpressJS
Tags: javascript, node, express, nunjucks
Published: 2021-01-01 00:41:03


---
canonical_url: https://kelvinmwinuka.com/how-to-set-up-nunjucks-with-expressjs/
---

When building a web app without a dedicated front-end framework like ReactJS, Templating engines (e.g. Blade, Nunjucks) are incredibly useful.

Though they aren't entirely necessary, they definitely help create more dynamic pages with cleaner HTML code.

Before getting into JavaScript, Flask and Django were my preferred choices for building web applications. Coming from that background, I got very used to the Jinja2 engine.

When I switched to using Express for web app development, I wanted a solution that would have similar syntax and features to Jinja2. Fortunately, Nunjucks is exactly that. This is a templating engine that is heavily inspired by Jinja2.

In this article, I will walk you through the Nunjucks setup for ExpressJS. This is a fairly simple and straight-forward process.

<!-- wp:heading -->
<h2>Setup</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>First, create an empty folder. Navigate into the folder and run the following command to initialise npm:</p>
<!-- /wp:paragraph -->

`npm init`

<!-- wp:paragraph -->
<p>Follow all the prompts to setup your project.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Once the setup process has completed, you should have a package.json file in the root of your project.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Installing packages</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Next, run the following command to install express and nunjucks.</p>
<!-- /wp:paragraph -->

`npm install express nunjucks`

<!-- wp:heading {"level":3} -->
<h3>Defining the entry point</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Now create the file that will be the entry point of our application. I name this file index.js and place it at the root of my project.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The contents of index.js are as follows:</p>
<!-- /wp:paragraph -->

```javascript
const express = require('express')
const nunjucks = require('nunjucks')

var app = express()

nunjucks.configure('views', {
  autoescape: true,
  express: app
})

app.set('view engine', 'html')

const PORT = '8000'

app.get('/', (req, res) => {
  res.render('home.html')
})

app.listen(PORT, () => {
  console.log(`Listening on port ${PORT}...`)
})
```

<!-- wp:paragraph -->
<p>Let's take a moment to go through what's happening in this file:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Require the express and nunjucks packages.</li><li>Create an instance of express and assign it to a variable called 'app'.</li><li>Configuring nunjucks: The first parameter is the path to the template folder. The second parameter is an object containing configuration options. <a href="https://mozilla.github.io/nunjucks/templating.html#autoescaping" target="_blank" rel="noreferrer noopener">Autoescape</a> makes sure all output to templates are escaped before display (recommended). You can manually mark the output as safe. The express property requires an instance of an express app.</li><li>Set the port number. We'll use this when starting the application later.</li><li>Create a 'get' route at '/' and return a response that simply renders the template home.html.</li><li>Listen for connections on the specified port.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Creating the templates</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>At the moment if you try to load the application, you'll get an error because we haven't created the template that we're trying to render yet.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Remember that we set the path to templates as 'views'. Nunjucks will look for the 'views' folder in the same directory as the script that runs the configuration. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>If you have your template folder in another directory or have named it something different like 'templates', make sure you configure the path correctly.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In this case, we have to create a folder called 'views' in the root of our project (because this is where index.js resides).</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Inside the views folder, create a base.html template. This is the template that will be inherited by other templates. It allows us to define certain UI elements, styles and scripts only once and have them displayed/imported on every template.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This is where we'd define navigation bars and page footers.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The contents of base.html are as follows:</p>
<!-- /wp:paragraph -->

```html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>{{ title }}</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
  </head>
  <body>
    {% block content %}{% endblock %}
    <script src="" async defer></script>
  </body>
</html>
```

<!-- wp:paragraph -->
<p>We've defined a content block that will be overridden by the child templates. This is where the child templates will place their respective content.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Next, create a home.html template that extends base.html and displays a simple header in the content block.</p>
<!-- /wp:paragraph -->

```html
{% extends 'base.html' %}

{% set title = 'Home' %}

{% block content %}
  <h1>Welcome home!</h1>
{% endblock %}
```

Now that we've created the templates, we're able to load the home page. Visit localhost at the specified port and you should see that your app is up and running!

<!-- wp:heading -->
<h2>Conclusion</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In this article, we've covered setting up the nunjucks templating engine with an express web application. In the next article, I will write about <a href="https://kelvinmwinuka.com/how-to-set-up-mongoose-with-expressjs/" target="_blank" rel="noreferrer noopener">connecting an express application to MongoDB using mongoose</a> so we can persist data.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You can track the progress of this project on <a href="https://github.com/kelvinmwinuka/express-tutorial" target="_blank" rel="noreferrer noopener">Github</a>.</p>
<!-- /wp:paragraph -->

The post [How to Set Up Nunjucks with ExpressJS](https://kelvinmwinuka.com/how-to-set-up-nunjucks-with-expressjs/) appeared first on [Kelvin Mwinuka](https://kelvinmwinuka.com).

If you enjoyed this article, consider following my [website](https://kelvinmwinuka.com) for early access to my content before it gets published here (don’t worry, it’s still free with no annoying pop-up ads!). Also, feel free to comment on this post. I’d love to hear your thoughts!