Unverified Commit 30dd3cc2 authored by Genet Schneider's avatar Genet Schneider Committed by GitHub

Account for `assetPrefix` when initializing HMR connection (#30632)

parent ec191982
...@@ -89,6 +89,9 @@ addMessageListener((event) => { ...@@ -89,6 +89,9 @@ addMessageListener((event) => {
} }
}) })
connectHMR({ path: `${assetPrefix}/_next/webpack-hmr` }) connectHMR({
assetPrefix,
path: '/_next/webpack-hmr',
})
displayContent() displayContent()
initOnDemandEntries() initOnDemandEntries()
...@@ -13,6 +13,7 @@ export function sendMessage(data: any) { ...@@ -13,6 +13,7 @@ export function sendMessage(data: any) {
export function connectHMR(options: { export function connectHMR(options: {
path: string path: string
assetPrefix: string
timeout: number timeout: number
log?: boolean log?: boolean
}) { }) {
...@@ -30,8 +31,18 @@ export function connectHMR(options: { ...@@ -30,8 +31,18 @@ export function connectHMR(options: {
function init() { function init() {
if (source) source.close() if (source) source.close()
const { protocol, hostname, port } = location const { hostname, port } = location
const url = `${protocol === 'http:' ? 'ws' : 'wss'}://${hostname}:${port}` const protocol = location.protocol === 'http:' ? 'ws' : 'wss'
const assetPrefix = options.assetPrefix.replace(/^\/+/, '')
let url = `${protocol}://${hostname}:${port}${
assetPrefix ? `/${assetPrefix}` : ''
}`
if (assetPrefix.startsWith('http')) {
url = `${protocol}://${assetPrefix.split('://')[1]}`
}
source = new window.WebSocket(`${url}${options.path}`) source = new window.WebSocket(`${url}${options.path}`)
source.onopen = handleOnline source.onopen = handleOnline
source.onerror = handleDisconnect source.onerror = handleDisconnect
......
...@@ -24,7 +24,7 @@ const { ...@@ -24,7 +24,7 @@ const {
const prefix = assetPrefix || '' const prefix = assetPrefix || ''
const webpackHMR = initWebpackHMR() const webpackHMR = initWebpackHMR()
connectHMR({ path: `${prefix}/_next/webpack-hmr` }) connectHMR({ assetPrefix: prefix, path: '/_next/webpack-hmr' })
window.next = { window.next = {
version, version,
......
...@@ -478,10 +478,26 @@ export default class DevServer extends Server { ...@@ -478,10 +478,26 @@ export default class DevServer extends Server {
`Invalid IncomingMessage received, make sure http.createServer is being used to handle requests.` `Invalid IncomingMessage received, make sure http.createServer is being used to handle requests.`
) )
} else { } else {
const { basePath } = this.nextConfig
server.on('upgrade', (req, socket, head) => { server.on('upgrade', (req, socket, head) => {
let assetPrefix = (this.nextConfig.assetPrefix || '').replace(
/^\/+/,
''
)
// assetPrefix can be a proxy server with a url locally
// if so, it's needed to send these HMR requests with a rewritten url directly to /_next/webpack-hmr
// otherwise account for a path-like prefix when listening to socket events
if (assetPrefix.startsWith('http')) {
assetPrefix = ''
} else if (assetPrefix) {
assetPrefix = `/${assetPrefix}`
}
if ( if (
req.url?.startsWith( req.url?.startsWith(
`${this.nextConfig.basePath || ''}/_next/webpack-hmr` `${basePath || assetPrefix || ''}/_next/webpack-hmr`
) )
) { ) {
this.hotReloader?.onHMR(req, socket, head) this.hotReloader?.onHMR(req, socket, head)
......
module.exports = { module.exports = {
assetPrefix: 'foo',
onDemandEntries: { onDemandEntries: {
maxInactiveAge: 1000 * 5, maxInactiveAge: 1000 * 5,
}, },
......
const http = require('http')
const next = require('next')
const { assetPrefix } = require('./next.config')
const dev = process.env.NODE_ENV !== 'production'
const dir = __dirname
const port = process.env.PORT || 3000
function rewriteAssetPrefix(req) {
if (assetPrefix) {
req.url = req.url.replace(`${assetPrefix}/`, '')
}
}
const app = next({ dev, dir })
const nextReqHandler = app.getRequestHandler()
app.prepare().then(() => {
const server = new http.Server((req, res) => {
rewriteAssetPrefix(req)
return nextReqHandler(req, res)
})
server.listen(port, (err) => {
if (err) {
throw err
}
console.log(`> Ready on http://localhost:${port}`)
})
})
...@@ -2,24 +2,44 @@ ...@@ -2,24 +2,44 @@
import WebSocket from 'ws' import WebSocket from 'ws'
import { join } from 'path' import { join } from 'path'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import getPort from 'get-port'
import clone from 'clone'
import { import {
renderViaHTTP, renderViaHTTP,
findPort, fetchViaHTTP,
launchApp,
killApp, killApp,
waitFor, waitFor,
check, check,
getBrowserBodyText, getBrowserBodyText,
getPageFileFromBuildManifest, getPageFileFromBuildManifest,
getBuildManifest, getBuildManifest,
initNextServerScript,
} from 'next-test-utils' } from 'next-test-utils'
import { assetPrefix } from '../next.config'
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
const context = {} const context = {}
const startServer = async (optEnv = {}, opts) => {
const scriptPath = join(appDir, 'server.js')
context.appPort = await getPort()
const env = Object.assign(
{},
clone(process.env),
{ PORT: `${context.appPort}` },
optEnv
)
context.server = await initNextServerScript(scriptPath, /ready on/i, env)
}
const doPing = (page) => { const doPing = (page) => {
return new Promise((resolve) => { return new Promise((resolve) => {
context.ws.onmessage = () => resolve() context.ws.onmessage = (e) => {
console.log(e)
resolve()
}
context.ws.send(JSON.stringify({ event: 'ping', page })) context.ws.send(JSON.stringify({ event: 'ping', page }))
}) })
} }
...@@ -27,15 +47,26 @@ const doPing = (page) => { ...@@ -27,15 +47,26 @@ const doPing = (page) => {
describe('On Demand Entries', () => { describe('On Demand Entries', () => {
it('should pass', () => {}) it('should pass', () => {})
beforeAll(async () => { beforeAll(async () => {
context.appPort = await findPort() await startServer()
context.server = await launchApp(appDir, context.appPort)
// Send an initial request to nextjs to establish an 'upgrade' listener
// If we send the websocket request as the first thing, it will result in 404 due to listener not set yet
// This is by design as the 'upgrade' listener is set during the first request run
await fetchViaHTTP(context.appPort, '/')
await new Promise((resolve) => { await new Promise((resolve, reject) => {
context.ws = new WebSocket( context.ws = new WebSocket(
`ws://localhost:${context.appPort}/_next/webpack-hmr` `ws://localhost:${context.appPort}${
assetPrefix ? `/${assetPrefix}` : ''
}/_next/webpack-hmr`
) )
context.ws.on('open', () => resolve()) context.ws.on('open', () => resolve())
context.ws.on('error', console.error) context.ws.on('error', (err) => {
console.error(err)
context.ws.close()
reject()
})
}) })
}) })
afterAll(() => { afterAll(() => {
......
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