Tutorial using ejs with Express

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

In this tutorial, we will use ejs with Express and Node.js. ejs is embedded Javascript template engine suitable for use with Express applications on Node.js. We assume that you have Node.js installed. If not follow this tutorial.

1. In an empty working directory, create a package.json file with the following content …

  "name": "ejs",
  "version": "0.0.1",
  "description": "Using ejs with Express",
  "main": "server.js",
  "dependencies": {
      "express": "~3.4.8",
      "ejs": "1.0.0"

2. In package.json, we specify server.js to be the main entry point. Create a server.js file with the following content…

var express = require('express');
var app = express();

app.set("view engine", "ejs");
app.set("views", __dirname + "/views");
app.set("view options", { layout: false } );

app.get('/', function(req, res) {

console.log('listening on port 3000...');

Note we had set the express app to use “view engine” of “ejs”.

3. We had specified our views to be in the “views” folder. So create a folder called “views”.

4. We had specified “index” as the argument to res.render. So it expects “index.ejs” within the views folder. Create file index.ejs with the following HTML content…

html using ejs

html using ejs

5. Run “npm install” in the working directory and it will create the folder “node_modules” with “express” and “ejs” in it.

6. Run node and start the web app with …

node server.js

7. Because we had specified to listen on port 3000, point your browser to http://localhost:3000 and you should see your web app render the ejs template …

express with ejs

express with ejs