Express Templates

By

Express can use server-side template engines like Pug and Handlebars to add data to a view and generate HTML dynamically.

~~~

Express is capable of handling server-side template engines.

Template engines let us add data to a view and generate HTML dynamically.

Express 5 (latest stable as of this update) does not ship with a Jade/Pug default. You pick an engine and install it yourself.

Pug used to be called Jade. The name changed in 2016 for trademark reasons when the project released version 2. Pug is now at 3. Official site: https://pugjs.org/.

You can use Pug, Handlebars, Mustache, EJS, and more.

Using Pug

Install it:

npm install pug

Set it on the Express app:

const express = require('express')
const app = express()
app.set('view engine', 'pug')

Create an about view:

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

And the template in views/about.pug:

p Hello from Flavio

That renders a p tag with Hello from Flavio.

Interpolate a variable:

app.get('/about', (req, res) => {
  res.render('about', { name: 'Flavio' })
})
p Hello from #{name}

Express compiles the template on every request while you develop, so edits show up on reload. With NODE_ENV=production it compiles each template once and caches it. I explain that switch in Node, the difference between development and production.

This is a short introduction to Pug with Express. See the Pug guide for more.

If you convert existing HTML to Pug, this HTML-to-Jade converter helps (Jade is close to Pug, with a few differences): https://jsonformatter.org/html-to-jade

Also see the differences between Jade and Pug

Using Handlebars

Install Handlebars for Express with npm install hbs.

Put an about.hbs template in views/:

Hello from {{name}}

Then:

const path = require('path')
const express = require('express')
const app = express()

app.set('view engine', 'hbs')
app.set('views', path.join(__dirname, 'views'))

app.get('/about', (req, res) => {
  res.render('about', { name: 'Flavio' })
})

app.listen(3000, () => console.log('Server ready'))

Rendering React

The old express-react-views package wired JSX templates into Express. It is largely unmaintained now.

For React on the server today, look at a proper SSR setup (for example Next.js, or a Vite SSR app) rather than treating React as a drop-in Express view engine.

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about express: