Skip to content
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

Enable windowHistorySupport by default #60557

Merged
merged 2 commits into from
Jan 12, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ For a full list of `useRouter` methods, see the [API reference](/docs/app/api-re

Next.js allows you to use the native [`window.history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState) and [`window.history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState) methods to update the browser's history stack without reloading the page.

This behavior is enabled with the Next.js [`windowHistorySupport`](/docs/app/api-reference/next-config-js/windowHistorySupport) config option. When the flag is set to `true`, `pushState` and `replaceState` calls integrate into the Next.js Router, allowing you to sync with [`usePathname`](/docs/app/api-reference/functions/use-pathname) and [`useSearchParams`](/docs/app/api-reference/functions/use-search-params).
`pushState` and `replaceState` calls integrate into the Next.js Router, allowing you to sync with [`usePathname`](/docs/app/api-reference/functions/use-pathname) and [`useSearchParams`](/docs/app/api-reference/functions/use-search-params).

### `window.history.pushState`

Expand Down

This file was deleted.

3 changes: 0 additions & 3 deletions packages/next/src/build/webpack/plugins/define-env-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,6 @@ export function getDefineEnv({
isEdgeServer ? 'edge' : isNodeServer ? 'nodejs' : ''
),
'process.env.NEXT_MINIMAL': JSON.stringify(''),
'process.env.__NEXT_WINDOW_HISTORY_SUPPORT': JSON.stringify(
config.experimental.windowHistorySupport
),
'process.env.__NEXT_PPR': JSON.stringify(config.experimental.ppr === true),
'process.env.__NEXT_ACTIONS_DEPLOYMENT_ID': JSON.stringify(
config.experimental.useDeploymentIdServerActions
Expand Down
112 changes: 53 additions & 59 deletions packages/next/src/client/components/app-router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -122,10 +122,7 @@ function HistoryUpdater({
useInsertionEffect(() => {
const { tree, pushRef, canonicalUrl } = appRouterState
const historyState = {
...(process.env.__NEXT_WINDOW_HISTORY_SUPPORT &&
pushRef.preserveCustomHistoryState
? window.history.state
: {}),
...(pushRef.preserveCustomHistoryState ? window.history.state : {}),
// Identifier is shortened intentionally.
// __NA is used to identify if the history entry can be handled by the app-router.
// __N is used to identify if the history entry can be handled by the old router.
Expand Down Expand Up @@ -467,65 +464,64 @@ function Router({
const originalReplaceState = window.history.replaceState.bind(
window.history
)
if (process.env.__NEXT_WINDOW_HISTORY_SUPPORT) {
// Ensure the canonical URL in the Next.js Router is updated when the URL is changed so that `usePathname` and `useSearchParams` hold the pushed values.
const applyUrlFromHistoryPushReplace = (
url: string | URL | null | undefined
) => {
const href = window.location.href
startTransition(() => {
dispatch({
type: ACTION_RESTORE,
url: new URL(url ?? href, href),
tree: window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE,
})
})
}

/**
* Patch pushState to ensure external changes to the history are reflected in the Next.js Router.
* Ensures Next.js internal history state is copied to the new history entry.
* Ensures usePathname and useSearchParams hold the newly provided url.
*/
window.history.pushState = function pushState(
data: any,
_unused: string,
url?: string | URL | null
): void {
// Avoid a loop when Next.js internals trigger pushState/replaceState
if (data?.__NA || data?._N) {
return originalPushState(data, _unused, url)
}
data = copyNextJsInternalHistoryState(data)

if (url) {
applyUrlFromHistoryPushReplace(url)
}
// Ensure the canonical URL in the Next.js Router is updated when the URL is changed so that `usePathname` and `useSearchParams` hold the pushed values.
const applyUrlFromHistoryPushReplace = (
url: string | URL | null | undefined
) => {
const href = window.location.href
startTransition(() => {
dispatch({
type: ACTION_RESTORE,
url: new URL(url ?? href, href),
tree: window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@timneutkens after upgrading from 14.0.4 to 14.1.0 I'm seeing errors from this line when using Microsoft's @azure/msal-browser with NextJS. Specifically the error is:

null is not an object (evaluating 'window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE')

The flow that causes the error is that Microsoft has just redirected a user to my site with a hash in the URL, and the client code on my site (via the @azure/msal-browser package) is trying to remove the hash from the URL. Specifically, this line is being called:

https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/2d4d0b2cde8e072ba6c64aea9b251984b2dd4021/lib/msal-browser/src/utils/BrowserUtils.ts#L21-L25

I have a patch locally that "fixes" this by adding if (window.history.state == null) return; directly above startTransition(() => { ... a couple of lines above here, but I don't understand Next.js's internals well enough to know if that's the right fix. I can submit a PR with it if you think it is.

❤️ for all your work on Next.js.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@timneutkens gentle nudge on ☝️

})
})
}

/**
* Patch pushState to ensure external changes to the history are reflected in the Next.js Router.
* Ensures Next.js internal history state is copied to the new history entry.
* Ensures usePathname and useSearchParams hold the newly provided url.
*/
window.history.pushState = function pushState(
data: any,
_unused: string,
url?: string | URL | null
): void {
// Avoid a loop when Next.js internals trigger pushState/replaceState
if (data?.__NA || data?._N) {
return originalPushState(data, _unused, url)
}
data = copyNextJsInternalHistoryState(data)

/**
* Patch replaceState to ensure external changes to the history are reflected in the Next.js Router.
* Ensures Next.js internal history state is copied to the new history entry.
* Ensures usePathname and useSearchParams hold the newly provided url.
*/
window.history.replaceState = function replaceState(
data: any,
_unused: string,
url?: string | URL | null
): void {
// Avoid a loop when Next.js internals trigger pushState/replaceState
if (data?.__NA || data?._N) {
return originalReplaceState(data, _unused, url)
}
data = copyNextJsInternalHistoryState(data)
if (url) {
applyUrlFromHistoryPushReplace(url)
}

if (url) {
applyUrlFromHistoryPushReplace(url)
}
return originalPushState(data, _unused, url)
}

/**
* Patch replaceState to ensure external changes to the history are reflected in the Next.js Router.
* Ensures Next.js internal history state is copied to the new history entry.
* Ensures usePathname and useSearchParams hold the newly provided url.
*/
window.history.replaceState = function replaceState(
data: any,
_unused: string,
url?: string | URL | null
): void {
// Avoid a loop when Next.js internals trigger pushState/replaceState
if (data?.__NA || data?._N) {
return originalReplaceState(data, _unused, url)
}
data = copyNextJsInternalHistoryState(data)

if (url) {
applyUrlFromHistoryPushReplace(url)
}
return originalReplaceState(data, _unused, url)
}

/**
Expand Down Expand Up @@ -560,10 +556,8 @@ function Router({
// Register popstate event to call onPopstate.
window.addEventListener('popstate', onPopState)
return () => {
if (process.env.__NEXT_WINDOW_HISTORY_SUPPORT) {
window.history.pushState = originalPushState
window.history.replaceState = originalReplaceState
}
window.history.pushState = originalPushState
window.history.replaceState = originalReplaceState
window.removeEventListener('popstate', onPopState)
}
}, [dispatch])
Expand Down
1 change: 0 additions & 1 deletion packages/next/src/server/config-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,6 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
excludeDefaultMomentLocales: z.boolean().optional(),
experimental: z
.strictObject({
windowHistorySupport: z.boolean().optional(),
appDocumentPreloading: z.boolean().optional(),
adjustFontFallbacks: z.boolean().optional(),
adjustFontFallbacksWithSizeAdjust: z.boolean().optional(),
Expand Down
2 changes: 0 additions & 2 deletions packages/next/src/server/config-shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,6 @@ export interface NextJsWebpackConfig {
}

export interface ExperimentalConfig {
windowHistorySupport?: boolean
caseSensitiveRoutes?: boolean
useDeploymentId?: boolean
useDeploymentIdServerActions?: boolean
Expand Down Expand Up @@ -780,7 +779,6 @@ export const defaultConfig: NextConfig = {
output: !!process.env.NEXT_PRIVATE_STANDALONE ? 'standalone' : undefined,
modularizeImports: undefined,
experimental: {
windowHistorySupport: false,
serverMinification: true,
serverSourceMaps: false,
caseSensitiveRoutes: false,
Expand Down
6 changes: 1 addition & 5 deletions test/e2e/app-dir/shallow-routing/next.config.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
windowHistorySupport: true,
},
}
const nextConfig = {}

module.exports = nextConfig