# What You’ll Build and Why It Matters#
"Next.js real-time notifications" sounds simple until you hit production constraints: serverless timeouts, fanout costs, reconnection storms, and users who miss events while offline.
This guide shows a pragmatic architecture that works with the Next.js App Router: real-time delivery via SSE or WebSockets, persistence via an inbox table, read states, and a fallback polling strategy using React Query or SWR. You’ll also learn how to choose between SSE and WebSockets for notification delivery and presence-like features, including scaling constraints.
If you want a broader overview of real-time options in Next.js, read Next.js real-time features with WebSockets, SSE, and Supabase Realtime.
# Prerequisites#
| Requirement | Version | Notes |
|---|---|---|
| Next.js | 14 or 15 | App Router examples assume modern route handlers |
| Node.js | 18+ | 20+ recommended in 2026 for performance and security updates |
| Database | Postgres recommended | Needed for inbox persistence and read state |
| Cache or pub-sub | Redis or managed pub-sub | Used for fanout across instances |
| Basic auth | Any | Examples assume you can identify a user ID on the server |
# Architecture Overview: Don’t Ship Notifications as “Just Events”#
Real-time transport is not the product. Notifications are a product feature with UX and reliability requirements.
A production-ready model usually includes:
- 1Durable inbox for every user, backed by a database table.
- 2Real-time transport to reduce perceived latency.
- 3Idempotent delivery so reconnects do not create duplicates.
- 4Read/unread state with timestamps and optional per-device semantics.
- 5Fallback polling for environments where real-time connections fail.
- 6Observability so you can debug missed notifications and latency.
🎯 Key Takeaway: Real-time transport is an optimization. Delivery guarantees come from persistence plus reconciliation.
# SSE vs WebSockets for Next.js Real-Time Notifications#
SSE and WebSockets solve different problems. Notifications are usually server-to-client, bursty, and tolerant to small delays. Presence-like features are bidirectional and require frequent client-to-server heartbeats.
Comparison Table: Notifications, Presence, and Scaling Constraints#
| Criteria | SSE | WebSockets |
|---|---|---|
| Direction | Server to client | Full duplex |
| Best for | Notifications, feeds, status updates | Presence, chat, collaborative cursors, typing indicators |
| Browser support | Excellent | Excellent |
| Proxy friendliness | Very good, uses HTTP | Sometimes problematic with corporate proxies |
| Reconnect behavior | Built-in retry and Last-Event-ID patterns | You must implement backoff and resubscribe logic |
| Message framing | Text only by default | Binary and text |
| Cost profile | One HTTP connection per client | One socket per client, often more infra |
| Serverless compatibility | Depends on platform support for streaming responses | Often requires specialized WS support or managed service |
| Presence accuracy | Limited | Strong, via heartbeats and server-side state |
| Delivery guarantees | Not built in | Not built in |
SSE for Notifications: Why It Often Wins#
SSE is typically the simplest way to ship "Next.js real-time notifications" when you only need server-to-client events:
- Runs over HTTP, usually plays nicely with load balancers and proxies.
- Automatic reconnect behavior in browsers makes it resilient.
- The mental model is closer to "stream of events" than a socket protocol.
Where SSE can hurt:
- Scaling: you still maintain one open connection per client, which affects memory and file descriptors.
- Multi-instance fanout: you need a shared pub-sub layer, otherwise each instance only knows about its own connected clients.
- Presence: without client-to-server heartbeats, SSE alone cannot reliably track online status.
WebSockets for Presence and Interactive Real-Time#
Use WebSockets when you need:
- Presence, last-seen, and accurate "online now" indicators
- Two-way events like "mark as read" without additional HTTP calls
- High-frequency client events, like collaborative updates
Where WebSockets can hurt:
- Infrastructure complexity: sticky sessions or shared state, plus careful backpressure handling.
- Serverless limitations: long-lived sockets do not fit basic serverless request lifecycles.
- Reconnection semantics: you must design resubscribe flows, replay, and idempotency.
⚠️ Warning: If you implement WebSockets and ship ephemeral events only, users will miss notifications when offline. Always add an inbox and reconcile on reconnect.
# Delivery Guarantees: What You Can and Can’t Promise#
Most teams want “exactly once delivery.” In real-world networks, "exactly once" is expensive and often not needed.
A pragmatic target is:
- At least once to the inbox: persisted notification exists once, uniquely identified.
- At least once real-time: the UI may receive duplicates, but the client deduplicates by ID.
- Eventually consistent read state: read/unread is correct after retries and reconciliation.
Define Your Notification States Explicitly#
If you do not model delivery, you cannot debug delivery.
Common states and timestamps:
| Field | Type | Why it matters |
|---|---|---|
created_at | timestamp | Sorting and auditing |
delivered_at | timestamp nullable | Optional, indicates a device saw it |
read_at | timestamp nullable | Unread count and UX |
archived_at | timestamp nullable | Optional, for inbox cleanup |
client_last_seen_id | bigint or uuid | Helps reconcile missed events |
# Data Model: Inbox Table and Read State Patterns#
A single "notifications" table is not enough when multiple users can receive the same event (fanout), and when read state is per recipient.
A proven approach:
notification_eventsstores the canonical event payload once.notification_inboxstores per-user delivery and read state.
Recommended Tables#
| Table | Key columns | Purpose |
|---|---|---|
notification_events | id, type, payload, created_at | Immutable event data |
notification_inbox | id, user_id, event_id, read_at, created_at | Per-user inbox row |
notification_devices (optional) | id, user_id, device_id, last_seen_at | Per-device read sync and delivery metrics |
Example Postgres DDL (Minimal)#
CREATE TABLE notification_events (
id uuid PRIMARY KEY,
type text NOT NULL,
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE notification_inbox (
id uuid PRIMARY KEY,
user_id uuid NOT NULL,
event_id uuid NOT NULL REFERENCES notification_events(id),
read_at timestamptz NULL,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (user_id, event_id)
);
CREATE INDEX notification_inbox_user_created_idx
ON notification_inbox (user_id, created_at DESC);This enables:
- Deduplication per user via
UNIQUE (user_id, event_id) - Fast unread counts with
WHERE read_at IS NULL - Replay from DB when the client reconnects
💡 Tip: Keep
notification_events.payloadcompact. Large payloads inflate both DB and network costs. Store IDs and fetch details lazily when the user opens the notification.
# Fanout Patterns: How Notifications Reach Many Users#
Fanout means one event might be delivered to thousands of inboxes.
You have three common options:
Option A: Fanout on Write (Immediate Inbox Insert)#
When an event happens:
- 1Insert into
notification_events - 2Insert one
notification_inboxrow per recipient user - 3Publish a real-time signal per recipient or per channel
Pros:
- Simple reads: inbox query is direct.
- Reliable: the DB is the source of truth.
Cons:
- Heavy write amplification for large recipient sets.
- Needs background jobs for very large fanout.
Option B: Fanout on Read (Dynamic Querying)#
Store only the event, and compute recipients at read time.
Pros:
- Low write amplification.
Cons:
- Complex queries, harder to track read state per user.
- Difficult to reason about delivery guarantees.
Option C: Hybrid with Background Jobs#
Write the event, enqueue fanout inserts, and publish a real-time hint.
Pros:
- Scales better with big audiences.
- Lets you rate-limit and batch inserts.
Cons:
- More moving parts: queue, retries, idempotency keys.
For most B2B apps, Option A is fine up to moderate scale. If you regularly notify more than 10,000 users per event, you want Option C with batching and backpressure.
# Implementing SSE in Next.js App Router#
SSE is built on streaming a response and writing data: lines. Next.js route handlers can do this on Node runtimes that support streaming.
SSE Route Handler Example#
// app/api/notifications/stream/route.ts
export const runtime = "nodejs";
export async function GET() {
const stream = new ReadableStream({
start(controller) {
const encoder = new TextEncoder();
const send = (obj: unknown) => {
controller.enqueue(encoder.encode(`data: ${JSON.stringify(obj)}\n\n`));
};
send({ type: "connected", ts: Date.now() });
const interval = setInterval(() => {
send({ type: "ping", ts: Date.now() });
}, 25000);
const cleanup = () => clearInterval(interval);
// No request abort signal in this minimal snippet
// In production, stop on disconnect and unsubscribe from pub-sub
return cleanup;
},
});
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache, no-transform",
Connection: "keep-alive",
},
});
}This example only pings. In production you will subscribe to a pub-sub channel for the authenticated user, and write notifications to the stream.
Client Subscription Example#
// client-side
export function connectNotifications() {
const es = new EventSource("/api/notifications/stream");
es.onmessage = (event) => {
const msg = JSON.parse(event.data);
console.log("notification stream message", msg);
};
es.onerror = () => {
es.close();
};
return () => es.close();
}Scaling SSE: Connection Limits and Instance Fanout#
SSE scaling constraints are often ignored until you have a few thousand concurrent users.
Important constraints to plan for:
- Each open connection consumes memory and file descriptors.
- You need cross-instance fanout via Redis pub-sub, NATS, Kafka, or a managed real-time service.
- If you deploy on serverless where instances scale up and down, connected clients can churn aggressively.
If you need help choosing the right real-time stack and deployment model, the tradeoffs are discussed in Next.js real-time features with WebSockets, SSE, and Supabase Realtime.
# Implementing WebSockets in Next.js: Presence and Bidirectional Actions#
Pure Next.js route handlers are not enough for classic WebSocket servers on many platforms. Common approaches are:
- Managed WebSocket providers
- Running a separate Node server for sockets
- Using platform-specific WebSocket support
Presence-like features require:
- Heartbeats from client to server
- A server-side presence store with TTL
- A strategy for reconnect storms and stale sessions
Presence Model (Practical Minimum)#
| Field | Stored in | TTL | Meaning |
|---|---|---|---|
user_id | Redis key | 60 to 120 seconds | User is online if key exists |
last_seen_at | DB | none | Updated on disconnect or periodic flush |
connection_id | Redis hash | same as TTL | Debugging and multi-device |
Presence accuracy depends on heartbeat intervals and TTL. For example, a 30-second heartbeat and a 90-second TTL tolerates brief network drops while keeping online status reasonably fresh.
ℹ️ Note: If you deploy behind a proxy that kills idle connections, presence over WebSockets must include ping frames or app-level heartbeats. Otherwise users will “ghost” as online.
# Reconciling Missed Notifications: The Inbox Sync API#
Even with real-time transport, clients will miss events:
- Device was offline
- Tab was in background
- Corporate proxy buffered the stream
- User switched networks
Your UI should always start by fetching the inbox delta since the last seen ID.
Minimal Inbox API Contract#
| Endpoint | Purpose | Returns |
|---|---|---|
GET /api/notifications?after={{cursor}} | Fetch new inbox items | Items plus next cursor |
POST /api/notifications/{{id}}/read | Mark as read | Updated unread count |
GET /api/notifications/unread-count | Fast header badge | Number |
Next.js Route Example: Fetch Inbox Delta#
// app/api/notifications/route.ts
export const runtime = "nodejs";
export async function GET(request: Request) {
const url = new URL(request.url);
const after = url.searchParams.get("after");
// Replace with your auth and DB calls
const userId = "user-id";
// Example: cursor-based pagination by created_at and id
// Keep it deterministic to avoid duplicates
const items = [
{ id: "n1", createdAt: Date.now(), title: "Invoice paid", readAt: null },
];
return Response.json({ items, nextCursor: "cursor-value" });
}The transport (SSE or WS) should only be responsible for prompting the client to refresh, or sending notification IDs that the client can reconcile against the inbox.
# Read States: Single Source of Truth vs Optimistic UI#
Unread badges are one of the highest-visibility notification surfaces. If they drift, users lose trust.
Recommended approach:
- DB is the source of truth for read state.
- Client can optimistically mark as read, but must reconcile on next fetch.
Two common patterns:
Pattern 1: Per-Notification Read Timestamp#
- Each inbox row has
read_at. - Unread count is
COUNT(*) WHERE read_at IS NULL.
This is simple and supports partial reads.
Pattern 2: High-Water Mark for “Read Up To”#
- Store
last_read_atorlast_read_notification_idper user. - Everything older than that is treated as read.
This is faster for bulk reads, but breaks if users read out of order or across devices without careful handling.
For most apps, start with per-notification read_at. You can add a high-water mark later for performance, but keep the inbox rows as the audit trail.
# Fallback Polling with React Query or SWR (Recommended Even with Real-Time)#
Some environments will not keep a stable stream. Your app should remain correct without real-time.
Polling is not “old-school,” it’s a safety net. A 30 to 60-second polling interval is often enough for notifications, and the cost is predictable.
React Query Polling Example#
import { useQuery, useQueryClient } from "@tanstack/react-query";
export function useNotifications() {
return useQuery({
queryKey: ["notifications"],
queryFn: async () => {
const res = await fetch("/api/notifications");
if (!res.ok) throw new Error("Failed to load notifications");
return res.json();
},
refetchInterval: 30000,
staleTime: 15000,
});
}
export function useNotificationStreamBridge() {
const qc = useQueryClient();
return () => {
const es = new EventSource("/api/notifications/stream");
es.onmessage = () => {
qc.invalidateQueries({ queryKey: ["notifications"] });
};
return () => es.close();
};
}This pattern keeps the stream dumb and robust: stream triggers invalidation, inbox API remains authoritative.
SWR Polling Example#
import useSWR from "swr";
const fetcher = (url: string) => fetch(url).then((r) => r.json());
export function useNotifications() {
return useSWR("/api/notifications", fetcher, {
refreshInterval: 30000,
dedupingInterval: 5000,
});
}For SWR, you can also call mutate("/api/notifications") when your SSE or WS message arrives.
💡 Tip: Use exponential backoff when the stream fails, but keep polling steady. This avoids reconnect storms during incidents.
# Choosing Between SSE and WebSockets: Practical Decision Matrix#
Use this decision matrix to avoid architecture churn.
| Requirement | Recommended transport | Why |
|---|---|---|
| Notifications only, server to client | SSE | Simple, resilient reconnects, fewer moving parts |
| Notifications plus interactive actions | SSE plus HTTP for actions | Keeps real-time channel simple and debuggable |
| Presence, typing indicators, collaborative features | WebSockets | Requires bidirectional low-latency messaging |
| Highly restricted enterprise networks | SSE | Often more proxy-friendly |
| Mobile app with background delivery needs | Push notifications plus inbox | Real-time sockets cannot run reliably in background |
| Need to support millions of connections | Managed real-time service | Self-hosting becomes costly without specialized infra |
If you still need presence but want SSE for notifications, you can do hybrid:
- SSE for notifications
- A lightweight WebSocket channel only for presence and heartbeats
This reduces message volume on the socket while keeping presence accurate.
# Observability: Debug Missed Notifications and Latency#
Real-time systems fail silently if you don’t instrument them. Add visibility before you scale.
Track these metrics:
| Metric | Why it matters | Typical alert trigger |
|---|---|---|
| Stream connection count | Capacity planning | Sudden drop greater than 30 percent |
| Reconnect rate | Network or platform issues | Spike greater than 3x baseline |
| Inbox insert latency | Backpressure and DB health | p95 greater than 500 ms |
| Time to first notification | UX and correctness | p95 greater than 2 s |
| Unread count mismatch rate | State bugs | Any sustained increase |
For a full instrumentation approach, read Web app observability guide: logging, metrics, tracing and the Next.js-specific setup in Next.js logging and monitoring with Sentry and OpenTelemetry on Vercel.
⚠️ Warning: Logging every notification payload in production can leak PII. Log IDs, types, and timings, and sample aggressively.
# Common Pitfalls (and How to Avoid Them)#
Treating real-time as the database#
If you don’t persist to an inbox, users lose notifications when offline. Always persist first, then notify.
Not deduplicating events on the client#
Reconnects and retries will cause duplicates. Deduplicate by event_id or inbox id in your state store.
Per-recipient fanout in the request path#
If a single action triggers 5,000 inbox inserts in the same HTTP request, your p95 latency will explode. Move fanout to a background job when recipient counts grow.
No fallback when streams fail#
Corporate proxies and mobile networks are not friendly to long-lived connections. Always keep polling enabled.
# Key Takeaways#
- Choose SSE for most notification-only use cases, and WebSockets when you need presence-like features or high-frequency bidirectional events.
- Build delivery guarantees with a durable inbox table plus reconciliation, not by trusting SSE or WebSockets to be reliable.
- Model read state explicitly with per-user inbox rows and
read_at, and deduplicate with a unique constraint on(user_id, event_id). - Plan fanout early: start with fanout-on-write for moderate scale, and move large recipient fanout into background jobs with batching.
- Always implement fallback polling with React Query or SWR, and let real-time messages trigger cache invalidation instead of being the only source of truth.
- Add observability for reconnect rate, inbox insert latency, and unread mismatches to catch failures before users report them.
# Conclusion#
Real-time delivery improves UX, but durable notifications require persistence, clear state modeling, and a fallback path. Start with an inbox-first design, add SSE for simple real-time updates, and reach for WebSockets only when presence and two-way interactions justify the complexity.
If you want Samioda to design or implement a production-ready Next.js real-time notifications system, including scaling and observability, contact us and we’ll review your requirements and propose an architecture that fits your traffic and hosting constraints.
FAQ
Founder & Senior Developer at Samioda. 8+ years building React, Next.js, Flutter and n8n automation solutions for clients across Europe.
More in Web Development
All →Next.js App Router Session Auth: Cookie Sessions, Middleware, and Refresh Patterns
A practical guide to Next.js App Router session authentication using httpOnly cookie sessions, middleware guards, and refresh or rotation patterns — with secure logout, CSRF guidance, and Vercel runtime notes.
React Admin Dashboard Architecture: RBAC, Audit Logs, Navigation, and Scalable Modules
A practical blueprint for React admin dashboard architecture in B2B products: information architecture, permission-driven UI, audit log event model, feature flags, module boundaries, and testing strategies for permissioned routes.
Next.js Multi-Tenant Authentication in the App Router: Tenant Resolution, Switching, and Security
A practical guide to Next.js multi-tenant authentication in the App Router: tenant resolution via subdomain, path, or header, session scoping, safe tenant switching UX, and code patterns that prevent cross-tenant data leaks.
Need help with your project?
We build custom solutions using the technologies discussed in this article. Senior team, fixed prices.
Related Articles
Next.js Real-Time Features: WebSockets vs SSE vs Supabase Realtime (When to Use What)
A practical comparison of Next.js real-time options—WebSockets, Server-Sent Events, and Supabase Realtime—covering hosting constraints, scalability, auth, cost, and which to use for chat, dashboards, notifications, and collaborative editing.
React Query vs SWR in Next.js App Router: When to Use Which (and How to Avoid Double Fetching)
A practical 2026 comparison of React Query and SWR inside Next.js App Router — caching models, SSR and RSC compatibility, mutations, optimistic updates, DX, and proven patterns to prevent double fetching.
React Multi-Step Forms at Scale: Save Draft, Resume Later, Validation, and Step Navigation
A practical guide to building a React multi step form that supports draft saving, cross-device resume, conditional steps, and robust validation using React Hook Form + Zod with server-side persistence and analytics.