An Introduction to Meteor

The goal of this blog post is to give you a brief introduction to Meteor which is a framework for building Single Page Apps. In this blog entry, I provide a walkthrough of building a simple Movie database app.

What is special about Meteor? Meteor has two jaw-dropping features:

Live HTML – If you make any changes to the HTML, CSS, JavaScript, or data on the server then every client shows the changes automatically without a browser refresh. For example, if you change the background color of a page to yellow then every open browser will show the new yellow background color without a refresh. Or, if you add a new movie to a collection of movies, then every open browser will display the new movie automatically.

With Live HTML, users no longer need a refresh button. Changes to an application happen everywhere automatically without any effort. The Meteor framework handles all of the messy details of keeping all of the clients in sync with the server for you.

Latency Compensation – When you modify data on the client, these modifications appear as if they happened on the server without any delay. For example, if you create a new movie then the movie appears instantly. However, that is all an illusion. In the background, Meteor updates the database with the new movie. If, for whatever reason, the movie cannot be added to the database then Meteor removes the movie from the client automatically.

Latency compensation is extremely important for creating a responsive web application. You want the user to be able to make instant modifications in the browser and the framework to handle the details of updating the database without slowing down the user.

Installing Meteor

Meteor is licensed under the open-source MIT license and you can start building production apps with the framework right now. Be warned that Meteor is still in the “early preview” stage. It has not reached a 1.0 release. According to the Meteor FAQ, Meteor will reach version 1.0 in “More than a month, less than a year.”

Don’t be scared away by that. You should be aware that, unlike most open source projects, Meteor has financial backing. The Meteor project received an $11.2 million round of financing from Andreessen Horowitz. So, it would be a good bet that this project will reach the 1.0 mark. And, if it doesn’t, the framework as it exists right now is still very powerful.

Meteor runs on top of Node.js. You write Meteor apps by writing JavaScript which runs both on the client and on the server. You can build Meteor apps on Windows, Mac, or Linux (Although the support for Windows is still officially unofficial).

If you want to install Meteor on Windows then download the MSI from the following URL:

http://win.meteor.com/

If you want to install Meteor on Mac/Linux then run the following CURL command from your terminal:

curl https://install.meteor.com | /bin/sh

Meteor will install all of its dependencies automatically including Node.js. However, I recommend that you install Node.js before installing Meteor by installing Node.js from the following address:

http://nodejs.org/

If you let Meteor install Node.js then Meteor won’t install NPM which is the standard package manager for Node.js. If you install Node.js and then you install Meteor then you get NPM automatically.

Creating a New Meteor App

To get a sense of how Meteor works, I am going to walk through the steps required to create a simple Movie database app. Our app will display a list of movies and contain a form for creating a new movie.

clip_image002

The first thing that we need to do is create our new Meteor app. Open a command prompt/terminal window and execute the following command:

Meteor create MovieApp

After you execute this command, you should see something like the following:

clip_image004

Follow the instructions: execute cd MovieApp to change to your MovieApp directory, and run the meteor command.

clip_image005

Executing the meteor command starts Meteor on port 3000. Open up your favorite web browser and navigate to http://localhost:3000 and you should see the default Meteor Hello World page:

clip_image007

Open up your favorite development environment to see what the Meteor app looks like. Open the MovieApp folder which we just created. Here’s what the MovieApp looks like in Visual Studio 2012:

clip_image009

Notice that our MovieApp contains three files named MovieApp.css, MovieApp.html, and MovieApp.js. In other words, it contains a Cascading Style Sheet file, an HTML file, and a JavaScript file.

Just for fun, let’s see how the Live HTML feature works. Open up multiple browsers and point each browser at http://localhost:3000. Now, open the MovieApp.html page and modify the text “Hello World!” to “Hello Cruel World!” and save the change. The text in all of the browsers should update automatically without a browser refresh. Pretty amazing, right?

clip_image011

Controlling Where JavaScript Executes

You write a Meteor app using JavaScript. Some of the JavaScript executes on the client (the browser) and some of the JavaScript executes on the server and some of the JavaScript executes in both places.

For a super simple app, you can use the Meteor.isServer and Meteor.isClient properties to control where your JavaScript code executes. For example, the following JavaScript contains a section of code which executes on the server and a section of code which executes in the browser:

if (Meteor.isClient) {
    console.log("Hello Browser!");
}

if (Meteor.isServer) {
    console.log("Hello Server!");
}

console.log("Hello Browser and Server!");

When you run the app, the message “Hello Browser!” is written to the browser JavaScript console. The message “Hello Server!” is written to the command/terminal window where you ran Meteor. Finally, the message “Hello Browser and Server!” is execute on both the browser and server and the message appears in both places.

clip_image013

For simple apps, using Meteor.isClient and Meteor.isServer to control where JavaScript executes is fine. For more complex apps, you should create separate folders for your server and client code. Here are the folders which you can use in a Meteor app:

· client – This folder contains any JavaScript which executes only on the client.

· server – This folder contains any JavaScript which executes only on the server.

· common – This folder contains any JavaScript code which executes on both the client and server.

· lib – This folder contains any JavaScript files which you want to execute before any other JavaScript files.

· public – This folder contains static application assets such as images.

For the Movie App, we need the client, server, and common folders.

Delete the existing MovieApp.js, MovieApp.html, and MovieApp.css files. We will create new files in the right locations later in this walkthrough.

Combining HTML, CSS, and JavaScript Files

Meteor combines all of your JavaScript files, and all of your Cascading Style Sheet files, and all of your HTML files automatically. If you want to create one humongous JavaScript file which contains all of the code for your app then that is your business. However, if you want to build a more maintainable application, then you should break your JavaScript files into many separate JavaScript files and let Meteor combine them for you.

Meteor also combines all of your HTML files into a single file. HTML files are allowed to have the following top-level elements:

<head> — All <head> files are combined into a single <head> and served with the initial page load.

<body> — All <body> files are combined into a single <body> and served with the initial page load.

<template> — All <template> files are compiled into JavaScript templates.

Because you are creating a single page app, a Meteor app typically will contain a single HTML file for the <head> and <body> content. However, a Meteor app typically will contain several template files. In other words, all of the interesting stuff happens within the <template> files.

Displaying a List of Movies

Let me start building the Movie App by displaying a list of movies.

clip_image015

In order to display a list of movies, we need to create the following four files:

· client\movies.html – Contains the HTML for the <head> and <body> of the page for the Movie app.

· client\moviesTemplate.html – Contains the HTML template for displaying the list of movies.

· client\movies.js – Contains the JavaScript for supplying data to the moviesTemplate.

· server\movies.js – Contains the JavaScript for seeding the database with movies.

After you create these files, your folder structure should looks like this:

clip_image017

Here’s what the client\movies.html file looks like:

<head>
    <title>My Movie App</title>
</head>

<body>
    <h1>Movies</h1>
    {{> moviesTemplate }}
</body>

 

Notice that it contains <head> and <body> top-level elements. The <body> element includes the moviesTemplate with the syntax {{> moviesTemplate }}.

The moviesTemplate is defined in the client/moviesTemplate.html file:

<template name="moviesTemplate">
    <ul>
    {{#each movies}}
    <li>
        {{title}}
    </li>
    {{/each}}
    </ul>
</template>

By default, Meteor uses the Handlebars templating library. In the moviesTemplate above, Handlebars is used to loop through each of the movies using {{#each}}…{{/each}} and display the title for each movie using {{title}}.

The client\movies.js JavaScript file is used to bind the moviesTemplate to the Movies collection on the client. Here’s what this JavaScript file looks like:

// Declare client Movies collection
Movies = new Meteor.Collection("movies");

// Bind moviesTemplate to Movies collection
Template.moviesTemplate.movies = function () {
    return Movies.find();
};

The Movies collection is a client-side proxy for the server-side Movies database collection. Whenever you want to interact with the collection of Movies stored in the database, you use the Movies collection instead of communicating back to the server.

The moviesTemplate is bound to the Movies collection by assigning a function to the Template.moviesTemplate.movies property. The function simply returns all of the movies from the Movies collection.

The final file which we need is the server-side server\movies.js file:

// Declare server Movies collection
Movies = new Meteor.Collection("movies");

// Seed the movie database with a few movies
Meteor.startup(function () {
    if (Movies.find().count() == 0) {
        Movies.insert({ title: "Star Wars", director: "Lucas" });
        Movies.insert({ title: "Memento", director: "Nolan" });
        Movies.insert({ title: "King Kong", director: "Jackson" });
    }
});

The server\movies.js file does two things. First, it declares the server-side Meteor Movies collection. When you declare a server-side Meteor collection, a collection is created in the MongoDB database associated with your Meteor app automatically (Meteor uses MongoDB as its database automatically).

Second, the server\movies.js file seeds the Movies collection (MongoDB collection) with three movies. Seeding the database gives us some movies to look at when we open the Movies app in a browser.

Creating New Movies

Let me modify the Movies Database App so that we can add new movies to the database of movies. First, I need to create a new template file – named client\movieForm.html – which contains an HTML form for creating a new movie:

<template name="movieForm">
    <fieldset>
    <legend>Add New Movie</legend>
    <form>
        <div>
            <label>
                Title:
                <input id="title" />
            </label>
        </div>
        <div>
            <label>
                Director:
                <input id="director" />
            </label>
        </div>
        <div>
            <input type="submit" value="Add Movie" />
        </div>
    </form>
    </fieldset>
</template>

In order for the new form to show up, I need to modify the client\movies.html file to include the movieForm.html template. Notice that I added {{> movieForm }} to the client\movies.html file:

<head>
    <title>My Movie App</title>
</head>

<body>
    <h1>Movies</h1>
    {{> moviesTemplate }}
    {{> movieForm }}
</body>

After I make these modifications, our Movie app will display the form:

clip_image019

The next step is to handle the submit event for the movie form. Below, I’ve modified the client\movies.js file so that it contains a handler for the submit event raised when you submit the form contained in the movieForm.html template:

// Declare client Movies collection
Movies = new Meteor.Collection("movies");

// Bind moviesTemplate to Movies collection
Template.moviesTemplate.movies = function () {
    return Movies.find();
};

// Handle movieForm events
Template.movieForm.events = {
    'submit': function (e, tmpl) {
        // Don't postback
        e.preventDefault();

        // create the new movie
        var newMovie = {
            title: tmpl.find("#title").value,
            director: tmpl.find("#director").value
        };

        // add the movie to the db
        Movies.insert(newMovie);
    }
};

The Template.movieForm.events property contains an event map which maps event names to handlers. In this case, I am mapping the form submit event to an anonymous function which handles the event.

In the event handler, I am first preventing a postback by calling e.preventDefault(). This is a single page app, no postbacks are allowed!

Next, I am grabbing the new movie from the HTML form. I’m taking advantage of the template find() method to retrieve the form field values.

Finally, I am calling Movies.insert() to insert the new movie into the Movies collection. Here, I am explicitly inserting the new movie into the client-side Movies collection. Meteor inserts the new movie into the server-side Movies collection behind the scenes. When Meteor inserts the movie into the server-side collection, the new movie is added to the MongoDB database associated with the Movies app automatically.

If server-side insertion fails for whatever reasons – for example, your internet connection is lost – then Meteor will remove the movie from the client-side Movies collection automatically. In other words, Meteor takes care of keeping the client Movies collection and the server Movies collection in sync.

If you open multiple browsers, and add movies, then you should notice that all of the movies appear on all of the open browser automatically. You don’t need to refresh individual browsers to update the client-side Movies collection. Meteor keeps everything synchronized between the browsers and server for you.

clip_image021

Removing the Insecure Module

To make it easier to develop and debug a new Meteor app, by default, you can modify the database directly from the client. For example, you can delete all of the data in the database by opening up your browser console window and executing multiple Movies.remove() commands.

Obviously, enabling anyone to modify your database from the browser is not a good idea in a production application. Before you make a Meteor app public, you should first run the meteor remove insecure command from a command/terminal window:

clip_image023

Running meteor remove insecure removes the insecure package from the Movie app. Unfortunately, it also breaks our Movie app. We’ll get an “Access denied” error in our browser console whenever we try to insert a new movie. No worries. I’ll fix this issue in the next section.

clip_image024

Creating Meteor Methods

By taking advantage of Meteor Methods, you can create methods which can be invoked on both the client and the server. By taking advantage of Meteor Methods you can:

1. Perform form validation on both the client and the server. For example, even if an evil hacker bypasses your client code, you can still prevent the hacker from submitting an invalid value for a form field by enforcing validation on the server.

2. Simulate database operations on the client but actually perform the operations on the server.

Let me show you how we can modify our Movie app so it uses Meteor Methods to insert a new movie. First, we need to create a new file named common\methods.js which contains the definition of our Meteor Methods:

Meteor.methods({
    addMovie: function (newMovie) {
        // Perform form validation
        if (newMovie.title == "") {
            throw new Meteor.Error(413, "Missing title!");
        }
        if (newMovie.director == "") {
            throw new Meteor.Error(413, "Missing director!");
        }

        // Insert movie (simulate on client, do it on server)
        return Movies.insert(newMovie);
    }

});

The addMovie() method is called from both the client and the server. This method does two things. First, it performs some basic validation. If you don’t enter a title or you don’t enter a director then an error is thrown.

clip_image026

Second, the addMovie() method inserts the new movie into the Movies collection. When called on the client, inserting the new movie into the Movies collection just updates the collection. When called on the server, inserting the new movie into the Movies collection causes the database (MongoDB) to be updated with the new movie.

You must add the common\methods.js file to the common folder so it will get executed on both the client and the server. Our folder structure now looks like this:

clip_image028

We actually call the addMovie() method within our client code in the client\movies.js file. Here’s what the updated file looks like:

// Declare client Movies collection
Movies = new Meteor.Collection("movies");

// Bind moviesTemplate to Movies collection
Template.moviesTemplate.movies = function () {
    return Movies.find();
};

// Handle movieForm events
Template.movieForm.events = {
    'submit': function (e, tmpl) {
        // Don't postback
        e.preventDefault();

        // create the new movie
        var newMovie = {
            title: tmpl.find("#title").value,
            director: tmpl.find("#director").value
        };

        // add the movie to the db
        Meteor.call(
            "addMovie",
            newMovie,
            function (err, result) {
                if (err) {
                    alert("Could not add movie " + err.reason);
                }
            }
       );

    }
};

The addMovie() method is called – on both the client and the server – by calling the Meteor.call() method. This method accepts the following parameters:

· The string name of the method to call.

· The data to pass to the method (You can actually pass multiple params for the data if you like).

· A callback function to invoke after the method completes.

In the JavaScript code above, the addMovie() method is called with the new movie retrieved from the HTML form. The callback checks for an error. If there is an error then the error reason is displayed in an alert (please don’t use alerts for validation errors in a production app because they are ugly!).

clip_image029

Summary

The goal of this blog post was to provide you with a brief walk through of a simple Meteor app. I showed you how you can create a simple Movie Database app which enables you to display a list of movies and create new movies.

I also explained why it is important to remove the Meteor insecure package from a production app. I showed you how to use Meteor Methods to insert data into the database instead of doing it directly from the client.

I’m very impressed with the Meteor framework. The support for Live HTML and Latency Compensation are required features for many real world Single Page Apps but implementing these features by hand is not easy. Meteor makes it easy.

ASP.NET 5/MVC 6 Training

Learn MVC 6 from Stephen Walther. We fly to you!
Learn More

Discussion

  1. Brent Noorda says:

    Very well written. The example you chose shows just enough complexity (i.e. not much) to clarify the issues that meteors own examples left wanting (e.g. why the directory structure, validating at client and server, and handling a “form”). Thanks.

  2. I think there’s a minor error in your write-up. On this page (http://stephenwalther.com/archive/2013/03/18/an-introduction-to-meteor.aspx) search for the phrase, “Notice that I added” and change that sentence:

    From this: Notice that I added {{> movieForm }} to the client\movieForm.html file
    To this: Notice that I added {{> movieForm }} to the client\movies.html file

    That’s as far as I got so far. Very nice blog and tutorial. Thanks for writing it!

  3. Joshua Leasure says:

    This is great! This is an excellently sized chunk for someone just wading into meteor.js (me).

    One very tiny inconsistency… when you create the first batch of custom files the image that immediately follows shows movieForm.html being in the tree even though it hasn’t yet been created. It took me all of 8 seconds to figure out that it would be created later, so hardly important, but everything else was very clean so I figured it was worth pointing out.

  4. Austin says:

    Nice tutorial. Found it from the @meteorjs Twitter account.