Unverified Commit 4c35b7e7 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add warning on stalled page load possibly from too many tabs open (#6514)

* Add warning on stalled page load possibly from too many tabs open

* Add test for stalled warning

* Update onDemand pinging to close on routeChangeStart and added
warning when onDemand handler detects multiple tabs from the same
browser
parent 5034e4e1
# Multiple Tabs
#### Why This Error Occurred
In development mode Next.js creates 2 persistent connections to the server to receive hot updates and to keep pages active. Each browser has their own limit for the number of concurrent connections to a specific server a site is allowed to have so if you open the same Next.js site in multiple tabs of the same browser you could exceed your browser's limit.
More info here: https://tools.ietf.org/html/rfc6202#section-5.1
#### Possible Ways to Fix It
- Don't have too many tabs open to the same Next.js site open in development in the same browser at the same time.
- If using Firefox you can increase this limit by navigating to `about:config` and setting `network.http.max-persistent-connections-per-server` to a higher number
/* global window */ /* global window */
import Router from 'next/router' import Router from 'next/router'
import { setupPing, currentPage } from './on-demand-entries-utils' import { setupPing, currentPage, closePing } from './on-demand-entries-utils'
export default async ({ assetPrefix }) => { export default async ({ assetPrefix }) => {
Router.ready(() => { Router.ready(() => {
Router.events.on(
'routeChangeStart',
() => closePing()
)
Router.events.on( Router.events.on(
'routeChangeComplete', 'routeChangeComplete',
setupPing.bind(this, assetPrefix, () => Router.pathname) setupPing.bind(this, assetPrefix, () => Router.pathname)
......
...@@ -7,16 +7,18 @@ export let currentPage ...@@ -7,16 +7,18 @@ export let currentPage
let retryTimeout let retryTimeout
const retryWait = 5000 const retryWait = 5000
export function closePing () {
if (evtSource) evtSource.close()
}
export function setupPing (assetPrefix, pathnameFn, retry) { export function setupPing (assetPrefix, pathnameFn, retry) {
const pathname = pathnameFn() const pathname = pathnameFn()
// Make sure to only create new EventSource request if page has changed // Make sure to only create new EventSource request if page has changed
if (pathname === currentPage && !retry) return if (pathname === currentPage && !retry) return
// close current EventSource connection
if (evtSource) {
evtSource.close()
}
currentPage = pathname currentPage = pathname
// close current EventSource connection
closePing()
const url = `${assetPrefix}/_next/on-demand-entries-ping?page=${currentPage}` const url = `${assetPrefix}/_next/on-demand-entries-ping?page=${currentPage}`
evtSource = new window.EventSource(url) evtSource = new window.EventSource(url)
......
...@@ -33,7 +33,7 @@ export default function onDemandEntryHandler (devMiddleware, multiCompiler, { ...@@ -33,7 +33,7 @@ export default function onDemandEntryHandler (devMiddleware, multiCompiler, {
pagesBufferLength pagesBufferLength
}) { }) {
const pagesDir = join(dir, 'pages') const pagesDir = join(dir, 'pages')
const clients = new Set() const clients = new Map()
const evtSourceHeaders = { const evtSourceHeaders = {
'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Origin': '*',
'Content-Type': 'text/event-stream;charset=utf-8', 'Content-Type': 'text/event-stream;charset=utf-8',
...@@ -152,7 +152,7 @@ export default function onDemandEntryHandler (devMiddleware, multiCompiler, { ...@@ -152,7 +152,7 @@ export default function onDemandEntryHandler (devMiddleware, multiCompiler, {
disposeHandler.unref() disposeHandler.unref()
function stop () { function stop () {
clients.forEach(client => client.end()) clients.forEach((id, client) => client.end())
clearInterval(disposeHandler) clearInterval(disposeHandler)
stopped = true stopped = true
doneCallbacks = null doneCallbacks = null
...@@ -292,7 +292,24 @@ export default function onDemandEntryHandler (devMiddleware, multiCompiler, { ...@@ -292,7 +292,24 @@ export default function onDemandEntryHandler (devMiddleware, multiCompiler, {
req.socket.setKeepAlive(true) req.socket.setKeepAlive(true)
res.writeHead(200, evtSourceHeaders) res.writeHead(200, evtSourceHeaders)
res.write('\n') res.write('\n')
clients.add(res)
const startId = req.headers['user-agent'] + req.connection.remoteAddress
let clientId = startId
let numSameClient = 0
while (clients.has(clientId)) {
numSameClient++
clientId = startId + numSameClient
}
if (numSameClient > 1) {
// If the user has too many tabs with Next.js open in the same browser,
// they might be exceeding the max number of concurrent request.
// This varies per browser so we can only guess if this is the cause of
// a slow request and show a warning that this might be why
console.warn(`\nWarn: You are opening multiple tabs of the same site in the same browser, this could cause requests to stall. https://err.sh/zeit/next.js/multi-tabs`)
}
clients.set(clientId, res)
const runPing = () => { const runPing = () => {
const data = handlePing(query.page) const data = handlePing(query.page)
...@@ -302,7 +319,7 @@ export default function onDemandEntryHandler (devMiddleware, multiCompiler, { ...@@ -302,7 +319,7 @@ export default function onDemandEntryHandler (devMiddleware, multiCompiler, {
const pingInterval = setInterval(() => runPing(), 5000) const pingInterval = setInterval(() => runPing(), 5000)
req.on('close', () => { req.on('close', () => {
clients.delete(res) clients.delete(clientId)
clearInterval(pingInterval) clearInterval(pingInterval)
}) })
// Do initial ping right after EventSource is finished being set up // Do initial ping right after EventSource is finished being set up
......
setTimeout(() => process.exit(0), 5 * 1000)
module.exports = {}
export default function Index (props) {
return (
<div>Index Page</div>
)
}
/* eslint-env jest */
/* global jasmine */
import { join } from 'path'
import webdriver from 'next-webdriver'
import {
runNextCommand,
findPort,
waitFor
} from 'next-test-utils'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 30
describe('Promise in next config', () => {
it('should show warning when multiple tabs are open in the same browser', async () => {
const port = await findPort()
const runPromise = runNextCommand(
['dev', join(__dirname, '..'), '-p', port],
{ stderr: true }
).then(({ stderr }) => {
expect(stderr).toMatch(/Warn: You are opening multiple tabs of the same site in the same browser, this could cause requests to stall/)
})
await waitFor(1000)
const browser = await webdriver(port, '/')
await browser.eval(`window.copy1 = window.open('/', '_blank')`)
await browser.eval(`window.copy2 = window.open('/', '_blank')`)
await waitFor(1000)
await browser.eval(`window.copy1.close()`)
await browser.eval(`window.copy2.close()`)
browser.close()
await runPromise
})
})
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