Node.js app with Nunjucks (Part 2)

Maciej Modzelewski
Version 1
Published in
3 min readFeb 10, 2024

In the first part of this tutorial, we created a basic Node.js app to use for serving pages built using Nunjucks. Now it’s time to configure Nunjucks and our app to use it.

Configuration

Firstly, install Nunjucks, and to use the file watcher built-in to Nunjucks, Chokidar, a cross-platform file-watching library, must be installed as well.

npm i nunjucks chokidar

You have to also install the relevant type definition package.

npm i --save-dev @types/nunjucks

Following the model-view-controller software design pattern, create a views subdirectory in the src directory. This is where your template files will be located. Then in the index.ts file set path to it.

app.set('views', path.join(__dirname, '/views'));

Also, remember about importing the Node.js path module ( here is more about it if you are interested in details).

import path from 'path';

Next, create a Nunjucks loader, which is an object that takes a template name and loads it from a source, with a path to templates as an argument.

const nunjuckLoader = new nunjucks.FileSystemLoader(app.get('views'));

Also, create an object with the loader options. You really only need two: watch, which reloads templates when they are changed (server-side), and noCache, which will determine if the cache is used or templates will be recompiled every single time ( see the documentation).

const nunjuckLoaderOptions = {
watch: process.env.NUNJUCKS_LOADER_WATCH === 'true',
noCache: process.env.NUNJUCKS_LOADER_NO_CACHE === 'true',
};

Of course, remember to add relevant entries to the .env file.

NUNJUCKS_LOADER_WATCH=true
NUNJUCKS_LOADER_NO_CACHE=true

Finally, create a new instance of Nunjucks’s Environment class with the loader and its options.

const nunjucksEnvironment = new nunjucks.Environment(
nunjuckLoader,
nunjuckLoaderOptions
);

Then install Nunjucks as the rendering engine for the Express app.

nunjucksEnvironment.express(app);

You also need to provide the view engine, which is the file extension of your template files. You can use njk, which is the one adopted by the Nunjucks community, or HTML, but in fact, you are free to use any file extension you wish for your Nunjucks template files since any will work.

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

To check if the configuration works, create a simple template in the views directory with the name index.njk.

Then create a controllers directory in the src directory, and inside it, create an indexController.ts file with a simple function that will call Nunjucks’s render function available in the response parameter. It takes the name of the template and an object with properties that will be used in the template to substitute the tags with the provided texts. You have to ensure that the property keys are the same as the tags in the template.

import {Request, Response} from 'express';

export const indexController = (req: Request, res: Response) => {
res.render('main_content/home', {
headerText: 'Hello World!',
titleText: 'Home page',
});
};

Next, you have to import it into index.ts

import {indexController} from './controllers/indexController';

and provide as a parameter to the get request instead of the previously used arrow function.

app.get('/', indexController);

Before you can run the app, you have to modify the scripts in package.json. First, add a new script called build that will run the preexisting clean script, which removes the build directory, then the compile script, which will run the TypeScript Compiler (tsc), and finally copy recursively the views directory.

"build": "npm run clean && npm run compile && cp -r src/views build/src/views"

Then modify the start script, replacing the compile script with the build script, so it’s as follows:

"start": "npm run build && node build/src/index.js"

Now you can run your app. Happy coding!

If you’re interested in how these skills can be applied to larger projects, be sure to check out our Azure Application Modernisation Playbook.

About the author

Maciej Modzelewski is a Java Developer here at Version 1.

Originally published at http://maciejmodzelewski.com on February 10, 2024.

--

--