Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 24 additions & 12 deletions packages/next/src/server/next.ts
Original file line number Diff line number Diff line change
Expand Up @@ -392,21 +392,36 @@ class NextCustomServer implements NextWrapperServer {
quiet: this.options.quiet,
})
this.init = initResult
this.setupWebSocketHandler(this.options.httpServer)
}

private setupWebSocketHandler(
customServer?: import('http').Server,
_req?: IncomingMessage
) {
private setupWebSocketHandler(customServer?: import('http').Server) {
if (!this.didWebSocketSetup) {
this.didWebSocketSetup = true
customServer = customServer || (_req?.socket as any)?.server

if (customServer) {
customServer.on('upgrade', async (req, socket, head) => {
this.upgradeHandler(req, socket, head)
const server = customServer
if (server) {
server.on('upgrade', (req, socket, head) => {
try {
// Basic handshake guards before delegating:
const toStr = (v: string | string[] | undefined) =>
Array.isArray(v) ? v.join(',') : v || ''
const isGet = req.method === 'GET'
const upgrade = toStr(req.headers.upgrade).toLowerCase()
const connection = toStr(req.headers.connection).toLowerCase()
if (!isGet || upgrade !== 'websocket' || !connection.includes('upgrade')) {
socket.write('HTTP/1.1 400 Bad Request\r\n\r\n')
socket.destroy()
return
}
Promise.resolve(this.upgradeHandler(req, socket, head)).catch(() => {
try { socket.destroy() } catch {}
})
} catch {
try { socket.destroy() } catch {}
}
})
}

}
}

Expand All @@ -416,8 +431,6 @@ class NextCustomServer implements NextWrapperServer {
res: ServerResponse,
parsedUrl?: UrlWithParsedQuery
) => {
this.setupWebSocketHandler(this.options.httpServer, req)

if (parsedUrl) {
req.url = formatUrl(parsedUrl)
}
Expand All @@ -428,7 +441,6 @@ class NextCustomServer implements NextWrapperServer {

async render(...args: Parameters<NextWrapperServer['render']>) {
let [req, res, pathname, query, parsedUrl] = args
this.setupWebSocketHandler(this.options.httpServer, req as IncomingMessage)

if (!pathname.startsWith('/')) {
console.error(`Cannot render page with path "${pathname}"`)
Expand Down
Loading