How do access NODE_ENV in Nunjucks template?

Viewed 1369

I have some Nunjucks template blocks that I want to render only in certain environments. I can't seem to access the NODE_ENV variable though. I tried this:

{% if process.env.NODE_ENV === 'development' %}
  <div>rendering some stuff here</div>
{% endif %}

This didn't seem to work for me though. It didn't seem to have any idea what process.env.NODE_ENV was.

Is it possible to access an environment variable like this in a template?

2 Answers

I ended up doing the following in my app.js

nunjucks.configure('views', {
  ...
}).addGlobal('NODE_ENV', process.env.NODE_ENV)

This simply adds NODE_ENV as a globally accessible variable in my Nunjucks template.

You can use one of these variants:

  1. Use addGlobal to define function which returns environment

    var nunjucks  = require('nunjucks');
    var env = nunjucks.configure();
    
    env.addGlobal('$environment', () => process.env.NODE_ENV || 'development');
    var res = nunjucks.renderString(`{{$environment()}}`);
    
    console.log(res);
    
  2. Define $environment as global.

  3. Set res.locals.environment in middleware

    const app = express();
    
    app.use(function (req, res, next) {
        res.locals.$environment = process.env.NODE_ENV || 'development';
        next();
    });
    
    // In nunjucks template
    {{$environment}}
    
Related