How to Secure WebSockets in a Next.js SaaS Application
WebSocket security in Next.js SaaS requires auth, origin checks, and tenant isolation. Prevent CSWSH and cross-tenant data leakage in real-time features.
WebSocket security in Next.js SaaS applications is one of the most commonly overlooked attack surfaces. HTTP endpoints get headers, cookies, middleware, and framework-level CSRF protection. WebSocket connections get none of that by default. The protocol offloads authentication, authorization, and input validation entirely to the application — and when those are absent or incomplete, real-time features become a direct path into your tenant data, your session management, and your message bus.
The problem is structural. Next.js does not ship with WebSocket support, so developers reach for Socket.IO, Ably, Pusher, or Partykit and wire them up quickly to get the demo working. The auth layer gets added later, if at all, in the same pattern that leads to authentication mistakes in vibe-coded apps. Unlike HTTP where a missing authentication check usually blocks a single endpoint, a misconfigured WebSocket connection can expose an entire message room — including every other tenant in that namespace — to anyone who connects. This post covers what WebSocket security requires in a production SaaS application, with the specific patterns that apply to Next.js App Router and the multi-tenant context.
Three attacks dominate the real-world risk profile. Cross-Site WebSocket Hijacking (CSWSH) is the WebSocket equivalent of CSRF: an attacker page connects to your WebSocket server using the victim's browser cookies and reads or sends messages on their behalf. Tenant data leakage through shared channels is a persistent risk in multi-tenant SaaS where rooms are not scoped to a tenant. Input injection through unsanitized WebSocket message payloads creates XSS and command injection vectors in real-time collaboration features. Each requires a deliberate fix — none are addressed by default Next.js configuration.
Why Next.js SaaS Apps Need a Custom WebSocket Strategy
Next.js does not natively support WebSocket connections. The framework's serverless and edge deployment model means incoming HTTP requests are handled by short-lived function invocations — there is no persistent process that can hold a WebSocket connection open. To add real-time features you have several options, each with different security implications.
- →Socket.IO with a custom Node.js server: Socket.IO requires a persistent HTTP server and attaches its own WebSocket and long-polling transports. This means adding a custom server.js to your Next.js project, which breaks Vercel and Netlify serverless deployments. You gain full control over the connection lifecycle and authentication hooks — but that control is entirely your responsibility to implement.
- →Managed real-time services (Ably, Pusher, Liveblocks, Partykit): these offload the WebSocket infrastructure to a third party. Your Next.js server generates signed tokens that clients use to authenticate with the managed service. Authentication is handled per-connection via token claims, and you need to understand how those claims map to channel access before trusting their enforcement.
- →Vercel WebSocket support via Edge Runtime: Vercel Edge Functions gained persistent WebSocket support in 2025. These run in an edge context with a request/response model but support WebSocket upgrades. Auth must be explicitly checked during the upgrade handler before the connection is accepted — there is no middleware-level auth applied automatically.
- →Server-Sent Events (SSE) as a simpler alternative: SSE is unidirectional (server to client), lives on a standard HTTP endpoint, and therefore inherits all of Next.js route handler authentication patterns. For read-only real-time feeds — notifications, live dashboards, audit log tails — SSE avoids WebSocket complexity and is significantly easier to secure correctly.
Authenticating the WebSocket Upgrade Request
A WebSocket connection begins as an HTTP upgrade request. The server must respond with 101 Switching Protocols or refuse with 401/403. That upgrade handler is the last chance to validate the caller's identity before a persistent bidirectional channel is established. Once upgraded, the connection is live until one side closes it — there is no equivalent of per-request session validation unless you explicitly add it.
- →Cookie-based session authentication is the safest default for browser clients. The WebSocket upgrade request is an HTTP request, so the browser includes httpOnly session cookies automatically. Read and validate the session cookie in the upgrade handler exactly as you would in an API route. If the session is invalid or missing, refuse the upgrade with a 401 before the WebSocket channel opens.
- →Never pass credentials in the WebSocket URL query string. A pattern seen frequently in AI-generated WebSocket code passes JWTs or API keys in the URL: wss://app.example.com/ws?token=eyJ... WebSocket URLs are logged by servers, proxies, CDNs, and browser history. Any secret in the URL is effectively leaked to every infrastructure layer between the client and server. Use cookies or headers instead.
- →Short-lived one-time tickets are the recommended pattern for token-based auth. The client first makes an authenticated HTTP request to an API route that returns a short-lived (60-300 second) one-time ticket. The client then connects to the WebSocket endpoint using that ticket, which the upgrade handler validates and invalidates on first use. This avoids long-lived tokens in URLs while supporting non-browser clients that cannot send cookies.
- →Revalidate the session at meaningful intervals for long-lived connections. A session validated at upgrade time may expire or be revoked while the connection is open. For sensitive SaaS contexts, periodically re-verify the session token: on a timer (every 15-30 minutes), on each meaningful client action, or by using short-lived tokens that force a re-authentication cycle. A user who is deprovisioned mid-session should lose their WebSocket connection, not retain it until they disconnect.
Cross-Site WebSocket Hijacking and Origin Validation
Cross-Site WebSocket Hijacking (CSWSH) is the attack where a malicious page at evil.com opens a WebSocket connection to wss://app.yoursaas.com. Because the upgrade request is a browser HTTP request, the victim's session cookies are included. If your upgrade handler validates the session cookie but not the connection origin, the attacker page is now authenticated to your WebSocket server and can receive or send messages on behalf of the victim — without the victim knowing.
- →Validate the Origin header on every WebSocket upgrade request. The browser sets the Origin header to the page that initiated the connection — evil.com in a hijacking scenario, or app.yoursaas.com in a legitimate one. Your upgrade handler must compare the Origin against an allowlist of valid origins and refuse connections from unexpected sources. This is the primary defense against CSWSH and it is easy to add: check the header before accepting the upgrade.
- →An allowlist is safer than a blocklist. Define the exact origins your application runs on (your production domain, your staging domain, localhost during development) and reject anything else. Never use a wildcard match against the origin — attackers can register subdomains that would match a broad pattern.
- →CSWSH requires cookies as the auth mechanism. If your WebSocket endpoint uses token-based auth passed in custom headers, CSWSH does not apply — browsers cannot inject custom headers from a cross-origin page. The attack only works because browsers automatically attach cookies. This is another argument for short-lived ticket patterns in high-security contexts.
- →Test CSWSH manually during security review. Open a browser console on a different origin and run new WebSocket('wss://app.yoursaas.com/ws'). If the connection upgrades successfully without a valid same-origin session, your origin check is missing or not enforced correctly. This test takes two minutes and catches a vulnerability that automated scanners frequently miss.
Authorizing Per-Subscription and Per-Message Events
Authentication — confirming who is connecting — is not the same as authorization — confirming what they are allowed to do. A common gap in WebSocket implementations is authenticating the upgrade request but then processing all subsequent messages without checking whether the authenticated user has permission to perform each action. This is the WebSocket equivalent of the IDOR vulnerabilities seen in multi-tenant SaaS APIs: the user identity is confirmed, but the resource-level permission check is missing.
- →Authorize at subscription time, not just connection time. When a client joins a channel, room, or subscribes to a resource, check that the authenticated user has permission to access that specific resource. A user authenticated to your SaaS application should not automatically have access to every channel — only the channels for their tenant, their workspace, and their role.
- →Re-check permissions on each state-changing message. A subscription check at join time guards entry. It does not guard against a user whose role changes after they connect, or against a user who was deprovisioned while the connection is live. For mutations — creating, updating, or deleting data through a WebSocket message — re-verify the current user's permissions against the current state of your authorization data on each message.
- →Use the same authorization logic as your REST or GraphQL API. WebSocket message handlers that bypass the authorization middleware used by your API routes introduce inconsistency. A multi-tenant SaaS should enforce tenant isolation in one place and use it everywhere — WebSocket handlers, API routes, Server Actions, and background jobs. If your REST API uses a Zod-validated request plus a permission check function, your WebSocket handler should call the same permission check function.
- →Log authorization denials. A series of rapid authorization failures on a WebSocket connection is a signal worth alerting on — it may indicate a user exploring what they can access, a misconfigured client, or a compromised session being probed. WebSocket authorization events are often absent from application logs because developers instrument HTTP endpoints but forget the persistent connection path.
Multi-Tenant Isolation for Real-Time Channels
In a multi-tenant SaaS application, the most critical WebSocket security property is tenant isolation: messages intended for Tenant A must never reach Tenant B, and a client authenticated to Tenant A's workspace must not be able to subscribe to Tenant B's channels. The architectural failure mode is a shared namespace where channel names or room IDs are predictable and not scoped to a tenant.
- →Prefix every channel, room, and namespace with the tenant ID. If your real-time channels are named by feature (live-document-123, comments-456), a user who guesses or enumerates IDs can subscribe to another tenant's resources. Prefix with the tenant ID: tenant-abc:live-document-123. When a user subscribes to a channel, verify that the tenant ID in the channel name matches the tenant in their session before allowing the subscription.
- →Never trust the tenant ID from the client. The client should not send its own tenant ID in WebSocket messages and have the server use that value. The server must derive the tenant identity from the authenticated session — the same principle that prevents tenant impersonation in multi-tenant API routes. A session belongs to exactly one tenant; the server enforces that mapping.
- →Isolate channels at the infrastructure level for high-security tenants. Logical isolation through naming conventions and server-side checks is correct and sufficient for most SaaS applications. For customers with regulatory requirements or strong data isolation needs, consider per-tenant message bus namespaces or separate real-time service deployments.
- →Test tenant isolation with two separate sessions. The definitive test: create two users in different tenants, connect both to your WebSocket server simultaneously, have Tenant A send a message, and confirm that Tenant B does not receive it. This test is easy to write and must be in your integration test suite — not just a manual check before launch.
Validating and Rate-Limiting Incoming WebSocket Messages
Every message received over a WebSocket connection is untrusted client input. This is obvious for HTTP where each request goes through validation middleware, but WebSocket message handlers are frequently written without input validation — the developer connects the socket to business logic directly. Authenticated users can still send malformed or malicious payloads, and XSS content in WebSocket message payloads that reach other clients is a real injection vector in real-time collaboration features. The same XSS prevention principles apply to WebSocket message payloads that are rendered in the browser.
- →Parse and validate every incoming message with a schema validator. A WebSocket message handler that runs JSON.parse() on the payload and passes the result directly to business logic is equivalent to an HTTP handler that skips request body validation. Use Zod or a similar library to define the expected shape of each message type, validate before processing, and close the connection or send an error response on a validation failure.
- →Define a message type enum and validate it first. If your WebSocket protocol has multiple message types (join, leave, send, react), validate the type field first and reject anything not in the expected set. Unrecognized message types should be ignored or rejected, not passed to default handlers that might process them in unexpected ways.
- →Sanitize any message content that will be rendered to other users. In a real-time collaboration feature where messages from one user appear in another user's browser, treat the content as untrusted HTML input. Strip or encode HTML, use textContent instead of innerHTML when rendering in the browser, and implement a Content Security Policy that would catch injected scripts.
- →Apply rate limiting per connection and per user. A WebSocket connection held open can send thousands of messages per second. Without rate limiting, a single authenticated user can DoS your message processing infrastructure or trigger downstream services at scale. Apply per-connection message rate limits and per-user limits across all connections for the same user.
- →Set a maximum message size and reject oversized payloads before parsing them. An unbounded message size allows a client to allocate arbitrary memory in your server by sending a single large frame. The WebSocket library or gateway should enforce a configurable maximum frame size; the application should also validate that parsed payloads do not exceed expected content length before storing or forwarding them.
Testing Your WebSocket Security Implementation
WebSocket security is easy to miss in standard security reviews because HTTP scanners do not cover the WebSocket protocol, and most automated tools focus on the REST API surface. Running DeployReady gives you a production-readiness baseline for the HTTP layer — exposed endpoints, missing security headers, unauthenticated API routes. Verifying WebSocket security requires a combination of integration tests, manual testing, and targeted tooling on top of that baseline.
- →Test unauthenticated upgrade attempts. Write an integration test that attempts to open a WebSocket connection without a valid session cookie. The upgrade should be refused with a 401 or 403. If it succeeds and the connection is opened, authentication is missing or broken.
- →Test CSWSH manually with a cross-origin connection. From a browser console on a different origin (or by temporarily modifying the Origin header using a proxy like Burp Suite), attempt to connect to your WebSocket endpoint with an active session cookie. The upgrade should be refused. If it succeeds, origin validation is missing.
- →Test channel authorization with a low-privilege user. Connect as a user with restricted access and attempt to subscribe to channels, rooms, or resources belonging to another tenant or a higher-privilege scope. The subscription should be refused with a clear error response. If it succeeds, per-subscription authorization is missing.
- →Test message injection with HTML payloads. Send WebSocket messages containing HTML and JavaScript strings. If the payload reaches other connected clients and is rendered as HTML in the browser, the application is vulnerable to stored XSS via the WebSocket message bus. Confirm that the client correctly escapes message content before rendering.
- →Fuzz message payloads with malformed JSON, missing required fields, unexpected types, and oversized values. The server should reject invalid payloads gracefully without crashing or exposing internal error details. A crash in a WebSocket handler that takes down your Node.js server is a denial-of-service vulnerability.
Frequently Asked Questions
How do you authenticate WebSocket connections in Next.js?
The standard approach is to validate the session cookie during the HTTP upgrade handshake before accepting the connection. The WebSocket upgrade request is an HTTP request and includes httpOnly cookies set by your Next.js application. In the upgrade handler, read the session cookie, validate it against your session store, and either accept the upgrade or refuse it with a 401. For token-based auth, generate a short-lived one-time ticket via an authenticated API route, pass the ticket in the WebSocket connection URL, and validate it on the server during upgrade — invalidating the ticket immediately on first use.
What is Cross-Site WebSocket Hijacking and how do you prevent it?
Cross-Site WebSocket Hijacking (CSWSH) is an attack where a malicious page opens a WebSocket connection to your server using the victim's session cookies. The browser attaches cookies to WebSocket upgrade requests just as it does to regular HTTP requests. Prevention requires validating the Origin header on every upgrade request and refusing connections from origins outside your expected allowlist. It is the WebSocket equivalent of CSRF, and it requires explicit origin checking even when session authentication looks correct.
Should WebSocket authorization checks happen at connection time or per message?
Both. Authentication and coarse-grained authorization — is this user allowed to use this WebSocket service at all? — should happen at connection time during the upgrade handshake. Per-resource authorization — is this user allowed to subscribe to this specific channel? — must happen at subscription time. For state-changing messages, re-check authorization per message, because a user's role or permissions may have changed after the connection was established and the connection is still live.
How do you prevent one tenant from receiving another tenant's WebSocket messages?
Name every channel and room with a tenant-scoped prefix derived from the server-side session, never from the client. When a client subscribes to a channel, validate that the tenant ID in the channel name matches the tenant in the authenticated session before allowing the subscription. Test isolation explicitly: connect two sessions from different tenants simultaneously and verify that a message sent from one is not received by the other. This test must be automated in your integration suite, not performed manually once before launch.
Can automated tools scan WebSocket endpoints for security issues?
Most standard scanners (OWASP ZAP, Burp Suite free tier) have partial WebSocket support. Burp Suite Pro can intercept, replay, and fuzz WebSocket messages. DeployReady scans the HTTP surface of your application including WebSocket upgrade endpoint exposure and missing security headers, but deep WebSocket protocol testing requires manual review. For a production SaaS, automated HTTP scanning is the floor; manual WebSocket auth and authorization testing is what catches the gaps that automated tools miss.
How Belsoft Helps with Real-Time SaaS Security
WebSocket security failures are rarely caught before launch because they look like working features. A channel that leaks cross-tenant data appears functional to the developer who built it — the right data shows up. The wrong data also shows up, to the wrong tenant, invisibly. Belsoft's security audit service includes a manual review of real-time and WebSocket implementations as part of the broader authorization review: we test upgrade authentication, CSWSH susceptibility, channel-level authorization, and tenant isolation. We test these the way an attacker would — not by reading the code but by running the connections and observing what comes back.
For the HTTP surface, run DeployReady as a first pass. It checks for exposed WebSocket upgrade endpoints, missing security headers, and authentication gaps in API routes. The audit covers what automated tools miss. If your SaaS application has real-time features and you have not explicitly verified WebSocket auth, tenant isolation, and message validation, book a security review before your first enterprise customer does that review for you.
“An authenticated WebSocket connection is not a secure one. Authentication confirms who connected. Authorization determines what they can see. Tenant isolation determines who they cannot.”
Written by
Marco Silva
Security Engineer, Belsoft Solutions
More from the blog
Ready to partner?
Let's talk about your company.
30 minutes. No pitch. We talk through how you run today and where AI and automation would help.
Book a free audit
