JavaScript
Article

Creating a Custom Login and Registration Form with Meteor

By David Turnbull

Right out of the box, one of the simplest things you can do with the Meteor JavaScript framework is to create a user accounts system. Just install a pair of packages — accounts-password and accounts-ui — and you’ll end up with the following, fully-functional interface:

login buttons template

But while this simplicity is convenient, relying on this boilerplate interface doesn’t exactly allow for a lot of flexibility. So what if we want to create a custom interface for our users to register and log into our website?

Luckily, it’s not too difficult at all. In this article I’ll show you how to create a custom login and registration form with Meteor. However, this article assumes that you know how to set up a project using this framework by your own.

To play with the code developed in this article, take a look at the GitHub repository I set up.

Basic Setup

Inside a new Meteor project, add the accounts-password package by executing the command:

meteor add accounts-password

By adding this package to a project a Meteor.users collection will be created to store our user’s data and we won’t have to write custom logic for user-related functions.

So, although creating a custom interface means we’ll lose the convenience of the accounts-ui package, that doesn’t mean we have to lose the convenience of the back-end “magic” that Meteor can provide.

Developing the Interface

For a complete login and registration system, there are a lot of features for which we have to create interfaces for, including:

  • registration
  • login
  • forgot password
  • “confirm your email” page
  • “email confirmed” page

But for the moment, we’ll talk about the first two points listed (registration and login) forms. The reason is that it won’t be difficult for you to figure out how to create the other interfaces once you’ve got a handle on the fundamentals.

The following snippet shows the code of the registration form:

<template name="register">
    <form>
        <input type="email" name="registerEmail">
        <input type="password" name="registerPassword">
        <input type="submit" value="Register">
    </form>
</template>

The next snippet shows the code of the login form instead:

<template name="login">
    <form>
        <input type="email" name="loginEmail">
        <input type="password" name="loginPassword">
        <input type="submit" value="Login">
    </form>
</template>

As you can see, the templates are very similar. They contain a form, the fields for the email and password, and the submit button. The only difference is the value of the name attribute for the input fields and the template. (We’ll reference those values soon, so make sure they’re unique.)

We only want these templates to be shown for a not-yet-logged user. Therefore we can refer to a currentUser object between the opening and closing body tags:

<head>
    <title>Custom Registration Tutorial</title>
</head>
<body>
    {{#if currentUser}}
        <p>You're logged in.</p>
    {{else}}
        {{> register}}
        {{> login}}
    {{/if}}
</body>

This code shows the “You’re logged in” message if the current user is logged in, and the “register” and “login” templates otherwise.

Creating the Events

At the moment, our forms are static. To make them do something, we need them to react to the submit event. Let’s demonstrate this by focusing on the “register” template.

Inside the project’s JavaScript file, write the following:

if (Meteor.isClient) {
    Template.register.events({
        'submit form': function(event) {
            event.preventDefault();
            console.log("Form submitted.");
        }
    });
}

Here, we’ve written code so that the form inside the “register” template:

  1. Responds to the submit event
  2. Doesn’t have any default behavior
  3. Outputs a confirmation message on the console

We’ve also placed this code inside the isClient conditional since we don’t want this code running on the server (as it’s only meant for the interface).

Inside the event, we’ll want to grab the values of the email and password fields, and store them in a pair of variables. So let’s modify the previous code:

Template.register.events({
    'submit form': function(event){
        event.preventDefault();
        var emailVar = event.target.registerEmail.value;
        var passwordVar = event.target.registerPassword.value;
        console.log("Form submitted.");
    }
});

For the “login” template, the code is almost identical:

Template.login.events({
    'submit form': function(event) {
        event.preventDefault();
        var emailVar = event.target.loginEmail.value;
        var passwordVar = event.target.loginPassword.value;
        console.log("Form submitted.");
    }
});

Hooking Things Together

After adding the accounts-password package to the project, a number of methods became available to us:

  • Accounts.createUser()
  • Accounts.changePassword()
  • Accounts.forgotPassword()
  • Accounts.resetPassword()
  • Accounts.setPassword()
  • Accounts.verifyEmail()

We’ll focus on the createUser method but, based on the method names, it’s not hard to figure out the purpose of the other ones.

At the bottom of the submit event for the “register” template, write:

Accounts.createUser({
    // options go here
});

This is the code we can use to create a new user and, by default, it requires two options: an email and a password.

To pass them through, write:

Accounts.createUser({
    email: emailVar,
    password: passwordVar
});

The final code for the event should resemble:

Template.register.events({
    'submit form': function(event) {
        event.preventDefault();
        var emailVar = event.target.registerEmail.value;
        var passwordVar = event.target.registerPassword.value;
        Accounts.createUser({
            email: emailVar,
            password: passwordVar
        });
    }
});

By using this code instead of a generic insert function we have the advantage that passwords are automatically encrypted. Moreover, users are logged in after signing up and we don’t have to write much code.

There is also a loginWithPassword() method that we can use within the “login” event:

Meteor.loginWithPassword();

It also accepts the email and password values:

Meteor.loginWithPassword(emailVar, passwordVar);

And in context, this is what the code should look like:

Template.login.events({
    'submit form': function(event){
        event.preventDefault();
        var emailVar = event.target.loginEmail.value;
        var passwordVar = event.target.loginPassword.value;
        Meteor.loginWithPassword(emailVar, passwordVar);
    }
});

Logging Out

Users can now register and log in but, to allow them to log out, let’s first make a new “dashboard” template that will be shown when logged in:

<template name="dashboard">
    <p>You're logged in.</p>
    <p><a href="#" class="logout">Logout</a></p>
</template>

Then include the following code within the if statement we wrote earlier in this article:

<body>
    {{#if currentUser}}
        {{> dashboard}}
    {{else}}
        {{> register}}
        {{> login}}
    {{/if}}
</body>

Now we can create an event that’s attached to the “logout” link within the “dashboard” template:

Template.dashboard.events({
    'click .logout': function(event){
        event.preventDefault();
    }
});

To execute the logging out process, we only have to use a logout method as such:

Template.dashboard.events({
    'click .logout': function(event){
        event.preventDefault();
        Meteor.logout();
    }
});

Registering, logging in, and logging out should now all work as expected.

Conclusions

We’ve made a good amount of progress with a tiny amount of code, but if we want to create a complete interface for the accounts system, there’s still a lot left to do.

Here’s what I’d suggest:

  1. Enable the verification of new user’s emails.
  2. Validate the creation (and logging in) of users.
  3. Add visual validation to the “register” and “login” forms.
  4. Do something when a login attempt fails.
  5. Allow users to change their password.

It might take an afternoon to figure out the specifics on how to implement these features but, based on what we’ve covered in this tutorial, none of it is out of your reach. Meteor does the hard work for us.

In case you want to play with the code developed in this article, take a look at the GitHub repository I set up.

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.