0
0
ExpressHow-ToBeginner · 4 min read

How to Create a Notification System in Express

To create a notification system in Express, set up API routes to send and retrieve notifications and use Socket.IO for real-time updates. Store notifications in memory or a database, then emit events to connected clients to show new notifications instantly.
📐

Syntax

A basic notification system in Express involves these parts:

  • Express app: Handles HTTP requests.
  • Routes: Endpoints to create and fetch notifications.
  • Socket.IO: Enables real-time communication to push notifications instantly.
  • Storage: Keeps notifications (in memory or database).
javascript
import express from 'express';
import http from 'http';
import { Server } from 'socket.io';

const app = express();
const server = http.createServer(app);
const io = new Server(server);

app.use(express.json());

let notifications = [];

// Route to get notifications
app.get('/notifications', (req, res) => {
  res.json(notifications);
});

// Route to add a notification
app.post('/notifications', (req, res) => {
  const notification = req.body;
  notifications.push(notification);
  io.emit('new-notification', notification); // send to all clients
  res.status(201).json(notification);
});

io.on('connection', (socket) => {
  console.log('User connected');
});

server.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
💻

Example

This example shows a simple Express server with Socket.IO that stores notifications in memory, provides API endpoints to add and get notifications, and pushes new notifications to all connected clients in real time.

javascript
import express from 'express';
import http from 'http';
import { Server } from 'socket.io';

const app = express();
const server = http.createServer(app);
const io = new Server(server);

app.use(express.json());

let notifications = [];

app.get('/notifications', (req, res) => {
  res.json(notifications);
});

app.post('/notifications', (req, res) => {
  const notification = req.body;
  if (!notification.message) {
    return res.status(400).json({ error: 'Message is required' });
  }
  notifications.push(notification);
  io.emit('new-notification', notification);
  res.status(201).json(notification);
});

io.on('connection', (socket) => {
  console.log('User connected');
  socket.on('disconnect', () => {
    console.log('User disconnected');
  });
});

server.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000 User connected User disconnected
⚠️

Common Pitfalls

Common mistakes when creating a notification system in Express include:

  • Not using express.json() middleware, so req.body is undefined.
  • Forgetting to emit notifications via Socket.IO, so clients don't get real-time updates.
  • Storing notifications only in memory without persistence, causing data loss on server restart.
  • Not validating notification data, leading to errors or empty messages.
javascript
/* Wrong: Missing express.json() middleware */
app.post('/notifications', (req, res) => {
  // req.body will be undefined
  const notification = req.body;
  notifications.push(notification);
  io.emit('new-notification', notification);
  res.status(201).json(notification);
});

/* Right: Add express.json() middleware */
app.use(express.json());
📊

Quick Reference

Tips for building notification systems in Express:

  • Use express.json() to parse JSON bodies.
  • Use Socket.IO for real-time notification delivery.
  • Validate incoming notification data before saving.
  • Consider persistent storage (database) for production use.
  • Emit events to all connected clients to update UI instantly.

Key Takeaways

Use Express routes to create and fetch notifications via HTTP.
Integrate Socket.IO to push notifications to clients in real time.
Always parse JSON request bodies with express.json() middleware.
Validate notification data to avoid errors and empty messages.
Store notifications persistently for production-ready systems.