Commit d3a42993 authored by Ethan Niser's avatar Ethan Niser

feat(server): add WebSocket support for App Router route handlers

parent 99eae38f
...@@ -7,6 +7,7 @@ declare global { ...@@ -7,6 +7,7 @@ declare global {
export { NextFetchEvent } from 'next/dist/server/web/spec-extension/fetch-event' export { NextFetchEvent } from 'next/dist/server/web/spec-extension/fetch-event'
export { NextRequest } from 'next/dist/server/web/spec-extension/request' export { NextRequest } from 'next/dist/server/web/spec-extension/request'
export { NextResponse } from 'next/dist/server/web/spec-extension/response' export { NextResponse } from 'next/dist/server/web/spec-extension/response'
export { NextWebSocket } from 'next/dist/server/web/spec-extension/websocket'
export { export {
NextMiddleware, NextMiddleware,
MiddlewareConfig, MiddlewareConfig,
......
...@@ -12,6 +12,7 @@ import { ...@@ -12,6 +12,7 @@ import {
setRequestMeta, setRequestMeta,
type RequestMeta, type RequestMeta,
} from '../../server/request-meta' } from '../../server/request-meta'
import { WEBSOCKET_INTERNAL } from '../../server/web/spec-extension/websocket'
import { getTracer, type Span, SpanKind } from '../../server/lib/trace/tracer' import { getTracer, type Span, SpanKind } from '../../server/lib/trace/tracer'
import { setManifestsSingleton } from '../../server/app-render/manifests-singleton' import { setManifestsSingleton } from '../../server/app-render/manifests-singleton'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
...@@ -323,6 +324,27 @@ export async function handler( ...@@ -323,6 +324,27 @@ export async function handler(
const response = await invokeRouteModule(currentSpan) const response = await invokeRouteModule(currentSpan)
// Check if this is a WebSocket upgrade response
const isWebSocketUpgrade =
response.headers.get('x-next-websocket-upgrade') === '1'
if (isWebSocketUpgrade) {
// Get the WebSocket internal data from the response
const wsInternal = (response as any)[WEBSOCKET_INTERNAL]
if (wsInternal && getRequestMeta(req, 'isWebSocketUpgrade')) {
// Store the WebSocket internal data in request metadata
// so the router-server can access it for bridging
addRequestMeta(req, 'websocketInternal', wsInternal)
// Set response headers to indicate WebSocket upgrade
res.statusCode = 101
res.setHeader('x-next-websocket-upgrade', '1')
// Don't end the response - let the bridge handle it
return null
}
}
;(req as any).fetchMetrics = (context.renderOpts as any).fetchMetrics ;(req as any).fetchMetrics = (context.renderOpts as any).fetchMetrics
let pendingWaitUntil = context.renderOpts.pendingWaitUntil let pendingWaitUntil = context.renderOpts.pendingWaitUntil
......
...@@ -198,13 +198,15 @@ export function checkCustomRoutes( ...@@ -198,13 +198,15 @@ export function checkCustomRoutes(
(route as Rewrite).basePath === false && (route as Rewrite).basePath === false &&
!( !(
(route as Rewrite).destination.startsWith('http://') || (route as Rewrite).destination.startsWith('http://') ||
(route as Rewrite).destination.startsWith('https://') (route as Rewrite).destination.startsWith('https://') ||
(route as Rewrite).destination.startsWith('ws://') ||
(route as Rewrite).destination.startsWith('wss://')
) )
) { ) {
console.error( console.error(
`The route ${ `The route ${
(route as Rewrite).source (route as Rewrite).source
} rewrites urls outside of the basePath. Please use a destination that starts with \`http://\` or \`https://\` https://nextjs.org/docs/messages/invalid-external-rewrite` } rewrites urls outside of the basePath. Please use a destination that starts with \`http://\`, \`https://\`, \`ws://\`, or \`wss://\` https://nextjs.org/docs/messages/invalid-external-rewrite`
) )
numInvalidRoutes++ numInvalidRoutes++
continue continue
...@@ -305,10 +307,10 @@ export function checkCustomRoutes( ...@@ -305,10 +307,10 @@ export function checkCustomRoutes(
invalidParts.push('`destination` is not a string') invalidParts.push('`destination` is not a string')
} else if ( } else if (
type === 'rewrite' && type === 'rewrite' &&
!_route.destination.match(/^(\/|https:\/\/|http:\/\/)/) !_route.destination.match(/^(\/|https:\/\/|http:\/\/|wss:\/\/|ws:\/\/)/)
) { ) {
invalidParts.push( invalidParts.push(
'`destination` does not start with `/`, `http://`, or `https://`' '`destination` does not start with `/`, `http://`, `https://`, `ws://`, or `wss://`'
) )
} }
} }
......
...@@ -369,6 +369,7 @@ export const experimentalSchema = { ...@@ -369,6 +369,7 @@ export const experimentalSchema = {
hideLogsAfterAbort: z.boolean().optional(), hideLogsAfterAbort: z.boolean().optional(),
runtimeServerDeploymentId: z.boolean().optional(), runtimeServerDeploymentId: z.boolean().optional(),
devCacheControlNoCache: z.boolean().optional(), devCacheControlNoCache: z.boolean().optional(),
webSockets: z.boolean().optional(),
} }
export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
......
...@@ -918,6 +918,13 @@ export interface ExperimentalConfig { ...@@ -918,6 +918,13 @@ export interface ExperimentalConfig {
* @default false * @default false
*/ */
devCacheControlNoCache?: boolean devCacheControlNoCache?: boolean
/**
* Enable WebSocket support in App Router route handlers via `NextResponse.upgrade()`.
*
* @default false
*/
webSockets?: boolean
} }
export type ExportPathMap = { export type ExportPathMap = {
...@@ -1644,6 +1651,7 @@ export const defaultConfig = Object.freeze({ ...@@ -1644,6 +1651,7 @@ export const defaultConfig = Object.freeze({
turbopackFileSystemCacheForBuild: false, turbopackFileSystemCacheForBuild: false,
turbopackInferModuleSideEffects: true, turbopackInferModuleSideEffects: true,
devCacheControlNoCache: false, devCacheControlNoCache: false,
webSockets: false,
}, },
htmlLimitedBots: undefined, htmlLimitedBots: undefined,
bundlePagesRouterDependencies: false, bundlePagesRouterDependencies: false,
...@@ -1741,6 +1749,7 @@ export interface NextConfigRuntime { ...@@ -1741,6 +1749,7 @@ export interface NextConfigRuntime {
| 'runtimeServerDeploymentId' | 'runtimeServerDeploymentId'
| 'maxPostponedStateSize' | 'maxPostponedStateSize'
| 'devCacheControlNoCache' | 'devCacheControlNoCache'
| 'webSockets'
> & { > & {
// Pick on @internal fields generates invalid .d.ts files // Pick on @internal fields generates invalid .d.ts files
/** @internal */ /** @internal */
...@@ -1804,6 +1813,7 @@ export function getNextConfigRuntime( ...@@ -1804,6 +1813,7 @@ export function getNextConfigRuntime(
runtimeServerDeploymentId: ex.runtimeServerDeploymentId, runtimeServerDeploymentId: ex.runtimeServerDeploymentId,
maxPostponedStateSize: ex.maxPostponedStateSize, maxPostponedStateSize: ex.maxPostponedStateSize,
devCacheControlNoCache: ex.devCacheControlNoCache, devCacheControlNoCache: ex.devCacheControlNoCache,
webSockets: ex.webSockets,
trustHostHeader: ex.trustHostHeader, trustHostHeader: ex.trustHostHeader,
isExperimentalCompile: ex.isExperimentalCompile, isExperimentalCompile: ex.isExperimentalCompile,
......
...@@ -60,6 +60,7 @@ import { ...@@ -60,6 +60,7 @@ import {
isChromeDevtoolsWorkspaceUrl, isChromeDevtoolsWorkspaceUrl,
} from './chrome-devtools-workspace' } from './chrome-devtools-workspace'
import { getNextConfigRuntime, type NextConfigComplete } from '../config-shared' import { getNextConfigRuntime, type NextConfigComplete } from '../config-shared'
import { bridgeWebSocket } from '../web/websocket-bridge'
const debug = setupDebug('next:router-server:main') const debug = setupDebug('next:router-server:main')
const isNextFont = (pathname: string | null) => const isNextFont = (pathname: string | null) =>
...@@ -800,6 +801,111 @@ export async function initialize(opts: { ...@@ -800,6 +801,111 @@ export async function initialize(opts: {
development?.bundler?.ensureMiddleware development?.bundler?.ensureMiddleware
) )
/**
* Handle WebSocket upgrade for app route handlers.
* Returns { handled: true } if the upgrade was handled, { handled: false } otherwise.
*/
async function handleWebSocketUpgrade(
req: import('http').IncomingMessage,
socket: import('stream').Duplex,
head: Buffer,
itemPath: string,
parsedUrl: NextUrlWithParsedQuery
): Promise<{ handled: boolean }> {
// Create a mock response to capture the route handler's response
const { ServerResponse } = require('http') as typeof import('http')
const mockRes = new ServerResponse(req)
// We need to capture the response from the route handler
let responseHeaders: Record<string, string | string[] | undefined> = {}
let responseStatus = 200
let wsInternalData: any = null
// Create a proxy response that captures the WebSocket upgrade response
const capturedChunks: Buffer[] = []
mockRes.writeHead = function (
this: typeof mockRes,
statusCode: number,
statusMessage?: string | Record<string, string | string[] | undefined>,
headers?: Record<string, string | string[] | undefined>
) {
responseStatus = statusCode
if (typeof statusMessage === 'object') {
responseHeaders = { ...responseHeaders, ...statusMessage }
} else if (headers) {
responseHeaders = { ...responseHeaders, ...headers }
}
return this
} as any
mockRes.setHeader = function (
this: typeof mockRes,
name: string,
value: string | string[]
) {
responseHeaders[name.toLowerCase()] = value
return this
} as any
mockRes.end = function (this: typeof mockRes, chunk?: any) {
if (chunk) {
capturedChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))
}
return this
} as any
mockRes.write = function (this: typeof mockRes, chunk: any) {
capturedChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))
return true
} as any
// Set up request metadata
addRequestMeta(req, 'invokePath', itemPath)
addRequestMeta(req, 'invokeQuery', parsedUrl.query)
addRequestMeta(req, 'middlewareInvoke', false)
addRequestMeta(req, 'isWebSocketUpgrade', true)
addRequestMeta(req, 'upgradeSocket', socket)
addRequestMeta(req, 'upgradeHead', head)
try {
// Initialize render server and invoke the handler
const initResult =
await renderServer?.instance?.initialize(renderServerOpts)
if (!initResult) {
return { handled: false }
}
// Create a custom request handler that can capture WebSocket upgrade responses
await initResult.requestHandler(req, mockRes as any)
// Check if the response indicates a WebSocket upgrade
const isWebSocketUpgrade =
responseHeaders['x-next-websocket-upgrade'] === '1' ||
responseStatus === 101
if (!isWebSocketUpgrade) {
return { handled: false }
}
// Get the WebSocket internal data from the request metadata
wsInternalData = getRequestMeta(req, 'websocketInternal')
if (!wsInternalData) {
debug('WebSocket upgrade requested but no internal data found')
return { handled: false }
}
// Bridge the WebSocket
await bridgeWebSocket(req, socket, head, wsInternalData)
return { handled: true }
} catch (err) {
debug('Error handling WebSocket upgrade:', err)
return { handled: false }
}
}
const upgradeHandler: WorkerUpgradeHandler = async (req, socket, head) => { const upgradeHandler: WorkerUpgradeHandler = async (req, socket, head) => {
try { try {
req.on('error', (_err) => { req.on('error', (_err) => {
...@@ -877,15 +983,99 @@ export async function initialize(opts: { ...@@ -877,15 +983,99 @@ export async function initialize(opts: {
) )
}, },
}) })
const { matchedOutput, parsedUrl } = await resolveRoutes({ const { matchedOutput, parsedUrl, finished, statusCode, resHeaders } =
await resolveRoutes({
req, req,
res, res,
isUpgradeReq: true, isUpgradeReq: true,
signal: signalFromNodeResponse(socket), signal: signalFromNodeResponse(socket),
}) })
// TODO: allow upgrade requests to pages/app paths? // If middleware returned a redirect response, send the redirect
// this was not previously supported if (
finished &&
statusCode &&
statusCode >= 300 &&
statusCode < 400 &&
resHeaders
) {
const location = resHeaders['location']
if (location) {
const redirectResponse = [
`HTTP/1.1 ${statusCode} ${statusCode === 301 ? 'Moved Permanently' : statusCode === 302 ? 'Found' : statusCode === 307 ? 'Temporary Redirect' : statusCode === 308 ? 'Permanent Redirect' : 'Redirect'}`,
`Location: ${location}`,
'Connection: close',
'',
'',
].join('\r\n')
socket.write(redirectResponse)
return socket.end()
}
}
// If middleware returned an error response (e.g., 403 Forbidden),
// send the error response instead of upgrading the connection
if (finished && statusCode && statusCode >= 400) {
const statusText =
statusCode === 400
? 'Bad Request'
: statusCode === 401
? 'Unauthorized'
: statusCode === 403
? 'Forbidden'
: statusCode === 404
? 'Not Found'
: 'Error'
const errorResponse = [
`HTTP/1.1 ${statusCode} ${statusText}`,
'Content-Type: text/plain',
'Connection: close',
'',
statusText,
].join('\r\n')
socket.write(errorResponse)
return socket.end()
}
// Note: When middleware returns NextResponse.next() with header modifications,
// finished=true but statusCode is typically 200. In this case, we should
// continue to handle the WebSocket upgrade, not close the connection.
// Handle WebSocket upgrade for app route handlers (only if experimental.webSockets is enabled)
if (
config.experimental.webSockets &&
matchedOutput &&
matchedOutput.type === 'appFile'
) {
// Check if this is an app route handler that might support WebSocket
const itemPath = matchedOutput.itemPath
// Try to invoke the route handler and check if it returns a WebSocket upgrade
try {
const result = await handleWebSocketUpgrade(
req,
socket,
head,
itemPath,
parsedUrl
)
if (result.handled) {
return
}
} catch (err) {
debug('WebSocket upgrade handler error:', err)
}
// If not handled as WebSocket, close the socket
return socket.end()
}
// If webSockets is not enabled but we matched an app route, close the socket
if (matchedOutput && matchedOutput.type === 'appFile') {
return socket.end()
}
// Pages router doesn't support WebSocket upgrades
if (matchedOutput) { if (matchedOutput) {
return socket.end() return socket.end()
} }
......
...@@ -303,6 +303,29 @@ export interface RequestMeta { ...@@ -303,6 +303,29 @@ export interface RequestMeta {
location: string location: string
duration: number duration: number
} }
/**
* True when this is a WebSocket upgrade request
*/
isWebSocketUpgrade?: boolean
/**
* The socket from the WebSocket upgrade request
*/
upgradeSocket?: import('stream').Duplex
/**
* The head buffer from the WebSocket upgrade request
*/
upgradeHead?: Buffer
/**
* Internal WebSocket data for bridging streams to the socket
*/
websocketInternal?: {
readable: ReadableStream
writable: WritableStream
}
} }
/** /**
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
export { ImageResponse } from '../spec-extension/image-response' export { ImageResponse } from '../spec-extension/image-response'
export { NextRequest } from '../spec-extension/request' export { NextRequest } from '../spec-extension/request'
export { NextResponse } from '../spec-extension/response' export { NextResponse } from '../spec-extension/response'
export { NextWebSocket } from '../spec-extension/websocket'
export { userAgent, userAgentFromString } from '../spec-extension/user-agent' export { userAgent, userAgentFromString } from '../spec-extension/user-agent'
export { URLPattern } from '../spec-extension/url-pattern' export { URLPattern } from '../spec-extension/url-pattern'
export { after } from '../../after' export { after } from '../../after'
......
...@@ -5,6 +5,12 @@ import { toNodeOutgoingHttpHeaders, validateURL } from '../utils' ...@@ -5,6 +5,12 @@ import { toNodeOutgoingHttpHeaders, validateURL } from '../utils'
import { ReflectAdapter } from './adapters/reflect' import { ReflectAdapter } from './adapters/reflect'
import { ResponseCookies } from './cookies' import { ResponseCookies } from './cookies'
import {
type NextWebSocket,
createWebSocketPair,
WEBSOCKET_INTERNAL,
type WebSocketCloseMessage,
} from './websocket'
const INTERNALS = Symbol('internal response') const INTERNALS = Symbol('internal response')
const REDIRECTS = new Set([301, 302, 303, 307, 308]) const REDIRECTS = new Set([301, 302, 303, 307, 308])
...@@ -33,12 +39,23 @@ function handleMiddlewareField( ...@@ -33,12 +39,23 @@ function handleMiddlewareField(
* *
* Read more: [Next.js Docs: `NextResponse`](https://nextjs.org/docs/app/api-reference/functions/next-response) * Read more: [Next.js Docs: `NextResponse`](https://nextjs.org/docs/app/api-reference/functions/next-response)
*/ */
// WebSocket internal data type
interface WebSocketInternalData {
readable: ReadableStream<
string | ArrayBufferLike | Blob | ArrayBufferView | WebSocketCloseMessage
>
writable: WritableStream
}
export class NextResponse<Body = unknown> extends Response { export class NextResponse<Body = unknown> extends Response {
[INTERNALS]: { [INTERNALS]: {
cookies: ResponseCookies cookies: ResponseCookies
url?: NextURL url?: NextURL
body?: Body body?: Body
} };
// WebSocket internal storage
[WEBSOCKET_INTERNAL]?: WebSocketInternalData
constructor(body?: BodyInit | null, init: ResponseInit = {}) { constructor(body?: BodyInit | null, init: ResponseInit = {}) {
super(body, init) super(body, init)
...@@ -150,6 +167,55 @@ export class NextResponse<Body = unknown> extends Response { ...@@ -150,6 +167,55 @@ export class NextResponse<Body = unknown> extends Response {
handleMiddlewareField(init, headers) handleMiddlewareField(init, headers)
return new NextResponse(null, { ...init, headers }) return new NextResponse(null, { ...init, headers })
} }
/**
* Creates a WebSocket upgrade response. Returns a tuple of [socket, response].
*
* The socket must have `accept()` called before sending messages.
*
* @example
* ```ts
* import { NextResponse } from 'next/server'
*
* export const GET = async () => {
* const [socket, response] = NextResponse.upgrade()
*
* socket.accept()
* socket.send("WELCOME")
*
* socket.addEventListener("message", (event) => {
* socket.send("ECHO: " + event.data)
* })
*
* socket.addEventListener("close", () => {
* console.log("Connection closed")
* })
*
* return response
* }
* ```
*/
static upgrade(init?: {
headers?: HeadersInit
}): [NextWebSocket, NextResponse] {
const { socket, readable, writable } = createWebSocketPair()
const headers = new Headers(init?.headers)
// Mark this response as a WebSocket upgrade
// We use 200 status code because the Web API doesn't allow 101
// The server will detect the x-next-websocket-upgrade header and handle it
headers.set('x-next-websocket-upgrade', '1')
const response = new NextResponse(null, {
status: 200,
headers,
})
// Store the WebSocket streams internally for the server to access
response[WEBSOCKET_INTERNAL] = { readable, writable }
return [socket, response]
}
} }
interface ResponseInit extends globalThis.ResponseInit { interface ResponseInit extends globalThis.ResponseInit {
......
/**
* NextWebSocket - A server-side WebSocket implementation for Next.js route handlers.
*
* This class implements the standard WebSocket interface and is designed to work
* with Next.js route handlers via NextResponse.upgrade().
*
* @example
* ```ts
* import { NextResponse } from 'next/server'
*
* export const GET = async () => {
* const [socket, response] = NextResponse.upgrade()
*
* socket.accept()
* socket.send("WELCOME")
*
* socket.addEventListener("message", (event) => {
* socket.send("ECHO: " + event.data)
* })
*
* return response
* }
* ```
*/
// Internal symbols
export const WEBSOCKET_READABLE = Symbol.for('next.websocket.readable')
export const WEBSOCKET_WRITABLE = Symbol.for('next.websocket.writable')
export const WEBSOCKET_INTERNAL = Symbol.for('next.websocket')
// Message types for internal communication
export interface WebSocketMessage {
type: 'message'
data: string | ArrayBuffer
}
export interface WebSocketCloseMessage {
type: 'close'
code?: number
reason?: string
}
export type WebSocketInternalMessage = WebSocketMessage | WebSocketCloseMessage
/**
* A server-side WebSocket that implements the standard WebSocket interface.
*/
export class NextWebSocket extends EventTarget implements WebSocket {
// WebSocket readyState constants
readonly CONNECTING = 0 as const
readonly OPEN = 1 as const
readonly CLOSING = 2 as const
readonly CLOSED = 3 as const
// WebSocket properties
private _readyState: number = 0 // CONNECTING
binaryType: BinaryType = 'blob'
readonly bufferedAmount: number = 0
readonly extensions: string = ''
readonly protocol: string = ''
readonly url: string = ''
// Event handlers (for compatibility with WebSocket interface)
onopen: ((this: WebSocket, ev: Event) => any) | null = null
onmessage: ((this: WebSocket, ev: MessageEvent) => any) | null = null
onclose: ((this: WebSocket, ev: CloseEvent) => any) | null = null
onerror: ((this: WebSocket, ev: Event) => any) | null = null
// Internal streams for communication
private _readable: ReadableStream<WebSocketInternalMessage>
private _writable: WritableStream<
WebSocketInternalMessage | string | ArrayBufferLike | Blob | ArrayBufferView
>
private _writer: WritableStreamDefaultWriter<
WebSocketInternalMessage | string | ArrayBufferLike | Blob | ArrayBufferView
>
private _accepted: boolean = false
constructor(
readable: ReadableStream<WebSocketInternalMessage>,
writable: WritableStream<
| WebSocketInternalMessage
| string
| ArrayBufferLike
| Blob
| ArrayBufferView
>
) {
super()
this._readable = readable
this._writable = writable
this._writer = writable.getWriter()
}
get readyState(): number {
return this._readyState
}
/**
* Accepts the WebSocket connection. Must be called before sending messages.
* This allows for pre-accept validation of the connection.
*/
accept(): void {
if (this._accepted) {
throw new DOMException(
'WebSocket has already been accepted',
'InvalidStateError'
)
}
if (this._readyState !== this.CONNECTING) {
throw new DOMException(
'WebSocket is not in CONNECTING state',
'InvalidStateError'
)
}
this._accepted = true
this._readyState = this.OPEN
// Dispatch open event
const openEvent = new Event('open')
this.dispatchEvent(openEvent)
this.onopen?.call(this as unknown as WebSocket, openEvent)
// Start reading messages from the client
this._startReading()
}
/**
* Sends data through the WebSocket connection.
*/
send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void {
if (this._readyState === this.CONNECTING) {
throw new DOMException(
'WebSocket is still in CONNECTING state. Call accept() first.',
'InvalidStateError'
)
}
if (this._readyState !== this.OPEN) {
throw new DOMException('WebSocket is not open', 'InvalidStateError')
}
// Write data to the stream
this._writer.write(data).catch((error) => {
// Handle write errors
console.error('WebSocket send error:', error)
})
}
/**
* Closes the WebSocket connection.
*/
close(code?: number, reason?: string): void {
if (this._readyState === this.CLOSING || this._readyState === this.CLOSED) {
return
}
// Validate close code
if (code !== undefined) {
if (code !== 1000 && (code < 3000 || code > 4999)) {
throw new DOMException(
`Invalid close code: ${code}. Must be 1000 or in range 3000-4999.`,
'InvalidAccessError'
)
}
}
// Validate reason length
if (reason !== undefined) {
const encoder = new TextEncoder()
if (encoder.encode(reason).length > 123) {
throw new DOMException(
'Close reason is too long (max 123 bytes)',
'SyntaxError'
)
}
}
this._readyState = this.CLOSING
// Send close message
const closeMessage: WebSocketCloseMessage = {
type: 'close',
code: code ?? 1000,
reason: reason ?? '',
}
this._writer
.write(closeMessage)
.then(() => {
this._writer.close().catch(() => {
// Ignore close errors
})
})
.catch(() => {
// Ignore write errors during close
})
}
/**
* Reads messages from the client and dispatches events.
*/
private async _startReading(): Promise<void> {
const reader = this._readable.getReader()
try {
while (true) {
const { done, value } = await reader.read()
if (done) {
break
}
if (value.type === 'close') {
this._readyState = this.CLOSED
const closeEvent = new CloseEvent('close', {
code: value.code ?? 1000,
reason: value.reason ?? '',
wasClean: true,
})
this.dispatchEvent(closeEvent)
this.onclose?.call(this as unknown as WebSocket, closeEvent)
break
}
if (value.type === 'message') {
const messageEvent = new MessageEvent('message', {
data: value.data,
})
this.dispatchEvent(messageEvent)
this.onmessage?.call(this as unknown as WebSocket, messageEvent)
}
}
} catch (error) {
// Handle read errors
const errorEvent = new Event('error')
this.dispatchEvent(errorEvent)
this.onerror?.call(this as unknown as WebSocket, errorEvent)
} finally {
if (this._readyState !== this.CLOSED) {
this._readyState = this.CLOSED
const closeEvent = new CloseEvent('close', {
code: 1006,
reason: 'Connection closed abnormally',
wasClean: false,
})
this.dispatchEvent(closeEvent)
this.onclose?.call(this as unknown as WebSocket, closeEvent)
}
}
}
}
/**
* Creates a pair of connected streams for WebSocket communication.
* Returns a NextWebSocket and the corresponding streams for the bridge.
*/
export function createWebSocketPair(): {
socket: NextWebSocket
readable: ReadableStream<
string | ArrayBufferLike | Blob | ArrayBufferView | WebSocketCloseMessage
>
writable: WritableStream<WebSocketInternalMessage>
} {
// Streams for client -> server communication (messages from client)
let clientToServerController: ReadableStreamDefaultController<WebSocketInternalMessage>
const clientToServerReadable = new ReadableStream<WebSocketInternalMessage>({
start(controller) {
clientToServerController = controller
},
})
// Streams for server -> client communication (messages from server)
let serverToClientController: ReadableStreamDefaultController<
string | ArrayBufferLike | Blob | ArrayBufferView | WebSocketCloseMessage
>
const serverToClientReadable = new ReadableStream<
string | ArrayBufferLike | Blob | ArrayBufferView | WebSocketCloseMessage
>({
start(controller) {
serverToClientController = controller
},
})
// Writable for the bridge to send messages to the server (user code)
const clientToServerWritable = new WritableStream<WebSocketInternalMessage>({
write(chunk) {
clientToServerController.enqueue(chunk)
},
close() {
clientToServerController.close()
},
})
// Writable for the server (user code) to send messages to the client
const serverToClientWritable = new WritableStream<
WebSocketInternalMessage | string | ArrayBufferLike | Blob | ArrayBufferView
>({
write(chunk) {
// Handle different message types
if (typeof chunk === 'object' && chunk !== null && 'type' in chunk) {
// It's an internal message (close message)
serverToClientController.enqueue(chunk as WebSocketCloseMessage)
} else {
// It's raw data (string, ArrayBuffer, etc.)
serverToClientController.enqueue(
chunk as string | ArrayBufferLike | Blob | ArrayBufferView
)
}
},
close() {
serverToClientController.close()
},
})
// Create the NextWebSocket that user code will interact with
const socket = new NextWebSocket(
clientToServerReadable,
serverToClientWritable
)
return {
socket,
readable: serverToClientReadable, // Bridge reads from this to send to client
writable: clientToServerWritable, // Bridge writes to this from client messages
}
}
/**
* WebSocket Bridge
*
* This module bridges the Web Streams-based NextWebSocket to actual Node.js
* TCP sockets using the 'ws' library for WebSocket protocol handling.
*/
import type { IncomingMessage } from 'http'
import type { Duplex } from 'stream'
import type {
WebSocketInternalMessage,
WebSocketCloseMessage,
} from './spec-extension/websocket'
/**
* Bridges a NextWebSocket (via its streams) to an actual Node.js socket.
*
* @param req - The original HTTP upgrade request
* @param socket - The raw TCP socket from the upgrade event
* @param head - The first packet of the upgraded stream (may be empty)
* @param wsInternal - The internal streams from NextResponse.upgrade()
*/
export async function bridgeWebSocket(
req: IncomingMessage,
socket: Duplex,
head: Buffer,
wsInternal: {
readable: ReadableStream<
string | ArrayBufferLike | Blob | ArrayBufferView | WebSocketCloseMessage
>
writable: WritableStream<WebSocketInternalMessage>
}
): Promise<void> {
// Dynamically import ws to avoid bundling issues
const { WebSocketServer } =
require('next/dist/compiled/ws') as typeof import('next/dist/compiled/ws')
const wsServer = new WebSocketServer({ noServer: true })
return new Promise((resolve, reject) => {
// Cast socket to any since ws expects a net.Socket but we have a Duplex
// This is safe because the Duplex is the socket from the HTTP upgrade
wsServer.handleUpgrade(req, socket as any, head, (nodeWs) => {
const writer = wsInternal.writable.getWriter()
let closed = false
const cleanup = () => {
if (closed) return
closed = true
writer.close().catch(() => {
// Ignore close errors
})
resolve()
}
// Forward messages from client (Node.js WebSocket) to user code (streams)
nodeWs.on(
'message',
(data: Buffer | ArrayBuffer | Buffer[], isBinary: boolean) => {
if (closed) return
let messageData: string | ArrayBuffer
if (Buffer.isBuffer(data)) {
if (isBinary) {
// Create a proper ArrayBuffer from the Buffer
const arrayBuffer = new ArrayBuffer(data.byteLength)
const view = new Uint8Array(arrayBuffer)
for (let i = 0; i < data.byteLength; i++) {
view[i] = data[i]
}
messageData = arrayBuffer
} else {
messageData = data.toString('utf-8')
}
} else if (Array.isArray(data)) {
// Concatenate Buffer array
const concatenated = Buffer.concat(data)
if (isBinary) {
const arrayBuffer = new ArrayBuffer(concatenated.byteLength)
const view = new Uint8Array(arrayBuffer)
for (let i = 0; i < concatenated.byteLength; i++) {
view[i] = concatenated[i]
}
messageData = arrayBuffer
} else {
messageData = concatenated.toString('utf-8')
}
} else {
messageData = data
}
const message: WebSocketInternalMessage = {
type: 'message',
data: messageData,
}
writer.write(message).catch((error) => {
console.error('WebSocket bridge write error:', error)
cleanup()
})
}
)
// Forward close from client to user code
nodeWs.on('close', (code: number, reason: Buffer) => {
if (closed) return
const closeMessage: WebSocketInternalMessage = {
type: 'close',
code,
reason: reason.toString('utf-8'),
}
writer
.write(closeMessage)
.catch(() => {
// Ignore write errors during close
})
.finally(() => {
cleanup()
})
})
nodeWs.on('error', (error) => {
console.error('WebSocket error:', error)
cleanup()
reject(error)
})
// Forward messages from user code (streams) to client (Node.js WebSocket)
const reader = wsInternal.readable.getReader()
const readLoop = async () => {
try {
while (!closed) {
const { done, value } = await reader.read()
if (done) {
// Stream ended, close the WebSocket
if (nodeWs.readyState === nodeWs.OPEN) {
nodeWs.close(1000, 'Stream ended')
}
break
}
// Check if it's a close message
if (
typeof value === 'object' &&
value !== null &&
'type' in value &&
(value as WebSocketCloseMessage).type === 'close'
) {
const closeMsg = value as WebSocketCloseMessage
if (nodeWs.readyState === nodeWs.OPEN) {
nodeWs.close(closeMsg.code ?? 1000, closeMsg.reason ?? '')
}
break
}
// Send regular message
if (nodeWs.readyState === nodeWs.OPEN) {
// Handle different data types
if (typeof value === 'string') {
nodeWs.send(value)
} else if (value instanceof ArrayBuffer) {
nodeWs.send(Buffer.from(value))
} else if (ArrayBuffer.isView(value)) {
nodeWs.send(
Buffer.from(value.buffer, value.byteOffset, value.byteLength)
)
} else if (value instanceof Blob) {
// Convert Blob to ArrayBuffer and send
const arrayBuffer = await value.arrayBuffer()
nodeWs.send(Buffer.from(arrayBuffer))
} else {
// Fallback: try to send as-is
nodeWs.send(value as any)
}
}
}
} catch (error) {
console.error('WebSocket bridge read error:', error)
if (nodeWs.readyState === nodeWs.OPEN) {
nodeWs.close(1011, 'Internal error')
}
} finally {
reader.releaseLock()
cleanup()
}
}
// Start reading from user code
readLoop()
})
})
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
import { NextResponse } from 'next/server'
import { headers } from 'next/headers'
export const GET = async () => {
const [socket, response] = NextResponse.upgrade()
// Get the middleware header if present
const headersList = await headers()
const middlewareHeader = headersList.get('x-middleware-test')
socket.accept()
// Send the middleware header value if present, otherwise just WELCOME
socket.send(middlewareHeader ? `WELCOME:${middlewareHeader}` : 'WELCOME')
const interval = setInterval(() => {
if (socket.readyState === socket.OPEN) {
socket.send('KEEP ALIVE')
}
}, 3000)
socket.onmessage = (event) => {
socket.send('ECHO: ' + event.data)
}
socket.onclose = () => {
clearInterval(interval)
}
return response
}
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
const url = request.nextUrl
// Test: Add a header to all requests
const response = NextResponse.next({
request: {
headers: new Headers({
...Object.fromEntries(request.headers),
'x-middleware-test': 'hello-from-middleware',
}),
},
})
// Test: Redirect /ws-redirect to /ws
if (url.pathname === '/ws-redirect') {
return NextResponse.redirect(new URL('/ws', request.url))
}
// Test: Rewrite /ws-rewrite to /ws
if (url.pathname === '/ws-rewrite') {
return NextResponse.rewrite(new URL('/ws', request.url))
}
// Test: Block /ws-blocked
if (url.pathname === '/ws-blocked') {
return new NextResponse('Blocked by middleware', { status: 403 })
}
return response
}
export const config = {
matcher: ['/ws', '/ws-redirect', '/ws-rewrite', '/ws-blocked'],
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
webSockets: true,
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import WebSocket from 'ws'
describe('websocket', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
})
if (skipped) {
return
}
it('should establish a WebSocket connection', async () => {
const url = new URL('/ws', next.url)
url.protocol = url.protocol.replace('http', 'ws')
const ws = new WebSocket(url.href)
const messages: string[] = []
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error('WebSocket connection timeout'))
}, 5000)
ws.on('open', () => {
clearTimeout(timeout)
resolve()
})
ws.on('error', (err) => {
clearTimeout(timeout)
reject(err)
})
})
expect(ws.readyState).toBe(WebSocket.OPEN)
// Wait for the welcome message
await new Promise<void>((resolve) => {
ws.on('message', (data) => {
messages.push(data.toString())
if (messages.length === 1) {
resolve()
}
})
})
expect(messages[0]).toBe('WELCOME:hello-from-middleware')
ws.close()
})
it('should echo messages back', async () => {
const url = new URL('/ws', next.url)
url.protocol = url.protocol.replace('http', 'ws')
const ws = new WebSocket(url.href)
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error('WebSocket connection timeout'))
}, 5000)
ws.on('open', () => {
clearTimeout(timeout)
resolve()
})
ws.on('error', (err) => {
clearTimeout(timeout)
reject(err)
})
})
// Skip the WELCOME message
await new Promise<void>((resolve) => {
ws.once('message', () => resolve())
})
// Send a test message
ws.send('Hello, World!')
// Wait for the echo response
const echoResponse = await new Promise<string>((resolve) => {
ws.once('message', (data) => {
resolve(data.toString())
})
})
expect(echoResponse).toBe('ECHO: Hello, World!')
ws.close()
})
it('should handle multiple concurrent connections', async () => {
const url = new URL('/ws', next.url)
url.protocol = url.protocol.replace('http', 'ws')
const connections: WebSocket[] = []
const messagePromises: Promise<string>[] = []
// Create 3 concurrent connections
for (let i = 0; i < 3; i++) {
const ws = new WebSocket(url.href)
connections.push(ws)
// Wait for connection
await new Promise<void>((resolve, reject) => {
ws.on('open', () => resolve())
ws.on('error', reject)
})
// Skip WELCOME message
await new Promise<void>((resolve) => {
ws.once('message', () => resolve())
})
// Send a message and collect the response promise
const messagePromise = new Promise<string>((resolve) => {
ws.once('message', (data) => resolve(data.toString()))
})
messagePromises.push(messagePromise)
ws.send(`Message from connection ${i}`)
}
// Wait for all responses
const responses = await Promise.all(messagePromises)
// Verify each connection got its own echo
for (let i = 0; i < 3; i++) {
expect(responses[i]).toBe(`ECHO: Message from connection ${i}`)
}
// Close all connections
for (const ws of connections) {
ws.close()
}
})
it('should handle connection close gracefully', async () => {
const url = new URL('/ws', next.url)
url.protocol = url.protocol.replace('http', 'ws')
const ws = new WebSocket(url.href)
await new Promise<void>((resolve, reject) => {
ws.on('open', () => resolve())
ws.on('error', reject)
})
// Close with a custom close code and reason
ws.close(1000, 'Test close')
// Wait for the close event
await new Promise<void>((resolve) => {
ws.on('close', (code, reason) => {
expect(code).toBe(1000)
resolve()
})
})
expect(ws.readyState).toBe(WebSocket.CLOSED)
})
it('should receive keep-alive messages', async () => {
const url = new URL('/ws', next.url)
url.protocol = url.protocol.replace('http', 'ws')
const ws = new WebSocket(url.href)
const messages: string[] = []
await new Promise<void>((resolve, reject) => {
ws.on('open', () => resolve())
ws.on('error', reject)
})
ws.on('message', (data) => {
messages.push(data.toString())
})
// Wait for WELCOME + at least one KEEP ALIVE message (sent every 3 seconds)
await retry(
async () => {
expect(messages.some((m) => m.startsWith('WELCOME'))).toBe(true)
expect(messages.some((m) => m === 'KEEP ALIVE')).toBe(true)
},
5000,
500
)
ws.close()
})
describe('middleware integration', () => {
it('should pass middleware headers to WebSocket route handler', async () => {
const url = new URL('/ws', next.url)
url.protocol = url.protocol.replace('http', 'ws')
const ws = new WebSocket(url.href)
const messages: string[] = []
// Set up message listener before waiting for open to avoid race conditions
ws.on('message', (data) => {
messages.push(data.toString())
})
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error('WebSocket connection timeout'))
}, 5000)
ws.on('open', () => {
clearTimeout(timeout)
resolve()
})
ws.on('error', (err) => {
clearTimeout(timeout)
reject(err)
})
})
// Wait for the welcome message
await retry(async () => {
expect(messages.some((m) => m.startsWith('WELCOME'))).toBe(true)
})
// Find the welcome message
const welcomeMessage = messages.find((m) => m.startsWith('WELCOME'))
// Middleware should have added the header, which the route handler includes in the welcome message
expect(welcomeMessage).toBe('WELCOME:hello-from-middleware')
ws.close()
})
it('should handle middleware rewrite for WebSocket', async () => {
// Connect to /ws-rewrite which middleware rewrites to /ws
const url = new URL('/ws-rewrite', next.url)
url.protocol = url.protocol.replace('http', 'ws')
const ws = new WebSocket(url.href)
const messages: string[] = []
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error('WebSocket connection timeout'))
}, 5000)
ws.on('open', () => {
clearTimeout(timeout)
resolve()
})
ws.on('error', (err) => {
clearTimeout(timeout)
reject(err)
})
})
// Wait for the welcome message
await new Promise<void>((resolve) => {
ws.on('message', (data) => {
messages.push(data.toString())
if (messages.length === 1) {
resolve()
}
})
})
// Should have connected successfully via the rewrite
expect(messages[0]).toMatch(/^WELCOME/)
ws.close()
})
it('should handle middleware redirect for WebSocket', async () => {
// Connect to /ws-redirect which middleware redirects to /ws
const url = new URL('/ws-redirect', next.url)
url.protocol = url.protocol.replace('http', 'ws')
// Create WebSocket with followRedirects enabled
const ws = new WebSocket(url.href, {
followRedirects: true,
} as WebSocket.ClientOptions)
// The ws library should follow the redirect and connect successfully
const result = await new Promise<
'connected' | 'error' | 'unexpected-response'
>((resolve) => {
const timeout = setTimeout(() => {
resolve('error')
}, 5000)
ws.on('open', () => {
clearTimeout(timeout)
resolve('connected')
})
ws.on('error', () => {
clearTimeout(timeout)
resolve('error')
})
ws.on('unexpected-response', () => {
clearTimeout(timeout)
resolve('unexpected-response')
})
})
// The ws library follows redirects when followRedirects is true
expect(result).toBe('connected')
expect(ws.readyState).toBe(WebSocket.OPEN)
ws.close()
})
it('should handle middleware blocking WebSocket', async () => {
// Connect to /ws-blocked which middleware blocks with 403
const url = new URL('/ws-blocked', next.url)
url.protocol = url.protocol.replace('http', 'ws')
const ws = new WebSocket(url.href)
// The connection should fail because middleware returns 403
const result = await new Promise<
{ type: 'error'; error: Error } | { type: 'unexpected-open' }
>((resolve) => {
const timeout = setTimeout(() => {
resolve({
type: 'error',
error: new Error('timeout - server did not respond'),
})
}, 5000)
ws.on('open', () => {
clearTimeout(timeout)
resolve({ type: 'unexpected-open' })
})
ws.on('error', (err) => {
clearTimeout(timeout)
resolve({ type: 'error', error: err })
})
ws.on('unexpected-response', (_req, res) => {
clearTimeout(timeout)
resolve({
type: 'error',
error: new Error(`Unexpected HTTP response: ${res.statusCode}`),
})
})
})
// Connection should have failed with an error (403 from middleware)
expect(result.type).toBe('error')
expect(ws.readyState).not.toBe(WebSocket.OPEN)
})
})
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment