Before you can create a full blown app in Node, you’ll have to learn a few of the basics. One of those basics is how to specify routes for your web application. This tutorial will walk you through creating a route and view in Express (one of the more popular frameworks for node apps). Let’s get started.

Creating The Route

We’re going to assume the knowledge of creating a new Node.js & Express app. If you don’t know how to create an Express app with Node.js, check out Get Up and Running on Windows with Node.js and Express.

Open up your app.js file in your favorite text editor. You’ll notice that there’s two routes that are already defined:

The first line is responsible for handling all traffic to the root domain of the application so for the first argument we pass in ‘/’, and you can see it calls the index route. This routes.index method is dynamically generated by express and refers to the index.js file within the routes directory.

The second line is responsible for delivering content when someone types in our root domain and then appends ‘/users’ to it. As you can see we are calling user.list which provides you with an example of how to call specific methods from within a route file.

First we’re going to add a variable for our router within the app.js file, then we’ll specify when to call the router. At the top of the file with the rest of the Module dependencies type the following:

Then type the following next to the two routes:

If you take a look within the routes directory you will see there is both an index.js and users.js. Now, let’s create a new route by creating a new file named new.js and we can type the following within it:

Now we have a basic route structure for the request ‘/new’. The last step is creating the view.

Views in Express

The default view engine in express is Jade. Jade is a very minimalistic approach to templating engines. For the purpose of this tutorial we’re just going to use Jade but understand there are many more templating engines for Express including some popular favorites like Mustache.JS and Handlebars.JS just to name a few.

Let’s create our view by creating a new file named new.jade in the views directory:

The first line specifies that we are extending the functionality of layout.jade which holds all of our normal boring html elements like html, body, and head. Next we specify where our content is to be placed within the layout.jade structure and that’s the content section. Next we specify that our h1 element will consist of the value of title which was passed in through the route JavaScript file. The last line specifies the message within the paragraph element, again referencing the value of title.


Now we should be able to start our app and navigate to ‘/new’ to retrieve a web page with a title of New Template and a message of Welcome to the New Template. That’s a basic route and view in Node.js & Express. To learn more about Express routes and views visit the Express website.