Meteor Routing tutorial using iron:router

Meteor Routing can be achieved using famous package available at atmospherejs ( Meteor package registry ) called iron-router. It provides both front-end and back-end routing facility.

In this tutorial I am going to cover :

  • Installing and configuring iron router.
  • Meteor front-end routing.
  • Meteor back-end routing.
  • Sample project.

DOWNLOAD

Prerequisites

Knowledge of Meteor basics is required. If you are new to Meteor then read this tutorial for basic information about Meteor.

Installing and configuring iron router

Create new Meteor project using following command.

meteor create appName

Meteor router tutorial - create app

After creating app, clean up the project directory cause meteor does create sample files for you.

Go to project directory and delete the files using following command.

 rm -rf *

Now let’s install the iron-router in our project. Run following command in your terminal.

meteor add iron:router

Meteor router tutorial - adding iron router

Now we can start writing code but before that create two folders in project directory. Namely client and server. We will add code in separate folders.

Meteor front-end routing

We can use iron-router to perform routing at our view. Meteor uses templates and helpers in front-end and to perform routing you need to define various templates which you want to display in each view.

By default, the declared routes are for the client. If you want a route to be server side, then you explicitly declare so by including where: ‘server’.

Create 3 blank files in client directory.

  • client.html
  • client.js
  • client.css

Consider following simple route.

Route : /

Show “Hello there !” message in heading 1. So we need to define one template in our HTML file and tell Router to show it when “/” route hits.

Here is sample template code.

client/client.html
<head>
    <meta charset="utf-8">
    <title>Meteor Router Tutorial</title>
</head>
<body>
</body>
<template name="home">
    <h1>Hello there !</h1>
</template>

Here is sample JS code.

if(Meteor.isClient) {
    Router.route('/',function(){
        this.render('home');
    });
}

Or if you want to pass custom data to each view you can do that too.

client/client.js
if(Meteor.isClient) {
    Router.route('/',function(){
        this.render('Home', {data: {title: 'Home'}});
    });
}

In HTML code, inside template use {{title}} to show its data. Of course you can write function in place of text which may return data from MongoDB and show it to Client !

Run it using following command.

meteor

Visit localhost:3000 to view the app.

Meteor Router Tutorial - Hello world route

You can define more routes in client.js and render the template on each. Easy stuff !

Meteor back-end routing

You can use iron-router for routing at server-side as well. We have covered ExpressJS routers to perform server-side routing. Create file name as server.js in server directory.

Here is skeleton of Router.

if(Meteor.isServer) {
    Router.route('/routeName',{where : 'server'})
    .get()
    .post()
    .put()
    .delete();
}

Let’s write one simple route which performs above operations.

Router : /message

GET – Returns all messages from MongoDB.
POST – Add new message in MongoDB.
PUT – update message text with respect to ID.
delete – delete message from MongoDB.

Our Server file.

server/server.js
if(Meteor.isServer) {
   // When Meteor starts, create new collection in Mongo if not exists.
    Meteor.startup(function () {
        Messages = new Meteor.Collection('messages');
    });

<pre><code>// GET /message - returns every message from MongoDB collection.

Router.route('/message',{where: 'server'})
    .get(function(){
        var response = Messages.find().fetch();
        this.response.setHeader('Content-Type','application/json');
        this.response.end(JSON.stringify(response));
    })

  // POST /message - {message as post data}
  // Add new message in MongoDB collection.

    .post(function(){
        var response;
        if(this.request.body.message === undefined || this.request.body.message === null || this.request.body.message === "") {
            response = {
                "error" : true,
                "message" : "invalid data"
            };
        } else {
            Messages.insert({
                message : this.request.body.message
            });
            response = {
                "error" : false,
                "message" : "message added."
            }
        }
        this.response.setHeader('Content-Type','application/json');
        this.response.end(JSON.stringify(response));
    });

Router.route('/message/:id',{where: 'server'})

    // GET /message/:id - returns specific records

    .get(function(){
        var response;
        if(this.params.id !== undefined) {
            var data = Messages.find({_id : this.params.id}).fetch();
            if(data.length &gt; 0) {
                response = data
            } else {
                response = {
                    "error" : true,
                    "message" : "Record not found."
                }
            }
        }
        this.response.setHeader('Content-Type','application/json');
        this.response.end(JSON.stringify(response));
    })

    // PUT /message/:id {message as put data}- update specific records.

    .put(function(){
        var response;
        if(this.params.id !== undefined) {
            var data = Messages.find({_id : this.params.id}).fetch();
            if(data.length &gt; 0) {
                if(Messages.update({_id : data[0]._id},{$set : {message : this.request.body.message}}) === 1) {
                    response = {
                        "error" : false,
                        "message" : "Message updated."
                    }
                } else {
                    response = {
                        "error" : true,
                        "message" : "Message not updated."
                    }
                }
            } else {
                response = {
                    "error" : true,
                    "message" : "Record not found."
                }
            }
        }
        this.response.setHeader('Content-Type','application/json');
        this.response.end(JSON.stringify(response));
    })

    // DELETE /message/:id delete specific record.

    .delete(function(){
        var response;
        if(this.params.id !== undefined) {
            var data = Messages.find({_id : this.params.id}).fetch();
            if(data.length &gt; 0) {
                if(Messages.remove(data[0]._id) === 1) {
                    response = {
                        "error" : false,
                        "message" : "Message deleted."
                    }
                } else {
                    response = {
                        "error" : true,
                        "message" : "Message not deleted."
                    }
                }
            } else {
                response = {
                    "error" : true,
                    "message" : "Record not found."
                }
            }
        }
        this.response.setHeader('Content-Type','application/json');
        this.response.end(JSON.stringify(response));
    });

}

Running the app.

Switch to project directory and run application using following command.

meteor

You should see following console.
Meteor router tutorial - running meteor app

Open REST simulator ( We recommend Postman ) and hit localhost:3000/message URL.

1: Fetch all messages (GET /message)

Meteor routing tutorial

2: Fetch Specific message (GET /message/:id)

Meteor routing tutorial

3: Add new message (POST /message)

Meteor routing tutorial

4: Update existing message (PUT /message/:id)

Meteor routing tutorial

5: Delete message (DEL /message/:id)

Meteor routing tutorial

Conclusion :

Meteor is indeed a next big thing in real time web app development zone. By using iron-router we can easily incorporate routing in meteor application. Will post more about this awesome framework in upcoming tutorials. Till then, happy coding!

Shahid
Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 126