Unverified Commit 10e8f4d4 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Enable windowHistorySupport by default (#60557)

## 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
parent cc2bd0de
...@@ -188,7 +188,7 @@ For a full list of `useRouter` methods, see the [API reference](/docs/app/api-re ...@@ -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. 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` ### `window.history.pushState`
......
---
title: windowHistorySupport
description: Learn how to use the windowHistorySupport option to sync the native History API with the Next.js Router.
---
`windowHistorySupport` is an experimental flag that allows you manually call [`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).
When the flag is enabled, `pushState` and `replaceState` calls are integrated 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).
To use it, set `windowHistorySupport` to `true` in your `next.config.js` file:
```js fileName="next.config.js"
module.exports = {
experimental: {
windowHistorySupport: true,
},
}
```
See the [Linking and Navigation](/docs/app/building-your-application/routing/linking-and-navigating#using-the-native-history-api) documentation for examples.
...@@ -95,9 +95,6 @@ export function getDefineEnv({ ...@@ -95,9 +95,6 @@ export function getDefineEnv({
isEdgeServer ? 'edge' : isNodeServer ? 'nodejs' : '' isEdgeServer ? 'edge' : isNodeServer ? 'nodejs' : ''
), ),
'process.env.NEXT_MINIMAL': JSON.stringify(''), '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_PPR': JSON.stringify(config.experimental.ppr === true),
'process.env.__NEXT_ACTIONS_DEPLOYMENT_ID': JSON.stringify( 'process.env.__NEXT_ACTIONS_DEPLOYMENT_ID': JSON.stringify(
config.experimental.useDeploymentIdServerActions config.experimental.useDeploymentIdServerActions
......
...@@ -122,10 +122,7 @@ function HistoryUpdater({ ...@@ -122,10 +122,7 @@ function HistoryUpdater({
useInsertionEffect(() => { useInsertionEffect(() => {
const { tree, pushRef, canonicalUrl } = appRouterState const { tree, pushRef, canonicalUrl } = appRouterState
const historyState = { const historyState = {
...(process.env.__NEXT_WINDOW_HISTORY_SUPPORT && ...(pushRef.preserveCustomHistoryState ? window.history.state : {}),
pushRef.preserveCustomHistoryState
? window.history.state
: {}),
// Identifier is shortened intentionally. // Identifier is shortened intentionally.
// __NA is used to identify if the history entry can be handled by the app-router. // __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. // __N is used to identify if the history entry can be handled by the old router.
...@@ -467,65 +464,64 @@ function Router({ ...@@ -467,65 +464,64 @@ function Router({
const originalReplaceState = window.history.replaceState.bind( const originalReplaceState = window.history.replaceState.bind(
window.history 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) { // 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.
applyUrlFromHistoryPushReplace(url) 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) return originalPushState(data, _unused, url)
} }
data = copyNextJsInternalHistoryState(data)
/** if (url) {
* Patch replaceState to ensure external changes to the history are reflected in the Next.js Router. applyUrlFromHistoryPushReplace(url)
* 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) { return originalPushState(data, _unused, url)
applyUrlFromHistoryPushReplace(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) return originalReplaceState(data, _unused, url)
} }
data = copyNextJsInternalHistoryState(data)
if (url) {
applyUrlFromHistoryPushReplace(url)
}
return originalReplaceState(data, _unused, url)
} }
/** /**
...@@ -560,10 +556,8 @@ function Router({ ...@@ -560,10 +556,8 @@ function Router({
// Register popstate event to call onPopstate. // Register popstate event to call onPopstate.
window.addEventListener('popstate', onPopState) window.addEventListener('popstate', onPopState)
return () => { return () => {
if (process.env.__NEXT_WINDOW_HISTORY_SUPPORT) { window.history.pushState = originalPushState
window.history.pushState = originalPushState window.history.replaceState = originalReplaceState
window.history.replaceState = originalReplaceState
}
window.removeEventListener('popstate', onPopState) window.removeEventListener('popstate', onPopState)
} }
}, [dispatch]) }, [dispatch])
......
...@@ -226,7 +226,6 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -226,7 +226,6 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
excludeDefaultMomentLocales: z.boolean().optional(), excludeDefaultMomentLocales: z.boolean().optional(),
experimental: z experimental: z
.strictObject({ .strictObject({
windowHistorySupport: z.boolean().optional(),
appDocumentPreloading: z.boolean().optional(), appDocumentPreloading: z.boolean().optional(),
adjustFontFallbacks: z.boolean().optional(), adjustFontFallbacks: z.boolean().optional(),
adjustFontFallbacksWithSizeAdjust: z.boolean().optional(), adjustFontFallbacksWithSizeAdjust: z.boolean().optional(),
......
...@@ -159,7 +159,6 @@ export interface NextJsWebpackConfig { ...@@ -159,7 +159,6 @@ export interface NextJsWebpackConfig {
} }
export interface ExperimentalConfig { export interface ExperimentalConfig {
windowHistorySupport?: boolean
caseSensitiveRoutes?: boolean caseSensitiveRoutes?: boolean
useDeploymentId?: boolean useDeploymentId?: boolean
useDeploymentIdServerActions?: boolean useDeploymentIdServerActions?: boolean
...@@ -780,7 +779,6 @@ export const defaultConfig: NextConfig = { ...@@ -780,7 +779,6 @@ export const defaultConfig: NextConfig = {
output: !!process.env.NEXT_PRIVATE_STANDALONE ? 'standalone' : undefined, output: !!process.env.NEXT_PRIVATE_STANDALONE ? 'standalone' : undefined,
modularizeImports: undefined, modularizeImports: undefined,
experimental: { experimental: {
windowHistorySupport: false,
serverMinification: true, serverMinification: true,
serverSourceMaps: false, serverSourceMaps: false,
caseSensitiveRoutes: false, caseSensitiveRoutes: false,
......
/** /**
* @type {import('next').NextConfig} * @type {import('next').NextConfig}
*/ */
const nextConfig = { const nextConfig = {}
experimental: {
windowHistorySupport: true,
},
}
module.exports = nextConfig module.exports = nextConfig
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