Skip to content

Commit

Permalink
Enable windowHistorySupport by default (#60557)
Browse files Browse the repository at this point in the history
## What?

Enables `experimental.windowHistorySupport` by default. It has been in
experimental for quite a while now and has been successfully dogfooded
in vercel.com as well.

<!-- 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 #

-->


Closes NEXT-2076
Closes NEXT-1773
  • Loading branch information
timneutkens authored Jan 12, 2024
1 parent cc2bd0d commit 10e8f4d
Show file tree
Hide file tree
Showing 7 changed files with 55 additions and 91 deletions.
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,
})
})
}

/**
* 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

0 comments on commit 10e8f4d

Please sign in to comment.