Using Nunjucks with Express 4

I would like to add my solution. I came across this same problem since the express generator does not have support for the nunjucks templating engine. As mentioned, you should import the express and nunjucks dependencies and then configure nunjucks.

const app = express();
const nunjucks = require('nunjucks');
nunjucks.configure('views', {
  autoescape: true,
  express: app
});

Next, you need to decide how you want to render your templates. You have the option of responding to HTTP requests by rending a simple string or file. However, assuming your project may grow at some point I believe it’s better to take advantage of routing and middleware provided by express. Using the express generator, express provides two folders, views, and routes. Within the app.js file are two methods for responding to incoming requests.

app.use('/', indexRouter);
app.use('/users', usersRouter);

Where indexRouter and usersRouter are both defined as follows:

const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');

This is telling express, when a request for “/” comes in, handle it with the index.js file in the routes folder. In the same manner, when a request for “/users” comes in, handle it with the users.js file in the routes folder. Since we are just trying to implement the nunjucks templating engine we can leave those lines as they are. It is important to understand that the index.js file in the routes folder will utilize the express Router, prepare the response, and render a file in the views folder with the same name. This means we need to create a file in the views folder called index – in order for the names to match.

The convention in the Nunjucks community is to use the njk extension. So, we will use index.njk as the name of our root page. Lastly, we need to let express know that it should be expecting the njk extension. This is because the njk extension is just a convention. We could just as easily use .html and as long as we have nunjucks configured and tell express to expect html. In app.js:

app.set('view engine', 'njk');

Now we can use the nunjucks templating engine and it will be compiled to HTML. I recommend creating a layout file and using nunjucks {% block content %} code-goes-here {% endblock %} to create reusable components that can be inherited via Nunjuck’s template inheritance, i.e. {% extends "layout.njk" %}

Nunjucks is an incredibly powerful templating engine with a robust set of feature. In my opinion, it is the most underrated templating engine. It’s easy to use, extremely powerful, and extensible.

For more information regarding template inheritance, this is a helpful link from jinja2, from which nunjucks was ported, click me!

If you want to see an example app I set up with Express 4, Nunjucks, and Winston for logging, you can find it on my GitHub.