I work on an existing Django application, and during a recent hack week, wanted to toy with the idea of adding user notifications. There are definitely customer use cases for this, but it was also a good excuse for me to try out some new technologies! I was able to get a proof of concept working in a couple days, and had a lot of fun doing it, so thought I’d share what I built!
Goal: when a specific thing happens somewhere in the system that creates a notification for a user, immediately increase the count in their notification bubble in the header, or if this is their first unread notification, make the notification bubble appear (without any page reloads).
Context & Caveats
Because this was a hack week project, it’s not in production (and I don’t expect that it’s production-ready…I didn’t even make any attempts at security).
This was my first foray into both Node and websockets, so it’s entirely possible that my implementation has some newbie mistakes in it. I’m writing this because I had fun working on it, I learned a lot…and because I’d love to learn more! So if you’ve done something like this before or just have ideas on how to do it better, I’d love to hear them!
The High Level
If you’re new to the idea of websockets entirely, and unsure how they work technically, I found this blog from Treehouse to be a good introduction, or for more technical depth on the protocol, this introduction from Mozilla.
So in order to make notifications work in our existing Django application, here are the pieces we’ll need (we’ll go into more depth into each of these later):
- New Node.js app that runs the websocket server
- User’s browsers opens websocket connections to said server on page load, identified by their unique user ID
- Django signals that listen for qualifying events: when one is received, it sends an HTTP request to an endpoint on the Node server, which includes the ID of the user we want to notify
- When the Node app receives that request, it finds the user’s socket connection, using the ID, and sends a message
- When the user’s browser receives that message, it can edit the HTML on the user’s browser to add the notification!