Skip to content

Commit c18fcf2

Browse files
kjugidevjiwonchoiijjk
authored
Fix hmr assetPrefix escaping and reuse logic from other files (#67983)
<!-- Thanks for opening a PR! Your contribution is much appreciated. To make sure your PR is handled as smoothly as possible we request that you follow the checklist sections below. Choose the right checklist for the change(s) that you're making: ## For Contributors ### Improving Documentation - Run `pnpm prettier-fix` to fix formatting issues before opening the PR. - Read the Docs Contribution Guide to ensure your contribution follows the docs guidelines: https://nextjs.org/docs/community/contribution-guide ### Adding or Updating Examples - The "examples guidelines" are followed from our contributing doc https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md - Make sure the linting passes by running `pnpm build && pnpm lint`. See https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md ### Fixing a bug - Related issues linked using `fixes #number` - Tests added. See: https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs - Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md ### Adding a feature - Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. (A discussion must be opened, see https://github.com/vercel/next.js/discussions/new?category=ideas) - Related issues/discussions are linked using `fixes #number` - e2e tests added (https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs) - Documentation added - Telemetry added. In case of a feature if it's used or not. - Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md ## For Maintainers - Minimal description (aim for explaining to someone not on the team to understand the PR) - When linking to a Slack thread, you might want to share details of the conclusion - Link both the Linear (Fixes NEXT-xxx) and the GitHub issues - Add review comments if necessary to explain to the reviewer the logic behind a change ### What? ### Why? ### How? Closes NEXT- Fixes # --> ### Fixing a bug fixes #63820 fixes #55320 fixes #52931 In one of the issues, there was a suggestion to delete `assetPrefix` from `next.config`. It helps if you have `assetPrefix: '/'`. Otherwise, you probably won't face this problem. **Explanation:** The problem lies where the browser tries to connect and where websocket is available on the server. Adjust the condition for `prefix` in `get-socket-url` as it can return `''` which will lead to `//` in the url. The browser wants to connect to `ws://localhost:3000/_next/webpack-hmr` While internally next exposes the web socket under `ws://localhost:3000//_next/webpack-hmr` - you can connect to it via wscat, postman or whatever. As the path is different it does not handle HMR requests in the browser. In addition to that - Reuse logic and extract separate files as a helper in shared/lib. | Before | After | | ------ | ------- | | ![before - latest canary branch](https://github.com/user-attachments/assets/c26c8b20-1352-49c6-a099-101394438ba0) before - latest canary branch - we can't establish a connection to HMR ws | ![after](https://github.com/user-attachments/assets/26500e68-bc4d-44ca-b418-f9bda6bc9aa6) same example with local changes - connected to ws | --------- Co-authored-by: Jiwon Choi <[email protected]> Co-authored-by: JJ Kasper <[email protected]>
1 parent 87464d0 commit c18fcf2

File tree

5 files changed

+866
-925
lines changed

5 files changed

+866
-925
lines changed
Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { normalizedAssetPrefix } from '../../../../../shared/lib/normalized-asset-prefix'
2+
13
function getSocketProtocol(assetPrefix: string): string {
24
let protocol = window.location.protocol
35

@@ -9,18 +11,16 @@ function getSocketProtocol(assetPrefix: string): string {
911
return protocol === 'http:' ? 'ws' : 'wss'
1012
}
1113

12-
export function getSocketUrl(assetPrefix: string): string {
14+
export function getSocketUrl(assetPrefix: string | undefined): string {
1315
const { hostname, port } = window.location
14-
const protocol = getSocketProtocol(assetPrefix)
15-
const normalizedAssetPrefix = assetPrefix.replace(/^\/+/, '')
16-
17-
let url = `${protocol}://${hostname}:${port}${
18-
normalizedAssetPrefix ? `/${normalizedAssetPrefix}` : ''
19-
}`
16+
const protocol = getSocketProtocol(assetPrefix || '')
17+
const prefix = normalizedAssetPrefix(assetPrefix)
2018

21-
if (normalizedAssetPrefix.startsWith('http')) {
22-
url = `${protocol}://${normalizedAssetPrefix.split('://', 2)[1]}`
19+
// if original assetPrefix is a full URL with protocol
20+
// we just update to use the correct `ws` protocol
21+
if (assetPrefix?.replace(/^\/+/, '').includes('://')) {
22+
return `${protocol}://${prefix}`
2323
}
2424

25-
return url
25+
return `${protocol}://${hostname}:${port}${prefix}`
2626
}

packages/next/src/client/components/react-dev-overlay/pages/websocket.ts

Lines changed: 2 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,12 @@
11
import type { HMR_ACTION_TYPES } from '../../../../server/dev/hot-reloader-types'
2+
import { getSocketUrl } from '../internal/helpers/get-socket-url'
23

34
let source: WebSocket
45

56
type ActionCallback = (action: HMR_ACTION_TYPES) => void
67

78
const eventCallbacks: Array<ActionCallback> = []
89

9-
function getSocketProtocol(assetPrefix: string): string {
10-
let protocol = location.protocol
11-
12-
try {
13-
// assetPrefix is a url
14-
protocol = new URL(assetPrefix).protocol
15-
} catch {}
16-
17-
return protocol === 'http:' ? 'ws' : 'wss'
18-
}
19-
2010
export function addMessageListener(callback: ActionCallback) {
2111
eventCallbacks.push(callback)
2212
}
@@ -62,17 +52,7 @@ export function connectHMR(options: { path: string; assetPrefix: string }) {
6252
timer = setTimeout(init, reconnections > 5 ? 5000 : 1000)
6353
}
6454

65-
const { hostname, port } = location
66-
const protocol = getSocketProtocol(options.assetPrefix || '')
67-
const assetPrefix = options.assetPrefix.replace(/^\/+/, '')
68-
69-
let url = `${protocol}://${hostname}:${port}${
70-
assetPrefix ? `/${assetPrefix}` : ''
71-
}`
72-
73-
if (assetPrefix.startsWith('http')) {
74-
url = `${protocol}://${assetPrefix.split('://', 2)[1]}`
75-
}
55+
const url = getSocketUrl(options.assetPrefix)
7656

7757
source = new window.WebSocket(`${url}${options.path}`)
7858
source.onopen = handleOnline

packages/next/src/server/lib/router-server.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ import {
4545
HMR_ACTIONS_SENT_TO_BROWSER,
4646
type AppIsrManifestAction,
4747
} from '../dev/hot-reloader-types'
48+
import { normalizedAssetPrefix } from '../../shared/lib/normalized-asset-prefix'
4849

4950
const debug = setupDebug('next:router-server:main')
5051
const isNextFont = (pathname: string | null) =>
@@ -662,8 +663,14 @@ export async function initialize(opts: {
662663
if (opts.dev && developmentBundler && req.url) {
663664
const { basePath, assetPrefix } = config
664665

666+
let hmrPrefix = basePath
667+
668+
// assetPrefix overrides basePath for HMR path
669+
if (assetPrefix) {
670+
hmrPrefix = normalizedAssetPrefix(assetPrefix)
671+
}
665672
const isHMRRequest = req.url.startsWith(
666-
ensureLeadingSlash(`${assetPrefix || basePath}/_next/webpack-hmr`)
673+
ensureLeadingSlash(`${hmrPrefix}/_next/webpack-hmr`)
667674
)
668675

669676
// only handle HMR requests if the basePath in the request
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
export function normalizedAssetPrefix(assetPrefix: string | undefined): string {
2+
const escapedAssetPrefix = assetPrefix?.replace(/^\/+/, '') || false
3+
4+
// assetPrefix as a url
5+
if (escapedAssetPrefix && escapedAssetPrefix.startsWith('://')) {
6+
return escapedAssetPrefix.split('://', 2)[1]
7+
}
8+
9+
// assetPrefix is set to `undefined` or '/'
10+
if (!escapedAssetPrefix) {
11+
return ''
12+
}
13+
14+
// assetPrefix is a common path but escaped so let's add one leading slash
15+
return `/${escapedAssetPrefix}`
16+
}

0 commit comments

Comments
 (0)