Realtime WebSocket Notifications for Next.js
Add WebSocket channels and real-time notifications to Next.js. Works with App Router and Pages Router — no dedicated WebSocket server needed.
npm install @apinator/server Server npm install @apinator/client Client Adding real-time WebSocket notifications to a Next.js app used to mean managing your own persistent server — which conflicts with Next.js's stateless, serverless architecture. Apinator solves this: hosted WebSocket infrastructure that connects to your Next.js Route Handlers for channel authentication and your Server Actions or API routes for event publishing. Add live WebSocket channels to any Next.js project in under 5 minutes.
Quick Start
How to add WebSocket notifications to Next.js App Router
Add realtime features to your Next.js app in a few steps.
Install both SDKs
Add the server SDK for signing WebSocket channel auth in Route Handlers, and the client SDK for subscribing to channels in React components.
npm install @apinator/server @apinator/client See your first event (no backend)
No server code yet: subscribe to the public channel my-channel (public channels need no auth endpoint) with your app key and cluster (us or eu) from the dashboard, then click the Send test event button on your app's Overview page in the dashboard. The event prints in your console. Open the dashboard
'use client'
// app/first-event.tsx: render <FirstEvent /> from any page
import { useEffect } from 'react'
import { Apinator } from '@apinator/client'
export function FirstEvent() {
useEffect(() => {
const client = new Apinator({ appKey: 'YOUR_APP_KEY', cluster: 'us' }).connect()
client.subscribe('my-channel').bind('my-event', (data) => console.log('Received:', data))
return () => { client.disconnect() }
}, [])
return null
} Create a WebSocket auth Route Handler
Add a POST Route Handler that signs WebSocket channel subscription requests using your app secret. Required for private and presence channels — for presence, also pass the user as a channel_data JSON string ({ user_id, user_info }).
// app/api/realtime/auth/route.ts
import { Apinator } from '@apinator/server'
import { NextResponse } from 'next/server'
const realtime = new Apinator({
appId: process.env.REALTIME_APP_ID!,
key: process.env.REALTIME_KEY!,
secret: process.env.REALTIME_SECRET!,
cluster: process.env.REALTIME_CLUSTER!
})
export async function POST(req: Request) {
const { socket_id, channel_name } = await req.json()
const auth = realtime.authenticateChannel(socket_id, channel_name)
return NextResponse.json(auth)
} Subscribe to a WebSocket channel
Open a persistent WebSocket connection and subscribe to channels from a React Client Component. Bind event handlers in useEffect for proper cleanup.
'use client'
import { Apinator } from '@apinator/client'
import { useEffect, useState } from 'react'
const client = new Apinator({
appKey: process.env.NEXT_PUBLIC_REALTIME_KEY!,
cluster: 'us',
authEndpoint: '/api/realtime/auth'
}) Trigger notifications from your server
Publish WebSocket events from Route Handlers, Server Actions, or any API route. All subscribed clients receive the real-time notification instantly.
// app/api/notify/route.ts
export async function POST(req: Request) {
const data = await req.json()
await realtime.trigger({
name: 'new-notification',
channel: 'private-notifications',
data: JSON.stringify(data)
})
return NextResponse.json({ ok: true })
} Why Next.js
Built for Next.js developers
Route Handler Auth
Authenticate private and presence WebSocket channels from Next.js Route Handlers. HMAC-SHA256 signed tokens, with the user passed as channel_data for presence. Runs in the Node.js runtime.
React Hooks Compatible
Client WebSocket SDK designed for React component lifecycles. Initialize once, subscribe in useEffect, automatic cleanup on unmount — no memory leaks.
TypeScript-First
Full TypeScript support for both server and client SDKs. Typed channels, options, and responses out of the box.
Node.js Runtime
Server SDK signs requests with Node's crypto module. Works in Route Handlers, Server Actions, and API routes on the Node.js runtime.
Why WebSockets in Next.js need a different approach
Next.js is built on a serverless-first model: Route Handlers spin up on demand and shut down immediately after responding. This stateless architecture makes it impossible to maintain a persistent WebSocket server — the kind you'd need to push real-time notifications to connected browser clients. Traditional WebSocket libraries like ws or socket.io require a long-running Node.js process, which conflicts with how Next.js App Router deployments work on Vercel or Cloudflare Pages.
Apinator solves this by keeping the persistent WebSocket infrastructure entirely off your Next.js server. Your application handles just two things: authenticating WebSocket channel subscriptions from a Route Handler (a simple HMAC verification), and triggering events via a standard REST call from a Server Action or API route. The real-time WebSocket connection between Apinator's edge servers and your users' browsers is fully managed — no WebSocket server to deploy, scale, or operate. Unlike push notifications, which require a service worker and platform-specific setup, Apinator uses persistent WebSocket connections that work immediately in any modern browser.
The result: real-time WebSocket notifications in Next.js App Router with a few dozen lines of code, no infrastructure changes, and no compatibility issues with serverless deployments.
Full Example
Full Example: Realtime WebSocket Notification Feed in Next.js App Router
Complete WebSocket example: authenticate private channels in a Route Handler, publish events from an API route, and receive real-time notifications in a React Client Component.
import { Apinator } from '@apinator/server'
import { NextResponse } from 'next/server'
const realtime = new Apinator({
appId: process.env.REALTIME_APP_ID!,
key: process.env.REALTIME_KEY!,
secret: process.env.REALTIME_SECRET!,
cluster: process.env.REALTIME_CLUSTER!
})
export async function POST(req: Request) {
const { socket_id, channel_name } = await req.json()
// Add your own auth check here
const auth = realtime.authenticateChannel(socket_id, channel_name)
return NextResponse.json(auth)
}Related Docs
Read the core WebSocket guides
Related Use Cases
Explore realtime use cases
From the blog
Next.js WebSockets (2026): Does Vercel Support Them? 4 Ways That Work
Vercel Functions and Route Handlers can't hold a WebSocket open. The 4 setups that work with the App Router and Pages Router, with full code for each.
How to Build Live Customer Support Chat
Build a live chat widget for your product — a customer-facing chat window and an agent dashboard that both update in real time using WebSockets.
What Is a Pub/Sub Channel?
Pub/sub channels are the core abstraction in realtime systems — they let publishers send messages to many subscribers without knowing who's listening. Here's how they work.
Start building realtime Next.js apps
Completely free. No credit card. No catch.