Skip to content

Fix unmatched WebSocket upgrade requests being closed #57245

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 23, 2023
Merged
Show file tree
Hide file tree
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
5 changes: 3 additions & 2 deletions packages/next/src/server/lib/router-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -602,8 +602,9 @@ export async function initialize(opts: {
if (parsedUrl.protocol) {
return await proxyRequest(req, socket as any, parsedUrl, head)
}
// no match close socket
socket.end()

// If there's no matched output, we don't handle the request as user's
// custom WS server may be listening on the same path.
} catch (err) {
console.error('Error handling upgrade request', err)
socket.end()
Expand Down
12 changes: 12 additions & 0 deletions test/e2e/socket-io/app/layout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export const metadata = {
title: 'Next.js',
description: 'Generated by Next.js',
}

export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
41 changes: 41 additions & 0 deletions test/e2e/socket-io/app/page.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
'use client'

import { useEffect, useState } from 'react'
import io from 'socket.io-client'

let socket

export default function Home() {
const [value, setValue] = useState('')

const socketInitializer = async () => {
// We call this just to make sure we turn on the websocket server
await fetch('/api/socket')

socket = io(undefined, {
path: '/api/my_awesome_socket',
})

socket.on('connect', () => {
console.log('Connected', socket.id)
})

socket.on('newIncomingMessage', (msg) => {
setValue(msg)
})
}

const sendMessageHandler = async (e) => {
if (!socket) return
const value = e.target.value

setValue(value)
socket.emit('createdMessage', value)
}

useEffect(() => {
socketInitializer()
}, [])

return <input value={value} onChange={sendMessageHandler} />
}
43 changes: 43 additions & 0 deletions test/e2e/socket-io/index.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { createNextDescribe } from 'e2e-utils'
import { check } from 'next-test-utils'

createNextDescribe(
'socket-io',
{
files: __dirname,
dependencies: {
'socket.io': '4.7.2',
'socket.io-client': '4.7.2',
'utf-8-validate': '6.0.3',
bufferutil: '4.0.8',
},
},
({ next }) => {
it('should support socket.io without falling back to polling', async () => {
let requestsCount = 0

const browser1 = await next.browser(next.url, '/')
const browser2 = await next.browser(next.url, '/', {
beforePageLoad(page) {
page.on('request', () => {
requestsCount++
})
},
})

const input1 = await browser1.elementByCss('input')
const input2 = await browser2.elementByCss('input')

await input1.fill('hello world')
await check(() => input2.inputValue(), /hello world/)

const currentRequestsCount = requestsCount

await input1.fill('123456')
await check(() => input2.inputValue(), /123456/)

// There should be no new requests (polling) and using the existing WS connection
expect(requestsCount).toBe(currentRequestsCount)
})
}
)
29 changes: 29 additions & 0 deletions test/e2e/socket-io/pages/api/socket.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { Server } from 'socket.io'

function onSocketConnection(io, socket) {
const createdMessage = (msg) => {
socket.broadcast.emit('newIncomingMessage', msg)
}

socket.on('createdMessage', createdMessage)
}

export default function handler(req, res) {
if (res.socket.server.io) {
res.end()
return
}

const io = new Server(res.socket.server, {
path: '/api/my_awesome_socket',
})
res.socket.server.io = io

const onConnection = (socket) => {
onSocketConnection(io, socket)
}

io.on('connection', onConnection)

res.end()
}