Post on 17-Oct-2015
04/04/14 Tutorial: Writing your first Meteor application - Sebastian Dahlgren
sebastiandahlgren.se/2013/07/17/tutorial-writing-your-first-metor-application/ 1/12
Sebastian Dahlgren
Clouds. Python. JavaScript. Open Source.
RSS
Search
Navigate
BlogArchives
@GitHub@Twitter
Tutorial: Writing your first Meteor application
Jul 17th, 2013 | Comments
Description
We will build a small chat application based on Meteor. It will support anonymous users and users signed in using their GitHub account.
The full example code can be found at https://github.com/sebdah/meteor-chat-tutorial.
The tutorial will cover the basics of:
MeteorMeteorite (package system)Meteor Accounts (user management system)Handebars usage, as that is the default templating system
Before we begin, please open a tab with the Metor Docs. Its a fairly good companion throughout the tutorial.
Install basic requirements
Install Meteor
First off, install Meteor itself by entering the following in your terminal.
1curl https://install.meteor.com | /bin/sh
It will download and install Meteor for you.
Install Meteorite
Meteorite is a packagemanager for Meteor. You can use npm to handle some packages, but Meteorite is a good choice because it supports the user
submitted packages in the Atmosphere repo.
1sudo npm install -g meteorite
Hint: If `npm` is not available, please install Node.JS from http://nodejs.org/ first.
Building the application
Alright, now that you have the basic components installed, lets get started with the actual development.
Project structure
04/04/14 Tutorial: Writing your first Meteor application - Sebastian Dahlgren
sebastiandahlgren.se/2013/07/17/tutorial-writing-your-first-metor-application/ 2/12
Lets create the project
1mrt create chatapp
This command will create a basic Meteor project structure that may suit less complex web apps, but it tend get messy as the projects are growing. Thedefault structure (which you have in your chatapp folder) looks like this:
1234
chatapp.csschatapp.htmlchatapp.jssmart.json
The problem is that code for both the client and server lives is within one .js file with an if clause to separate code from the client and server:
123456789
// Shared code goes here
if (Meteor.isClient) { // Client code}
if (Meteor.isServer) { // Server code}
But Meteor offers an alternative project structure that we will use in this example. So, before we begin lets remove some of the example code generated
by the create command.
12cd chatapprm chatapp.*
Now create two folders instead:
1mkdir client server
Your chatapp folder should now have the following folders and files:
123
client/server/smart.json
As you might have guessed, all code that lives within the client directory will be available for the client (i.e. the browser), while all code under server
will remain on the server side. It is easier (in my opinion) to structure the code like this when the code base grows.
Writing the HTML template
Heres the basic HTML template that we will be building on top of. There are a few things to note here. First of all, theres no doctype or html tags
because Meteor will add that for us. Secondly there are some wierd tags like {{> welcome }}. This is all part of the Handlebars templating system.What is says is that
The template with name=welcome should be inserted at {{>welcome}}
Store the HTML template in a file called client.html in your client folder.
client.html
12345678910111213
Chat app
Chatapp {{> welcome }}
Welcome to the example chat app! Please log in to show your username.
04/04/14 Tutorial: Writing your first Meteor application - Sebastian Dahlgren
sebastiandahlgren.se/2013/07/17/tutorial-writing-your-first-metor-application/ 3/12
14
You can now launch your Meteor app with
12cd chatappmrt
The point your browser at http://localhost:3000. You should see something like this:
You can leave Meteor running, it will automatically update whenever you change a file in the application.
Implementing simple chat functions
Well start writing the actual code for sending messages and we will use the built-in MongoDB database to store all messages.
Create a file called models.js in the chatapp.
models.js
1234
/*** Models*/Messages = new Meteor.Collection('messages');
This will define a new MongoDB collection called messages. Now lets extend our client.html to support messages. Add a new {{> messages}}
tag right under {{> welcome}} and add the following snipped at the end of your HTML code.
client.html
12345
{{#each messages}} {{name}}: {{message}} {{/each}}
Heres some more Handlebars tags that will loop over each message object in a list of messages and print the name and message attributes.
Finally we need to expose the messages list to the messages template. To do that we need to create a new file under client called client.js
client.js
123456
/*** Templates*/Template.messages.messages = function () { return Messages.find({}, { sort: { time: -1 }});}
Lets break down this abit. Template.messages.messages refers to Template... In our case we will
return all documents from MongoDB and sort them on the time attribute.
Sending messages (manually)
Its time to introduce the concept of databases everywhere. In Meteor, the database API is not soley for the backend (server) to use. Its also
exposed to the client using an JavaScript API that simulates MongoDB.
Lets see what it looks like. Run the following in your browsers JavaScript console:
04/04/14 Tutorial: Writing your first Meteor application - Sebastian Dahlgren
sebastiandahlgren.se/2013/07/17/tutorial-writing-your-first-metor-application/ 4/12
123
Messages.insert({name: "Sebastian", message: "My first message", time: Date.now()});Messages.insert({name: "Andrew", message: "Hi!", time: Date.now()});Messages.insert({name: "Sebastian", message: "Yo!", time: Date.now()});
You will now see the messages in your chat app.
This works because we exposed the Messages variable in the models.js to both the client and the server. Therefore we have access to the Messages
variable in the JavaScript console in the browser.
Security warning: This exposes a security hole as any client will be able to modify the database (and delete messages for example). Its of
course possible to fix. Read more at http://docs.meteor.com/#dataandsecurity.
Sending messages
Now well write a function so that anyone can post messages (without using the JavaScript console :)). Extend your HTML template with a new {{>
input}} tag that you place between {{> welcome}} and {{> messages}}. The new looks like this:
client.html
123
Message:
We will now need to catch the event and send the message when the user is pressing enter. Thats all done in the client.js. Add the following just
undet the Template.messages.messages code:
client.js
12345678910111213141516171819
Template.input.events = { 'keydown input#message' : function (event) { if (event.which == 13) { // 13 is the enter key event var name = 'Anonymous'; var message = document.getElementById('message');
if (message.value != '') { Messages.insert({ name: name, message: message.value, time: Date.now(), });
document.getElementById('message').value = ''; message.value = ''; } } }}
04/04/14 Tutorial: Writing your first Meteor application - Sebastian Dahlgren
sebastiandahlgren.se/2013/07/17/tutorial-writing-your-first-metor-application/ 5/12
Template.input.events is the callback for all events triggered withing the input template. In this case were listening to keydown input#message
which means any time a key is pressed with in the input#message selector. The syntax for the events are event selector.
You can now write messages directly in your app!
Add user authentication
Before we start writing the actual code for user authentication we need to install accounts-ui and accounts-github to support the user management
and OAuth signing with GitHub. Run the following in your chatapp folder.
12mrt add accounts-uimrt add accounts-github
The accounts-ui package is bundled with a UI for us to use right out of the box. Just add {{loginButtons align="right"}} just above
Chatapp in your client.html file. Your HTML should now look like this:
client.html
123456789101112131415161718192021222324252627
Chat app
{{loginButtons align="right"}} Chatapp {{> welcome }} {{> input }} {{> messages }}
Welcome to the example chat app!
{{#each messages}} {{name}}: {{message}} {{/each}}
Message:
Lets throw some CSS on this app. Create a client.css file under client with the following code:
client.css
12345678
html { padding: 10px; font-family: Verdana, sans-serif;}
.login-buttons-dropdown-align-right { float: right;}
We should also make sure to store the name of the user is the messages database, currently we have hard coded Anonymous as the name for all users.
Update the Template.input.events to look like this:
client.js
12345678910111213
Template.input.events = { 'keydown input#message' : function (event) { if (event.which == 13) { // 13 is the enter key event if (Meteor.user()) var name = Meteor.user().profile.name; else var name = 'Anonymous'; var message = document.getElementById('message');
if (message.value != '') { Messages.insert({ name: name, message: message.value,
04/04/14 Tutorial: Writing your first Meteor application - Sebastian Dahlgren
sebastiandahlgren.se/2013/07/17/tutorial-writing-your-first-metor-application/ 6/12
141516171819202122
time: Date.now(), });
document.getElementById('message').value = ''; message.value = ''; } } }}
Meteor.user() will hold profile information about the currenly signed in user. If no user is signed in it will return null. So now were storing the users
full name in the database rather than just Anonymous.
Open your application in a browser. You will see that the GitHub login button is red. This is because you will need to configure the GitHub OAuth thefirst time you use it. Just click the button and follow the instructions in order to get your Client ID and Client Secret from GitHub.
When this is all done you should be able to login to the chat app using your GitHub credentials.
Test it in two browsers
Now, just to test the actual chatting, open another browser and point at http://localhost:3000 as well. Do not log in with this second browser. You should
04/04/14 Tutorial: Writing your first Meteor application - Sebastian Dahlgren
sebastiandahlgren.se/2013/07/17/tutorial-writing-your-first-metor-application/ 7/12
now have two different browsers. One logged in with your GitHub account and one that is not logged in at all.
Then try to write some messages and see that they are popping upp in the other window directly (without having to reload).
Full code
To get the full code please checkout https://github.com/sebdah/meteor-chat-tutorial/tree/master/chatapp.
If you liked this tutorial, star it!
If you liked this tutorial, please star the repo at https://github.com/sebdah/meteor-chat-tutorial. Thanks!
Posted by Sebastian Dahlgren Jul 17th, 2013 javascript, meteorjs
TweetTweet 96 23
Password confirmation in WTForms Add routing to Meteor JS
Comments
38 Comments Sebastian Dahlgren's blog Login
Sort by Best Share
Join the discussion
Reply
Christian Fei 7 months ago
Hey Sebastian, nice tut!
I wanted to post here this comment to let people know about a similar, yet fully featured realtime web chat built with Meteor called
'OpenTalk' at http://opentalk.me
I made the source code available here https://github.com/christian-f...
Would love to know what you think
4
sebastiandahlgren 7 months agoMod Christian Fei
Great work Christian! I like the look and feel :).
Favorite
Share
39 people like this.LikeLike ShareShare
04/04/14 Tutorial: Writing your first Meteor application - Sebastian Dahlgren
sebastiandahlgren.se/2013/07/17/tutorial-writing-your-first-metor-application/ 8/12
Reply
I'd suggest that you add a list of popular or active chat rooms on the start page to get people started.
Keep up the good work!
Reply
Christian Fei 7 months ago sebastiandahlgren
Thanks Sebastian, I will certainly consider your suggestion!
Reply
Frankiezzy 3 months ago
Best tutorial I've read & followed so far. Thank you very much. Looking forward to reading more of your MeteorJS tutorials
1
Reply
Thomas Schmidt 4 months ago
This tutorial is so great. I like that you build everything step by step from scratch rather than taking an example application.
1
Reply
sebastiandahlgren 4 months agoMod Thomas Schmidt
Thank you for the feedback, I really appreciate it.
1
Reply
jtnix 20 hours ago
neat, but what happened to server/ ? seems like a red-herring... to be continued??
Reply
sebastiandahlgren 14 hours agoMod jtnix
I do not really get what you mean, there is no real server part (or at least no server-side code) in this application, so there is
no server/ directory?
Sorry if I misunderstood you!
Reply
Graham a day ago
When I tried to add {{loginButtons}}, I kept getting a blank page, and I was close to giving up trying to learn Meteor. Even copying the
code in this tutorial directly didn't work!
Finally I looked at the console, and found that I have to use {{> loginButtons}} instead of {{loginButtons}}. I don't know if this is a recent
change, but none of the tutorials I've looked at use the ">".
Reply
sebastiandahlgren 20 hours agoMod Graham
That is likely due to the release of MeteorJS 0.8. Check out http://docs.meteor.com/#accoun.... I'll see if I can review the
example app to suite MeteorJS 0.8 Did you find any other issues?
Reply
Kevin Paul 3 days ago
Im new to meteor and this tutorial is really good! I did every step exept I used facebook auth instead of the github.
Thanks for this tutorial and nice work!
Reply
Luiz Jos de Lemos 16 days ago
Congrats @sebastiandahlgren great tuto. Thanks! :)
Reply
sebastiandahlgren 16 days agoMod Luiz Jos de Lemos
Thanks @Luiz Jos de Lemos, much appreciated with the feedback :)
Aaron Stromberg 2 months ago
Hi Sebastian! Thought the tutorial was the bomb, totally killed it. I'm also having log-in issues with newer versions of meteor. I log in,
don't receive any errors, but my account information doesn't appear to actually get pulled, and I'm still coming up as anonymous. I'm
running Meteor 0.7.0.1 and Meteorite 0.7.0.1. I heard the accounts-ui was changed again, so I would not be surprised if this has
something to do with it. Anyway, I'm too lazy to figure out exactly what needs to be changed (if indeed I'm correct it fails with this
version, and I am not the mistake), I got exactly what I wanted out of this tutorial, and that was a great introduction to Meteor! Kudos
and much love!
Share
Share
Share
Share
Share
Share
Share
Share
Share
Share
Share
Share
04/04/14 Tutorial: Writing your first Meteor application - Sebastian Dahlgren
sebastiandahlgren.se/2013/07/17/tutorial-writing-your-first-metor-application/ 9/12
Reply
and much love!
Reply
sebastiandahlgren 2 months agoMod Aaron Stromberg
Thanks for your kind words Aaron, glad that you liked the tutorial!
Happy Meteor hacking :)
1
Reply
lt 4 months ago
great tutorial. had fun following along.
Reply
aidanxyz 4 months ago
It was really easy to read and understand! Thanks so much!)
Reply
sebastiandahlgren 4 months agoMod aidanxyz
Great, thank you so much aidanxyz :)
Reply
JGallardo 5 months ago
This is an excellent tutorial thank you so much.
By the way, even though Iogged in with Github. I was still showing up as anonymous. How exactly do we pull in their names from their
github profile?
Reply
sebastiandahlgren 5 months agoMod JGallardo
That seems a bit strange. The user's name is fetched from GitHub using the Meteor package called accounts-github (so it's
part of the MeteorJS core offering). Does you user have a first / last name defined at GitHub? I'm not really sure what would
be displayed in case the GitHub profile does not have first or last name defined, but I would really expect e.g. the username to
be displayed.
Reply
JGallardo 5 months ago sebastiandahlgren
This is my repo
https://github.com/JGallardo/t...
and I logged in with my own github account. so expected to see my name.
thank you.
Reply
sebastiandahlgren 5 months agoMod JGallardo
You're missing some parts of the client.js above. Compare your client.js with mine here
https://github.com/sebdah/mete.... Look specifically for the name variable.
1
Reply
Guest 5 months ago
Not sure what I missed here. in the beginning you tell us to remove all the files with the command
rm chatapp.*
but then I got this error:
Your app is crashing. Here's the latest log.
=> Errors prevented startup:
While building the application:
client/client.html:21: bad formatting in HTML template
=> Your application has errors. Waiting for file change.
sebastiandahlgren 5 months agoMod Guest
The removal of chatapp.* is not related to the error below. It's simply some syntactical error in your HTML file. Please double
check with the client.html above or by checking our the example code from GitHub (https://github.com/sebdah/mete....
Share
Share
Share
Share
Share
Share
Share
Share
Share
Share
04/04/14 Tutorial: Writing your first Meteor application - Sebastian Dahlgren
sebastiandahlgren.se/2013/07/17/tutorial-writing-your-first-metor-application/ 10/12
Reply
Reply
ay13 5 months ago
Just followed this tutorial and when you are logged in via github your name does not appear next to the sign out button and every time
you type a message the name is 'null' instead of your name. I dont know if there was a change since you published this but wanted to
bring to your attention.
Meteor: 0.6.6.2
Meteorite: 0.6.15
Reply
Christoph Geschwind 5 months ago ay13
That is the case if you don't set a public name on your profile. You can alternatively use the nickname from
'services.github.username'
Reply
Joe Cullin 2 months ago Christoph Geschwind
I ran into the same issue, since I was using a newly-created github account. I then filled out my profile info in Github,
but still had the same null display in the demo app. Then I realized that meteor seems to pull the profile details once
and store them. So it was still re-using the null details that it had originally gotten from github. I wiped all my data (just
used "meteor reset"), tried again with the same github account, and now my name displays correctly.
Thanks for the great tutorial, Sebastian.
Reply
sebastiandahlgren 2 months agoMod Joe Cullin
Ah, nice spotted Joe. Thanks for sharing!
Reply
sebastiandahlgren 5 months agoMod ay13
Thanks for the input. It should work fine, but I will test it later today!
Reply
Eliezer 6 months ago
Is there a way as simple as adding Github login to add FB or Google login?
Reply
Eliezer 6 months ago Eliezer
Found the answer here:
http://docs.meteor.com/#accoun...
Just as easy to add FB or Google login. (I was looking in the wrong place before).
Reply
sebastiandahlgren 6 months agoMod Eliezer
Yeah, it's just as easy, as you found out. Although I want to see a good way to combine the user accounts in the
background if you are using many of the services to authenticate your users.
Reply
Eliezer 6 months ago
Excellent tutorial. So so simple. (Both the tut and Meteor).
Reply
sebastiandahlgren 6 months agoMod Eliezer
Thank you so much Eliezer! Glad you enjoyed it :)
Reply
ference 8 months ago
Excellent tutorial keeping it simple and relate-able with a tangible example. I finally have the gist of templates, handlebars, and
collections. Muchas Gracias!
Reply
sebastiandahlgren 8 months agoMod ference
Thank you Ference, glad that it came to use :)
Share
Share
Share
Share
Share
Share
Share
Share
Share
Share
Share
Share
Share
04/04/14 Tutorial: Writing your first Meteor application - Sebastian Dahlgren
sebastiandahlgren.se/2013/07/17/tutorial-writing-your-first-metor-application/ 11/12
MongoDB pipeline for Scrapy - Sebastian Dahlgren
4 comments 9 months ago
sebast iandahlgren Thanks, Delbor! I have fixed the typo
now :)
Accessing GitHub user data in Meteor client
2 comments 5 months ago
sebast iandahlgren I write almost everything in Sublime Text
3. It's a pretty good tool. http://www.sublimetext.com/3 However,
I do not
Using Celery to handle asynchronous tasks in Django
2 comments a year ago
sebast iandahlgren Thank you Stefan!
Bootstrap3 with accounts support in MeteorJS
1 comment 3 months ago
Manea Eugen why mrt add accounts-ui-bootstrap-3 is
adding :( #login-buttons {display: none;}
ALSO ON SEBASTIAN DAHLGREN'S BLOG
Reply
Rich 9 months ago
Really great tutorial Sebastien, thanks!
It has motivated me to go and learn as much as possible about Meteor as it seems so much more powerful than express for
example, almost angular js power within a full blown framework. Very exciting. In fact, on to the next tutorial here as I've just seen the
title is about routing. Perfect. Much appreciated.
Just one bug in this tutorial is that the first time the input is added it has a 'name' instead of an 'id' and so the live update and keydown
don't work unless you overwrite all your code as you go through which I didn't.
Many thanks again
Rich
Reply
sebastiandahlgren 9 months agoMod Rich
Thanks for the comment Rich! I'm happy that you liked the tutorial.
I have corrected the name/id issue now. Thanks for pointing it out!
WHAT'S THIS?
Subscribe Add Disqus to your site
Share
Share
Tag Cloud
awk(1) aws(10) bash(2) bootstrap(1) celery(1) cloudformation(1) datatables(1) django(3) documentation(1) dynamodb(8) ebs(1)ec2(1) flask(1) git(2) github(1) javascript(5) jekyll(3) jquery(1) json(1) linux(1) markdown(1) meteorjs(5) mongodb(1) nodejs(1)
octopress(1) paramiko(1) python(17) scrapy(1) ssh(1) Sublime(1) sublime(1) testing(1) travis-ci(1) windows(1) wtforms(1)
GitHub Repos
dynamic-dynamodb
Dynamic DynamoDB provides auto scaling for AWS DynamoDB
scrapy-mongodb
MongoDB pipeline for Scrapy. This module supports both MongoDB in standalone setups and replica sets. This module will insert the items to
MongoDB as soon as your spider finds data to extract.
meteor-autocompletion
Autocompletion using data from MeteorJS collections
git-pylint-commit-hook
04/04/14 Tutorial: Writing your first Meteor application - Sebastian Dahlgren
sebastiandahlgren.se/2013/07/17/tutorial-writing-your-first-metor-application/ 12/12
Git pre-commit hook to check Python code quality with pylint. You can use this hook to prohibit Python code with a bad syntax to be checked in.
github-kanban
meteor-chat-tutorial
Example Meteor chat application supporting GitHub authentication.
chartista.js
JavaScript library for graphing
watchtower
Pythonic monitoring software
markdown-docs
markdown-docs is a documentation generator for projects using Markdown. The problem with having Markdown files spread around your
project is that it is hard to get an overview of all your documentation. markdown-docs solves this by collecting all of your Markdown files into one
browsable HTML hierarchy.
yayson
Yay! Beautiful JSON on the command line!
password-generator
Simple password generator module for Python
python-inspector
Used to track down which Python module and script that called your method / function. It will show you the exact Python file, line number and the
actual line that made the call. The module is plug'n'playable, just import it and place a non-interfering hook in your code.
elliot.js
Near real time graph library, see web page or demo.html for examples
relic
AWS Cloud management tool written in Python 2.7 and Django
gitstats
scripture
Scripture is a project for easy log management. The initial goal of the project is to simplify the logging from Python applications via a queue toAWS S3 or to file. Even though Python + S3/file logging is the initial step, we will implement more languages and backends as the project moves
forward.
beaver
Booking system
answering-robot
Fooling around with Python and text searching
@sebdah on GitHub
Copyright 2014 - Sebastian Dahlgren - Powered by Octopress