How to add realtime notifications to your Node.js app
To follow this tutorial you will need Node 6+, npm 3.8.6+ and MongoDB 3.4+ installed on your machine.
Realtime notifications are useful in social and other apps where all or some users need to be immediately aware when events they might be interested in occur. With the Web Notifications API (supported by most modern browsers), combined with Pusher’s realtime messaging model, it’s easy to notify your users almost instantly when something they should know about occurs.
In this tutorial, we’ll demonstrate how we can add realtime notifications to a Node.js app. The app we’ll build is similar to Wikipedia: it shows a list of posts that anyone can read and edit. Unlike Wikipedia, though, the app notifies everyone who’s anywhere in the app whenever you edit a page. (For this reason, we’ll call the app Tattletale**.**) Here’s a preview of the app in action:
You can check out the source code of the completed application on GitHub.
Requirements
- Node.js (version 6.0.0 or higher) and NPM (version 3.8.6 or higher). Get Node here (NPM’s included).
- MongoDB (version 3.4 or higher). Get it here.
Set up the project
We’ll be using the Express framework. First, install the Express app generator to quickly set up our app:
npm install express-generator -g
Next, create a new Express app with the view engine set to Handlebars (hbs):
express --view=hbs tattletale
Then we’ll install our dependencies, and add some more modules we’ll need:
cd tattletale && npm install
npm install --save dotenv faker mongoose pusher
Here’s a breakdown of what each module is for.
- dotenv: package for loading private configuration variables (namely our Pusher app credentials) from a
.env
file. - faker: module for generating fake data we can seed into our database.
- mongoose: an ORM for MongoDB that maps our models (JavaScript objects) to MongoDB documents.
- pusher: library for interacting with Pusher’s APIs.
We’ll store posts in a posts collection. A single item in this collection will contain a title and a body. Let’s define our Post
model. Create a directory called models
, and create a file in it called post.js
with he following content:
let mongoose = require('mongoose');
let Post = mongoose.model('Post', {
title: String,
body: String
});
module.exports = Post;
Next up, let’s populate our database with some fake posts. Create a file called seed.js
in the bin
directory, with the following content:
require('mongoose').connect('mongodb://localhost/tattletale');
const faker = require('faker');
const Post = require('../models/post');
// empty the collection first
Post.remove({})
.then(() => {
const posts = [];
for (let i = 0; i < 5; i++) {
posts.push({
title: faker.lorem.sentence(),
body: faker.lorem.paragraph()
});
}
return Post.create(posts);
})
.then(() => {
process.exit();
})
.catch((e) => {
console.log(e);
process.exit(1);
});
Run the seed using node
(remember to start your MongoDB server by running mongod
first):
node bin/seed.js
Displaying posts
Let’s implement our views and routes. Our home page will display a list of post titles. Clicking on a title will open the post for viewing. On the single post page, there’ll also be an Edit button that makes the post editable. Let’s get to work!
First, we’ll add our MongoDB connection setup to our app.js
, so the connection gets created when our app starts. Above this line:
module.exports = app;
Add this:
require('mongoose').connect('mongodb://localhost/tattletale');
Next, let’s write the route that retrieves all posts from the database and pass them to the view. We’ll also write the route that renders a single post. Replace the code in routes/index.js
with this:
const router = require('express').Router();
const Post = require('./../models/post');
router.get('/', (req, res, next) => {
Post.find({}, {title: true}).exec((err, posts) => {
res.render('index', { posts });
});
});
router.get('/posts/:id', (req, res, next) => {
Post.findOne({ _id: req.params.id }).exec((err, post) => {
res.render('post', { post });
});
});
module.exports = router;
Let’s create our views.
Put the following code in the views/layout.hbs
file:
<!DOCTYPE html>
<html lang='en'>
<head>
<title>{{title}}</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<!-- jQuery for easy DOM manipulation -->
<script src="https://code.jquery.com/jquery-3.3.0.min.js"
integrity="sha256-RTQy8VOmNlT6b2PIRur37p6JEBZUE7o8wPgMvu18MC4="
crossorigin="anonymous">
</script>
<!-- Axios for AJAX requests -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div class="container" style="padding: 50px;">
{{{body}}}
</div>
</body>
</html>
Add the following to the views/index.hbs
file:
<div class="row">
<h2>Posts</h2>
</div>
<div class="list-group">
{{#each posts }}
<a href="/posts/{{ this._id }}" class="list-group-item">
{{ this.title }}
</a>
{{/each}}
</div>
Place the code below in a file called post.hbs
in the views
directory:
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1>{{ post.title }}</h1>
<p id="post-body">{{ post.body }}</p>
<p id="actions">
<a class="btn btn-primary btn-lg" href="#" id="edit-btn" role="button">Edit</a>
</p>
</div>
</div>
Editing posts
On the single post page, when a user clicks the Edit button, the post body should become editable, and Save and Cancel buttons should replace the Edit button.
Let’s update our views and routes to support editing of posts. First, in our routes/index.js
, the route for saving changes to the post:
router.post('/posts/:id', (req, res, next) => {
Post.findByIdAndUpdate(req.params.id, {body: req.body.body}, (err, post) => {
res.send('');
});
});
Add the following code to the single post view, views/post.hbs
:
<script>
var postId = "{{ post._id }}";
var postContent;
var makeEditable = function (event) {
// capture the content of the post, then replace with editable textarea
postContent = $("#post-body").html();
var editableText = $('<textarea id="editable-post-body" class="form-control" />');
editableText.val(postContent);
$("#post-body").replaceWith(editableText);
editableText.focus();
var saveBtn = $('<a class="btn btn-primary btn-lg" id="save-btn" role="button">Save</a>');
var cancelBtn = $('<a class="btn btn-info btn-lg" id="cancel-btn" role="button">Cancel</a>');
saveBtn.click(function () {
// capture the new post content and send to backend
postContent = $("#editable-post-body").val();
axios.post("/posts/" + postId, { body: postContent });
restoreBody();
});
cancelBtn.click(restoreBody);
// replace "Edit" button with "Save" and "Cancel"
$("#actions").html([saveBtn, cancelBtn]);
};
$('#edit-btn').click(makeEditable);
var restoreBody = function() {
var postBody = $('<p id="post-body"></p>');
postBody.html(postContent);
$("#editable-post-body").replaceWith(postBody);
var editBtn = $('<a class="btn btn-primary btn-lg" href="#" id="edit-btn" role="button">Edit</a>');
editBtn.click(makeEditable);
$("#actions").html(editBtn);
};
</script>
At this point, the app is fairly functional. Start the app by running npm start
. Visit the app on http://localhost:3000. You should be able to view all posts, view a single post, and edit it (see the GIF below).
Adding notfications
Now let’s add the realtime notification capability.
The first thing you’ll need to do is to create a Pusher account if you don’t already have one (it’s free). Then create an app and obtain your app credentials from the app dashboard. Create a file named .env
in the root of your project with the following content:
PUSHER_APP_ID=YOUR_APP_ID
PUSHER_APP_KEY=YOUR_APP_KEY
PUSHER_APP_SECRET=YOUR_APP_SECRET
PUSHER_APP_CLUSTER=YOUR_APP_CLUSTER
Replace YOUR_APP_ID
, YOUR_APP_KEY
, YOUR_APP_SECRET
, and YOUR_APP_CLUSTER
with your Pusher app ID, app key, app secret and cluster respectively.
Then add this line to the top of your app.js
. This is to setup dotenv
so it pulls environment variables from our .env
file:
require('dotenv').config();
Modify your routes/index.js
so the endpoint for editing a post looks like this:
router.post('/posts/:id', (req, res, next) => {
Post.findByIdAndUpdate(req.params.id, {body: req.body.body}, (err, post) => {
let Pusher = require('pusher');
let pusher = new Pusher({
appId: process.env.PUSHER_APP_ID,
key: process.env.PUSHER_APP_KEY,
secret: process.env.PUSHER_APP_SECRET,
cluster: process.env.PUSHER_APP_CLUSTER
});
pusher.trigger('notifications', 'post_updated', post, req.headers['x-socket-id']);
res.send('');
});
});
You’ll notice we include a fourth parameter in our call to pusher.trigger
. This is the socket ID, a unique identifier that Pusher assigns to each client connection (in this case, every new window where our app is opened). The socket ID is sent from the frontend via an X-Socket-Id
header. By passing the socket ID to pusher.trigger
, we are ensuring that the client with that ID will not get notified. This is what we want, since that window has already updated its UI.
Let’s add the frontend code that responds to the events. We want to respond in two ways when a post_updated
event comes in:
- A browser notification should pop up. When the notification is clicked, it should open the edited post.
- On the home page, an Updated badge should also appear next to the list item corresponding to the post that was updated.
Since both pages in our app use this functionality, we’ll place it in within the body tags of views/layout.hbs
:
<script src="https://js.pusher.com/4.1/pusher.min.js"></script>
<script>
var pusher = new Pusher('your-app-key', { cluster: 'your-app-cluster' });
// retrieve the socket ID once we're connected
pusher.connection.bind('connected', function () {
// attach the socket ID to all outgoing Axios requests
axios.defaults.headers.common['X-Socket-Id'] = pusher.connection.socket_id;
});
// request permission to display notifications, if we don't alreay have it
Notification.requestPermission();
pusher.subscribe('notifications')
.bind('post_updated', function (post) {
// if we're on the home page, show an "Updated" badge
if (window.location.pathname === "/") {
$('a[href="/posts/' + post._id + '"]').append('<span class="badge badge-primary badge-pill">Updated</span>');
}
var notification = new Notification(post.title + " was just updated. Check it out.");
notification.onclick = function (event) {
window.location.href = '/posts/' + post._id;
event.preventDefault();
notification.close();
}
});
</script>
Remember to replace your-app-i
d with your Pusher app ID and your-app-cluster
with your app cluster.
All done! Start up your MongoDB server by running mongod
, serve your app with npm start,
and visit your app on http://localhost:3000 in two browser windows. It should work just like the preview shown earlier. Editing a post in one window immediately notifies the other.
Conclusion
We’ve seen how straightforward it is to add realtime push notifications to a web app, thanks to the Web Notifications API and Pusher realtime messaging. Our demo app is a simple example. The same functionality could be used in many real world scenarios (for instance, an internal company tool where realtime updates are important). You can check out the source code of the completed application on GitHub, read up more about Web Notifications here, and dive deeper into Pusher services here.
6 June 2018
by Shalvah Adebayo