### What?
Add support for auto-importing `headers()` and `cookies()`
### Why?
Improve the auto-import experience in IDEs like VScode
### How?
Re-export the `next/headers` type references
Closes NEXT-2146
### What
Follow up for #59852 , now you can use `next/og` if your nextjs app is
marked as ESM with `"type": "module"` in package.json.
### How
It's a bug in external handling, we shouldn't ESM import error for local
requests. Previously you'll see the below error but the
og import shouldn't be errored as it's not external package
```
Module not found: ESM packages (/.../app/opengraph-image.js) need to be imported. Use 'import' to reference the package instead
https://nextjs.org/docs/messages/import-esm-externals
```
Closes NEXT-2147
### What?
Follow-up to #60579 and #60750. Checking `startsWith` is not enough
because it hides the rest of the stack. Changed the test to check the
snapshot for Turbopack and webpack.
Fixes a bug where the stack lines showed `http (NaN:NaN)` as the source
lines.
Added support for source lines that don't have a open in editor.
<!-- 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-2128
### Fixed a Test Case
- Tests fixed:
`packages/next/src/build/normalize-catchall-routes.test.ts`, the
function call `normalizeCatchAllRoutes(appPaths)` was removed by
accident in this [merged commit
](efebba80a7 (diff-e3c0d3c6e15d8b035a3252a1ada2b04d5dd33010885fed8f6d689f75aa80bff5))
rendering the test case pointless
REF NEXT-1984
This PR stabilizes the previously introduced experimental config options
for providing a custom cache handler (for both ISR as well as the Data
Cache) and for disabling or configuring the in-memory cache size. The
example usage would be as follows:
```js
// next.config.js
module.exports = {
cacheHandler: require.resolve('./cache-handler.js'),
cacheMaxMemorySize: 0 // disable default in-memory caching
}
```
This PR also updates the documentation to better reflect how to use the
custom cache handler when self-hosting. Further information will be
added in a following PR that also includes a full example of a custom
cache handler that implements `revalidateTag` as well as passing in
custom cache tags. The API reference docs have been updated here, as
well as a version history added.
I also noticed that we currently have two duplicated versions of the ISR
docs in the Pages Router docs: both for rendering and for data fetching.
Data Fetching is the correct location for this page. There were no other
references to the rendering version in the docs, so that must have been
an accident. I'll need to a get a redirect going for that regardless.
Tests have been updated for `cacheHandler` and I added a new test for
`cacheMaxMemorySize`.
---------
Co-authored-by: Jiachi Liu <inbox@huozhi.im>
## What?
Skip postcss config resolving in node_modules for Turbopack. This
matches current Next.js on webpack closer as that only resolves the
postcss config from the project root. The additional feature Turbopack
has is that it can find a postcss config relative to the css being
compiled. This is useful for e.g. reducing the amount of overhead
certain postcss plugins that only have to run against a single file take
(i.e. Tailwindcss).
Depends on github.com/vercel/turbo/pull/7012 landing first.
<!-- 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-2109
---------
Co-authored-by: Tobias Koppers <tobias.koppers@googlemail.com>
This reapplies the `experimental.missingSuspenseWithCSRBailout` option
to bail out during build if there was a missing suspense boundary when
using something that bails out to client side rendering (like
`useSearchParams()`). See #57642
Closes [NEXT-1770](https://linear.app/vercel/issue/NEXT-1770)
The following spans are either added or displayed by default:
* `NextNodeServer.findPageComponents` - page components
resolution/require
* `NextNodeServer.getLayoutOrPageModule` - load modules (webpack or
turbopack)
This would allow different apps to setup fetch instrumentation similar
to `@opentelemetry/instrumentation-http` and
`@opentelemetry/instrumentation-fetch` without duplicating fetch spans
and avoiding confusion with context propagation.
This ensures when a dependency has a recursive require our should ignore
handling doesn't accidentally loop back and forth.
x-ref: https://github.com/lovell/sharp/issues/3944
Closes NEXT-2121
As Barrel Optimization might split one file into multiple different
modules, i.e. when you import different values from it, the target file
might be transformed differently, we can no longer rely on the file path
as the identifier of the client reference.
This fix adds a suffix (`'@' + this._module.matchResource`) to the
identifier so it looks like
`/filepath/file.js@__barrel_optimize__?names=Foo`.
Here's also a quick diagram to explain:
![CleanShot-2024-01-16-QzlxzMKy@2x](https://github.com/vercel/next.js/assets/3676859/99f25975-b965-4ae0-91f2-269a6a0d7458)
Closes#59804.
Closes NEXT-2108.
---------
Co-authored-by: Jiachi Liu <inbox@huozhi.im>
- Both the standalone server and the `startServer` function it calls
attempt to stop the server on `SIGINT` and `SIGTERM` in different ways.
This lets `server.js` yield to `startServer`
- The cleanup function in `startServer` was not waiting for the server
to close before calling `process.exit`. This lets it wait for any
in-flight requests to finish processing before exiting the process
- Sends `SIGKILL` to the child process in `next dev`, which should have
the same effect of immediately shutting down the server on `SIGTERM` or
`SIGINT`
fixes: #53661
refs: #59551
------
Previously #59551 attempted to fix#53661, but had broken some tests in
the process. It looks like the final commit was also missing an intended
change to `utils.ts`. This should fix those issues as well as introduce
a new set of tests for the graceful shutdown feature.
In the last PR I was squashing and force-pushing updates along the way
but it made it difficult to track the changes. This time I'm pushing
quite a few commits to make it easier to track the changes and refactors
I've made, with the idea that this should be squashed before being
merged.
<!-- 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 #
-->
### What
Sometimes the display of the error overlay is not consistent even when
you fixed the error
Example:
* You have a client page, and you add metadata export, Next.js will
error that it's not allowed in client component.
* You fix it, but the error overlay is not disappeared. Or you fix it,
then introduce it again, then fix it again, the error overlay is still
there.
### How
We're checking if the HMR webpack hash is changed to decide if we're
going to do a hot update in `BUILT` and `SYNC` event, but we update the
hash at the very beginning of the event handler. `isUpdateAvailable()`
will return `false` in the later calls but the hash has already changed
before. So we check if they change before applying hot updates, and then
use it later with `isUpdateAvailable()` to determine if necessary to
process a new hot update
Closes NEXT-2107
---------
Co-authored-by: Tim Neutkens <tim@timneutkens.nl>
### What?
removes to old next build turbopack version. It will be implemented in a
different way.
### Why?
We want to use next.rs api for that.
Closes PACK-2239
When you're using `noStore()` with `fetch` it's currently saying "auto
cache" in cache missed reason, adding "noStore call" here to show it's
caused by using with `unstable_noStore`
```
GET /no-store 200 in 4069ms
│ GET https://next-data-api-endpoint.vercel.app/api/random?another-no-cache 200 in 257ms (cache: SKIP)
│ │ Cache missed reason: (noStore call)
```
Closes NEXT-2097
### What
We're applying react-refresh to browser layer and inject ESM or CJS
helper based on file type. Some package from `trasnpilePackages` might
contain CJS browser bundle. And injecting ESM helper breaks them.
Actually they don't need to have fast refresh ability since they're in
`node_modules`.
### How
Skip react-refresh for transpiled packages as they're in node_modules
and won't change.
Fixes#56487
Closes NEXT-2061
### Depends on
- #60577
---
A popstate navigation reads data from the local cache. It does not issue
new network requests (unless the cache entries have been evicted). So,
when navigating with back/forward, we should not switch back to the PPR
loading state. We should render the full, cached dynamic data
immediately.
To implement this, on a popstate navigation, we update the cache to drop
the prefetch data for any segment whose dynamic data was already
received. We clone the entire cache node tree and set the `prefetchRsc`
field to `null` to prevent it from being rendered. (We can't mutate the
node in place because Cache Node is a concurrent data structure.)
Technically, what we're actually checking is whether the dynamic network
response was received. But since it's a streaming response, this does
not mean that all the dynamic data has fully streamed in. It just means
that _some_ of the dynamic data was received. But as a heuristic, we
assume that the rest dynamic data will stream in quickly, so it's still
better to skip the prefetch state.
Closes NEXT-2084
This allows us to more accurately attribute whether a trace was created
in a Turbopack session by doing so at trace creation time rather than
trace upload time.
Test Plan: Configured next to send traces to a local server and verified
this information is attached to the top-level of the trace.
Closes PACK-2233
### What?
Throwing a `notFound()` error inside of a segment that has an error
boundary will cause it to be handled by the segment's error boundary
rather than a parent not-found boundary.
### Why?
We assume anything that hits an `ErrorBoundary` is an actual error, but
this should not be the case when the caught error is one that is handled
by Next.js.
### How?
This checks if the caught error is one that is expected to be handled
someplace else.
Closes NEXT-2080
[slack
x-ref](https://vercel.slack.com/archives/C03S8ED1DKM/p1705003189392509?thread_ts=1704868742.169129&cid=C03S8ED1DKM)
This updates our default error rate to be much more precise and reduce
false positives by increasing the default size of the client filter we
generate. We can afford to increase the default size as it compresses
extremely well and gives us more accurate navigations. This carries over
the failing test case from https://github.com/vercel/next.js/pull/59293
which showed one case of false positive in a smaller filter.
Closes: https://github.com/vercel/next.js/issues/47486
Closes NEXT-2070
---------
Co-authored-by: Cris Vergara <cris.vergara@bookofthemonth.com>
## What
This fixes when the deep nested routes throws a client side error, it
can still be caught by the `global-error.js`
## How
We should always resolve global-error from root app directory instead of
current route's layout. Also fixed a bad test before where the
gloabl-error.js is not located correctly
Fixes#53756
Closes NEXT-1760
When sending post requests but it's not server action, skip logging
warning or calling non-existed server action. Instead we only log the
warning like missnig headers for server actions when it's a server
action and call the action handler when it's decoded as a function
Fixes#58152
Closes NEXT-1761
### Why?
We have more supported options than unsupported ones.
Also new options added to next.js now should always be supported by
turbopack.
Closes PACK-2023
This forwards spans created in the hmr client to the server-side tracer.
Test Plan: Loaded a page and verified navigation-to-hydration span is
recorded.
Closes PACK-2226
### What?
This fixes a race condition where loadClientReferenceManifest reads an
empty file. All other manifest already have retries, this adds it for
the client reference manifest too for consistency.
Closes WEB-1727
---------
Co-authored-by: Tim Neutkens <tim@timneutkens.nl>
### What?
Fixes#58570
### How?
Include the **basePath** to the **fetchUrl** to ensure the relative URL
matches the app when deployed under a **basePath**.
### Tested?
I have added an **e2e** test with a basic custom server & server action
redirect.
This test was confirmed to **catch** the bug when running it without the
fix in place. When running it you will get the failed result.
```
FAIL test/e2e/app-dir/app-basepath-custom-server/index.test.ts (12.293 s)
custom-app-render
✕ redirects properly when server action handler uses `redirect` (1661 ms)
● custom-app-render › redirects properly when server action handler uses `redirect`
expect(received).not.toEqual(expected) // deep equality
Expected: not ["/base/another", 200]
45 | // if broken, this will include a 200 from the /base/another indicating a full page redirect
46 | responses.forEach((res) => {
> 47 | expect(res).not.toEqual(['/base/another', 200])
| ^
48 | })
49 | })
50 | }
at toEqual (e2e/app-dir/app-basepath-custom-server/index.test.ts:47:25)
at Array.forEach (<anonymous>)
at Object.forEach (e2e/app-dir/app-basepath-custom-server/index.test.ts:46:17)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 12.321 s, estimated 22 s
Ran all test suites matching /test\/e2e\/app-dir\/app-basepath-custom-server/i.
ELIFECYCLE Command failed with exit code 1.
ELIFECYCLE Command failed with exit code 1.
ELIFECYCLE Command failed with exit code 1.
```
### Notes
Not sure if there are any edge cases where the `fetchUrl` is now broken
in other use cases where there is no **basePath**, I assume the string
would be empty `""` and result in the same URL as before, but not sure?
### Disclosure
~I am not that familiar with the Next.js code base and this is my first
PR. I was struggling to find out how to grab the **basePath** from
`next.config.js`, but then noticed the **assetPrefix** inside the
function matched, so decided to use that for minimal change. I don't
know if there are any caveats with this approach, but could consider
switching to pull directly from the config file, if that's possible?~
**Update:** Figured out where the **basePath** came from and switched
it.
---------
Co-authored-by: Colton Ehrman <cehrman@paypal.com>
Co-authored-by: Tim Neutkens <tim@timneutkens.nl>
This PR introduces 2 experimental options for doing more work in the
webpack build in parallel instead of in serial. These options may
improve the performance of builds at the cost of more memory.
`parallelServerAndEdgeCompiles`: This option kicks off the builds for
both `server` and `edge-server` at the same time instead of waiting for
each to complete before the next one. In applications that have many
server and edge functions, this can increase performance by doing that
work in parallel. This can be used with `next build` or `next
experimental-compile`.
`parallelServerBuildTraces`: This option starts the server build traces
as soon as the server compile completes and runs it in the background
while the other compilations are happening. With this option enabled,
some unnecessary work may be done since ordinarily the client
compilation provides information that can reduce the amount of tracing
necessary. However, since it is in parallel with the other work, it may
still result in a faster build in total at the cost of more memory. This
option is already the default when using `next experimental-compile` but
can now be used when `next build` is used also.
---------
Co-authored-by: Delba de Oliveira <32464864+delbaoliveira@users.noreply.github.com>
Co-authored-by: JJ Kasper <jj@jjsweb.site>
### What
`/default` segments were considered valid page outputs to handle
catch-all route normalization (see #60240) but they shouldn't leak into
the prerender manifest. This filters them out at build time.
Closes NEXT-2053
In the output shared js chunks section we're showing all shared chunks
atm, some of them might be too small (few bytes) due to code split. e.g.
in the below example, main-app is only `218B`, we're going to group all
the chunks below 10KB together into one item line
#### Before
```
+ First Load JS shared by all 81.9 kB
├ chunks/381-ffe155bc1c63f064.js 26.7 kB
├ chunks/8766613a-1f3d501627fe8359.js 53.3 kB
├ chunks/main-app-80d2c0fe59f30ae2.js 218 B
└ chunks/webpack-e6edcd8ebd35b832.js 1.68 kB
```
#### After
```
+ First Load JS shared by all 83.7 kB
├ chunks/4921c021-73266f862a05e4e2.js 53.3 kB
├ chunks/596-73310d23ef824244.js 28.6 kB
└ other shared chunks (total) 1.83 kB
```
Closes NEXT-2046
Closes NEXT-1970
### What?
When using catch-all routes in conjunction with parallel routes, and
when importing a client component (`"use client"`), the build would fail
with the following error:
> Could not find the module "PathToClientComponent" in the React Client
Manifest. This is probably a bug in the React Server Components bundler.
### Why?
`flight-manifest-plugin` generates manifests for each page entry. The
`clientModules` portion of this manifest is used by React to load the
appropriate client module. When React attempts to render a component
tree and detects a module that it cannot find, it will throw this error.
To illustrate why it isn't in the tree, consider the following example:
```
app
page.tsx
layout.tsx
@slot
[...catchAll]
page.tsx
```
```tsx
// app/layout.tsx
export default function Layout({children, slot}) {
return <>{children} {slot}</>
}
```
```tsx
// app/@slot/[...catchAll]/page.tsx
import Link from 'next/link'
export default function Page() {
return <Link href="/">Test</Link>
}
```
When visiting `/`, we'd expect both the catch-all `@slot` and the root
page to render. At build time, we'll generate a client reference
manifest for `/` and `/[...catchAll]` since both are page components.
However, the `@slot` imports a client component. When we attempt to load
the client reference manifest for `/`, it will ignore the catch-all
slot's manifest, resulting in the error.
### How?
The `entryNameToGroupName` function seems to already exist to handle
this scenario for other cases. For example,
`app/(group)/@named/foo/page` needs to know about any manifests
associated with `app/foo`. This updates the code to apply similar
handling to catchAll segments. When applying this change to the example
mentioned earlier, it will properly merge the manifests for both
`app/@slot/[...catchAll]/page.tsx` and `app/page.tsx` because both will
be part of the `/` group.
Closes NEXT-1908
Fixes#59747Fixes#59510
### Fixing a bug
### What?
When basePath is added, intercepted routes stop working correctly.
### Why?
For them, basePath was not added at all.
### How?
Added basePath to the rewrites for intercepted routes.
Fixes#52624, #58268
### What?
This PR adds a new flag called
`experimental.missingSuspenseWithCSRBailout`.
### Why?
Via this PR we can break a build when calling `useSearchParams` without
wrapping it in a suspense boundary.
If no suspense boundaries are present, Next.js must avoid doing SSR and
defer the entire page's rendering to the client. This is not a great
default. Instead, we will now break the build so that you are forced to
add a boundary.
### How?
Add an experimental flag. If a `BailoutToCSRError` error is thrown and
this flag is enabled, the build should fail and log an error, instead of
showing a warning and bail the entire page to client-side rendering.
Closes NEXT-1770
---------
Co-authored-by: Balázs Orbán <info@balazsorban.com>
Co-authored-by: Wyatt Johnson <accounts+github@wyattjoh.ca>
### Fixing a bug
### What?
Custom cache handler doesn't work on Windows
### Why?
It broke in a recent fix, when adding ESM support - #59863. The problem
is not new - dynamic imports consider an absolute path in Windows as a
protocol:
`ERR! Error [ERR_UNSUPPORTED_ESM_URL_SCHEME]: Only URLs with a scheme
in: file, data are supported by the default ESM loader. On Windows,
absolute paths must be valid file:// URLs. Received protocol 'C:'`
### How?
As a solution, it is necessary to explicitly indicate that it is indeed
an absolute path, for example by adding a / at the beginning, but the
most reliable way is to use pathToFileURL.
Since the logic is repeated in 4 places - I created a common function.
Fixes#58509
---------
Co-authored-by: JJ Kasper <jj@jjsweb.site>
### What?
Previously, if an error such as the client side rendering bailout (not
to be confused with the static rendering bailout which PPR supercedes)
occurs during render, and the `postpone` function was invoked during the
original render, then the `staticGenerationStore` would incorrectly
report that the render did call `postpone`, because the value is not
reset on the render for the error page.
### How?
Returning no error when the standard render is used and returning the
error when the error render was used ensures that we don't warn about
missing postpone data when a client side rendering bailout occurs.
### Looking Ahead
A refactor of the `AsyncLocalStorage` should be done such that the
stores are:
1. Returned by the calling function so we aren't reaching into store
properties at different parts
2. Reorganizing the stores so that they're tied to the invocation
lifetime, not the entire request lifetime, so that operations (like
postpone) should only be available during renders that support postpone,
not all renders during a request.
Closes NEXT-1927
The original motivation of this PR is to get `unstable_cache` into a
state where I can more easily change the implementation of postpone to
be more akin to "dynamic rendering APIs". the existing approach made
typing the staticGenerationStore in a way I wanted to for the planned
changes would have been hard to implement with the current approach. At
the same time this was an opportunity to make the implementation more
efficient and easier to reason about.
reorganizes unstable_cache to improve performance and potentially fix
latent bugs related to nest cache calls
In the original implementation there are repeated defined checks for the
store and relatively complex logic around gathering the cache entry. In
my refactor I fork the implementation based on whether we have a store
or not. Loosely this translates to whether the cache call is for App
Router vs Pages Router however due to a quirk in how we scope inner
cache calls there is an existing and unchanged case where a Pages Router
cached callback runs with a "fake" store that is used to scope some
cache values to prevent inner caching when one cached function calls
another. It should be noted that this fake store technique means that
inner cache calls inside Pages Router will hit the App Router pathway in
unstable cache. This is not great but it is the current behavior and
while I have made some changes that might fix some bugs changing this
felt like a much bigger lift to do in a primarily refactor PR.
This "fake" store can be replaced by a different async store for Pages
Router which we can use to scope the inner environment to not be cached
eventually though it may make more sense to just generalize the
staticGenerationStore into a kind of RenderStore and have it run for
Pages Router too.
I moved as much computation that can be done in the closure around the
cached function out of the cached function and I narrowed the scope of
the run call to make it clear that we really only need to scope the
callback.
I removed function allocations per invocation
I probably fixed a bug in how the revalidate property was refined on the
static generation store. Previously it would be possible to go from
number to false and back again but this doesn't make sense as false is
more like INFINITY in terms of refining to shorter values. This PR
updates this logic to be apparently
Closes NEXT-2028
### What?
When accessing `params` on a `RootLayout`, while also using parallel
routes, two potential errors would occur:
- A `Warning: React.createElement: type is invalid` error when
attempting to render a `NotFound` component that doesn't exist
- A `TypeError: Cannot read properties of undefined` error when
attempting to access params in the root layout.
### Why?
`createComponentTree` will render a duplicate `RootLayout` (to ensure
the `notFound()` fallback in unmatched parallel slots have a
`NotFoundBoundary` to catch them) but it currently doesn't ensure a
`NotFound` component exists nor does it forward `params` to the layout.
### How?
This forwards the params to the `RootLayout` and doesn't render a
`NotFoundComponent` if one doesn't exist. This replaces a few `any`
types with more sound types that would have helped catch these mistakes.
There's still a lot more typing that needs to be done (left a comment
below with some additional details) but I opted to make the minimal
changes related to this issue.
Longer term we should remove this duplicate `RootLayout` (see #60220)
which will require special UI to show unmatched slots (similar to the
error overlay, but less harsh)
Closes NEXT-1909
Fixes#59711
When you have a gaint code base of next.js app, the output client side
loaded js bundle size could be large since most of them are functional,
it might not make sense to display yellow or red color to warn you that
your bundle is too large since they conatin the basic functionality.
We display the previous colored ones with opinionless bold white color
to highlight them
![image](https://github.com/vercel/next.js/assets/4800338/34814f2f-ff83-48b4-bad8-989031eff49e)
Closes NEXT-2017
Closes NEXT-2015
This includes the list of changed modules in the `client-hmr-latency`
event for changes in app router pages as well as when using Turbopack.
For Turbopack, this list is derived from the data structure included in
the `turbopack-message` event. Each of these is originally a module id,
which includes additional context information. For analytics purposes
this is removed (and could maybe surfaced in the future once the webpack
data is also normalized).
Closes PACK-2167
### What?
When running a
[multi-zone](https://github.com/vercel/next.js/tree/canary/examples/with-zones)
app in dev, guest app pages would infinitely reload if you change the
basePath of the host app to the default one (omit basePath settings in
next.config.js) (empty string `""` as per Next.js docs).
### Why?
The HMR upgrade request would fail and get caught into a retry loop. In
the multi-zone case, they fail because the upgrade request would be sent
again for a request that had already been upgraded. This resulted in a
"server.handleUpgrade() was called more than once with the same socket"
error, causing the upgrade request to fail.
Every time a retry occurred, the page would trigger a full refresh since
certain HMR errors cause the browser to reload.
### How?
This ensures the upgrade handler only responds to requests that match
the configured basePath (considering when there is no basePath). Default
basePath for Next.js applications it's an empty string `""`.
Ref: https://nextjs.org/docs/app/api-reference/next-config-js/basePath
Other fixes & updates related to the bug:
- Updated test apps to avoid having issues regarding client & server
mismatch for dates
- Added default use case in e2e tests, where you have a default Next.js
application where the basePath it's the default one and a guest app that
it's being routed by the main one through Next.js rewrites.
Closes NEXT-1797
Fixes#59161Fixes#56615Fixes#54454
---------
Co-authored-by: Zack Tanner <zacktanner@gmail.com>
Per @styfle suggestion, #58038 has been split into multiple PRs for
easier review.
- Remove `chalk` inside `@next/react-dev-overlay`
- `@next/react-dev-overlay` is bundled with Next.js. The usage of
`chalk` inside `@next/react-dev-overlay` was not removed in
https://github.com/vercel/next.js/pull/55992, thus the `chalk` is still
being shipped.
---------
Co-authored-by: JJ Kasper <jj@jjsweb.site>
Per @styfle suggestion, #58038 has been split into multiple PRs for
easier review.
- Re-add precompile `watchpack`
- Next.js has stopped bundling the `watchpack` since
https://github.com/vercel/next.js/pull/50792. Currently, `watchpack` is
a direct dependency of Next.js. The PR adds the pre-compile back.
Co-authored-by: Steven <steven@ceriously.com>
Per @styfle suggestion, #58038 has been split into multiple PRs for
easier review.
- Remove `find-cache-dir`
- The usage of `find-cache-dir` was removed **4 years ago**
(https://github.com/vercel/next.js/pull/7013) but the dist and the build
script were never removed.
- Remove `@segment/ajv-human-errors`
- The usage of `@segment/ajv-human-errors` was removed in
https://github.com/vercel/next.js/pull/56383 by me. Though the build
script was also removed in that PR, the dist never got removed.
### What
Fix bad detection of dynamic route of sitemap metadata route, the swc
AST check should process when the text are detected. But prevuious if
there's text with `generateSitemap` such as comment but not the actual
export it will fail.
### How
Add both checks on metadata loader side and detection helper side
* Only call `generateSitemaps` helper when the export existed
* Fix the helper detection logic (major part of this PR)
Fixes#59698Closes#60344
Closes NEXT-2007
### What?
Our
[docs](https://nextjs.org/docs/app/building-your-application/routing/parallel-routes#convention)
point out that `app/page.js` is equivalent to `app/@children/page.js`,
however in practice this is not the case, and causes type errors when
using `@children` slots as well as incorrect behavior when matching
catch-all routes.
### Why?
- When typechecking, `@children` slots would be added to the typeguard
file for the associated layout, resulting in duplicate identifiers for
the `children` prop
- When determining where to insert catchall slots, the `hasMatchedSlots`
check wasn't considering that the `@children` slot corresponds with the
page component, so matching another page would clobber the previous one.
### How?
- Filters out the `@children` slot when collecting slots for
typechecking
- Filters out the `@children` slot when running the `hasMatchedSlots`
function in the catch-all normalizer
Closes NEXT-1984