In `v14.0.2-canary.1` users started noticing more memory errors
especially with many edge runtime configured pages. After investigation
it seems this can be related to the additional transpiling we configured
in https://github.com/vercel/next.js/pull/59569 and
https://github.com/vercel/next.js/pull/57784
To help alleviate this we are updating the default swc loader to have an
additional check to see if no special features such as `next/font`,
`next/dynamic`, or `use server/client` directives are present and then
no-oping in the loader to avoid additional overhead for a majority of
modules.
For monitoring regressions our `stats-app` has been updated with
repeated edge-ssr routes to hopefully help us keep an eye on memory or
cache size issues.
x-ref: NEXT-2430
x-ref: NEXT-2395
x-ref: NEXT-2299
x-ref: NEXT-2324
x-ref: NEXT-2373
Closes NEXT-2479
### What
When navigating back to a page that you had already loaded, it currently
results in a prefetch cache miss and will re-trigger any data
fetching/loading despite it being available.
### Why
When creating the initial router state, the prefetch cache is
initialized to an empty map.
### How
This uses the `initialTree` passed from the server to seed the cache for
that route with flight data.
Closes NEXT-2001
### What
Prefetches to pages within a shared layout would frequently cache miss
despite having the data available. This causes the "instant navigation"
behavior (with the 30s/5min TTL) to not be effective on these pages.
### Why
In #59861, `nextUrl` was added as a prefetch cache key prefix to ensure
multiple interception routes that correspond to the same URL wouldn't
clash in the prefetch cache. However this causes a problem in the case
where you're navigating between sub-pages. To illustrate the issue,
consider the case where you load `/foo`. This will populate the prefetch
cache with an entry of `{foo: <PrefetchCacheNode}`. Navigating to
`/foo/bar`, with a link that prefetches back to `/foo`, will now result
in a new cache node: `{foo: <PrefetchCacheNode>, /foo/bar%/foo:
<PrefetchCacheNode>}` (where `Next-URL` is `/foo/bar`). Now we have a
cache entry for the full data, as well as a cache entry for a partial
prefetch up to the nearest loading boundary. Now when we navigate back
to `/foo`, the router will see that it's missing data, and need to
lazy-fetch the data triggering the loading boundary.
This was especially noticeable in the case where you have a route group
with it's own loading.js file because it creates a level of hierarchy in
the React tree, and suspending on the data fetch would result in the
group's loading boundary to be triggered. In the non-route group
scenario, there's still a bug here but it would stall on the data fetch
rather than triggering a boundary.
### How
In #61794 we conditionally send `Next-URL` as part of the `Vary` header
if we detect it could be intercepted. We use this information when
creating the prefetch entry to prefix it, in case it corresponds with an
intercepted route.
Closes NEXT-2193
### What
When navigating to a page that uses a loading boundary + parallel route,
an empty white screen would be displayed rather than the loading state /
final state
### Why
With parallel routes, the RSC data is an array of data paths, each
corresponding with one of the parallel segments rendered on the page.
During the navigation event, when we iterate over this data, we call
`applyFlightData` with this data path & an empty cache node.
`applyFlightData` checks to see if the flight data contains cache nodes
("seed data"). If it doesn't, then that means it has no work to do, and
it bails out. Pre-PPR and in the case of having a `loading.js` file,
`walkTreeWithFlightRouterState` doesn't return any seed data, just
router state. This means that `applyFlightData` will not have any work
to do on the new cache node, and leaves it untouched.
Once `applyFlightData` is finished, but while still in the flight data
path loop, we reassign `currentCache` to the empty cache object we
created prior to `applyFlightData`. But since that cache node has
remained empty, the next iteration of the loop is going to be inspecting
a now empty cache, rather than the actual "current" cache. Now there's
no existing cache to copy into the new cache. The app now doesn't know
about any cache nodes.
### How
It doesn't seem like we should be re-assigning `currentCache` to the new
cache. In the context of a navigation, it seems more accurate to always
assume `currentCache` is the cache _now_, since it won't actually be
applied to the state until the action has finished (`mutable.cache` is
currently taking care of this).
Closes NEXT-2223
Fixes#61080
followup to: https://github.com/vercel/next.js/pull/60645
### Background
When prerendering the determination of whether a prerender is fully
static or partially static should not be directly related to whether
there is a postponed state or not. When rendering RSC it is possible to
postpone because a dynamic API was used but then on the client (SSR) the
postpone is never encountered. This can happen when a server component
is passed to a client component and the client component conditionally
renders the server component.
Today if this happens the entire output would be considered static when
in fact the flight data encoded into the page and used for bootstrapping
the client router contains dynamic holes. Today this is blocked by an
error that incorrectly assumes that this case means the user caught the
postpone in the client layer but as shown above this may not be the
case.
### Implementation
A more capable model is to think of the outcome of a prerender as having
3 possible states
1. Dynamic HTML: The HTML produces by the prerender has dynamic holes.
we save the static prelude but expect to resume the render later to
complete the HTML. This means we will resume the RSC part of the render
as well
2. Dynamic Data: The HTML is completely static but the RSC data encoded
into the page is dynamic. We don't want to resume the render but we do
need to produce new inlined RSC data during a Request.
3. Static: The HTML is completely static and so is the RSC data encoded
into the page. We save the entire HTML output and there will be no
dynamic continuation when this route is visited.
Really 1 & 3 are the same as today (Partially static & Fully Static
respectively) but case 2 which today errors in a confusing way is now
supported.
In addition implementing the Dynamic Data case the old warning about
catching postpones is removed. The reason we don't want this is that
catching postpones is potentially a valid way to do optimistic UI. We
probably want a first-party API for it at some point (and maybe we'll
add the warning back in once we do) but imagine you do something dynamic
like look up a user but during prerender you want to render as if the
user is logged out. you could call `getUser()` in a try catch and render
fallback UI if it throws. In this case we'd detect a dynamic API was
used but we wouldn't have a corresponding postpone state which would put
us in the Dynamic Data case (2).
Another item to note is that we can produce a fully static result even
if there is a postponed state because users may call postpone themselves
even if they are not calling dynamic APIs like headers or cookies. When
this happens we don't want to statically capture a page with postponed
boundaries in it. Instead we immediately resume the render and abort it
with a postponed abort signal. This will cause the boundaries to
immediately enter client render mode which should speed up recovery on
the client.
#### Technical Note
Another note about the implementation is that you'll see that regardless
of which case we are in, if there is a postponed state but we consider
the page to be Dynamic Data meaning we want to serialize all the HTML
and NOT do a resume in the dynamic continuation then we immediately
resume the render with and already aborted AbortSignal. The purpose here
is to mark any boundaries which have dynamic holes as being
client-rendered.
As a general rule if the render produces a postponed state we must do
one of the following
1. save the postponed state and ensure there is a dynamic continuation
that calls resume
2. immediately resume the render and save the concatenated output and
ensure the dynamic continuation does NOT call resume.
or said another way, every postponed state must be resumed (even if it
didn't come from Next's dynamic APIs)
#### Perf considerations
This PR modifies a few key areas to improve perf.
Reduces quantity of *Stream instances where possible as these add
significant overhead
Reduces extra closures to lower allocations and keep functions in
monomorphic form where possible
Closes NEXT-2164
Previously, this error was confusing because it made it sound like the
`sizes` prop was missing. This was because the default value of `sizes`
is `100vw` so the previous code couldn't tell the different between
implicit vs explicit `100vw`.
This PR changes the code to read the input value from the `sizes` prop
and prints a better warning.
Fixes NEXT-2441
There was a bug where if the root hydrates and then an update happens
the intitial server data response can be replaced by one that is
completely empty and will never resolve. This can lead to a frozen
hydration that blocks interactivity. This udpate makes it so it is
impossible for the initial data response to ever be created more than
once.
Making a regression test is tricky because this relies on subtle timing
of hydration, updates, and when the inline chunks arrive in the stream.
The original implementation is just not safe in that it violates the
rules of react and the new one is self-evidently unable to produce a
similar situation so as long as our existing test suite passes that must
be sufficient absent a good alternative to making a specific regression
test
Closes NEXT-2420
In #61794, the routes manifest is used to find the interception route rewrites in `next-server` and computed on the fly in `next-dev-server` based on `appPaths`.
The edge runtime doesn't have access to the routes manifest nor a full list of app paths. This writes an entry for the edge runtime to make the interception routes readable, and adds plumbing to return them in the `getInterceptionRouteRewrites` handling in `web-server`. This is what we use to signal to the server whether to return ‘Next-URL’ in the Vary for RSC requests.
This piggybacks on the existing interception routes test but adds an edge runtime case.
Closes NEXT-2304
To ensure that we properly cache data for routes that change based on `Next-URL` (which is used for route interception), this adjusts how we set the `Vary` header to conditionally include `Next-URL`.
The `Next-URL` request header only impacts the response for routes that are intercepted. When we detect that path we're handling could be intercepted, we add `Next-URL` to the vary. This signals in #61235 to prefix these cache entries with `nextUrl` if the response might vary based on it.
Closes NEXT-2398
### Fixing a bug
### What?
Fix remotePatterns when all paths and/or domains are allowed.
### Why?
micromatch creates a very strange regex for all paths -
`/^(?:(?!\.)(?:(?:(?!(?:^|[\\/])\.).)*?)[\\/]?)$/`. That is, paths
cannot start with a dot or contain a slash followed by a dot.
Interestingly, here are some valid paths:
- /a/a.a/6a00d8341c4fbe53ef02c8d3a82122200d-600wi
- ////a/a.a/6a00d8341c4fbe53ef02c8d3a82122200d-600wi
- ///:?%;№%/a/a.a/6a00d8341c4fbe53ef02c8d3a82122200d-600wi.\/
- /:./6a00d8341c4fbe53ef02c8d3a82122200d-600wi.\/
And here are some invalid ones:
- /.a/6a00d8341c4fbe53ef02c8d3a82122200d-600wi
- /a/.a/6a00d8341c4fbe53ef02c8d3a82122200d-600wi
- ./a/6a00d8341c4fbe53ef02c8d3a82122200d-600wi
I don't think this check makes any sense.
### How?
If the user allows all (`**`) - it means any path or domain will be
considered valid.
- Fixes#60483
- Fixes#58139
- Fixes#46903
---------
Co-authored-by: Steven <steven@ceriously.com>
### Why
The `process/browser` lib was imported and being transformed, but
`process.browser = true` turns to `true = true` that causes the
compilation error, we need to exclude them from certain compilation
layers
### What
- Fixes https://github.com/vercel/next.js/issues/61116
Closes NEXT-2410
Closes NEXT-2328
---------
Co-authored-by: Jiachi Liu <inbox@huozhi.im>
This implements falling back to try multiple locations loading chunks
for sourcemap tracing.
Unfortunately, when RSC replays server errors on the client, it does not
carry over the [0] symbol used to annotate server frames. Instead,
errors are recreated by React and only include the message and stack.
This allows more tests to pass, as we are able to correctly trace stack
frames by loading the appropriate server chunk.
Closes PACK-2442
### What
This PR injects a build-time error for the turbopack if
`client|server-only` is imported in incorrect context. The basic idea is
using resolve plugin, so in resolve time if matching context (which
alises erroneous import), raise a build time error.
Unfortunately this won't fix all of the tests in `invalid-imports`, due
to
1. resolveplugin does not have way to trace import from transformed, so
not able to detect `styled-jsx` from using `<styled..` tags
2. webpack (in our implementation) and turbopack's resolveplugin have
different order of transform / module trace chain, so enabling resolve
plugin in some context raises build error instead of runtime error in
rsc-build-error.
Closes PACK-2397
These are correct since #61735 fixed tracing these. Unfortunately they
don’t pass yet as the overlay is not properly dismissed when these
errors are fixed.
Closes PACK-2439
Fixes: #47978
When an error occurs in getInitialProps, the error page's
getInitialProps is run server-side and returned in `__NEXT_DATA__`.
Following, there's no need to re-run `getInitialProps` client-side on
the hydrate pass.
---------
Co-authored-by: JJ Kasper <jj@jjsweb.site>
### What
Exclude precompiled react packages from browser layer loaders coverage.
### Why
Since we're transpiling all the browser layer code now after #59569,
then SWC will also compile react. But when it compiles
`react.production.min.js` it gives me with the code and ESM helper
inserted
```js
import { _ as _type_of } from "@swc/helpers/_/_type_of"; // This is not correct
var l = Symbol.for("react.element"), n = Symbol.for("react.portal"), p = Symbol.for("react.fragment"), q = Sym
bol.for("react.strict_mode"), r = Symbol.for("react.profiler"), t = Symbol.for("react.provider"), u = Symbol.f
```
This makes bundler think it's a ESM package but actually it's CJS, which
converts the module into `{ default: .., __esModule }` instead of the
original react module.
When you're using `React.useEffect` or other API through namespace
import (`import * as React from 'react'`), this will break the module
exports check in bundling as the property doesn't directly attached to
the module now. This PR disabled the transform for precompiled react
packages now and will see the deeper issue in next-swc side later.
Fixes#60890Fixes#61185
Closes NEXT-2362
### What?
Fix the user-facing `MiddlewareConfig` interface.
~While in the codebase, I also made the incoming config object type a
bit more strict by converting from `any` to `unknown`.~ Reverted, as we
do a config assertion already in a [different
place](https://github.com/vercel/next.js/blob/canary/packages/next-swc/crates/next-custom-transforms/src/transforms/page_config.rs/#L171-L180).
### Why?
The interface we previously exposed was the one we used internally,
_after_ we did some parsing on the config object, which is different
from what the user is expected to pass.
### How?
I separated the internal type to its own `MiddlewareConfigParsed`
interface.
Closes NEXT-2375
Fixes#61705
Ref: #61576
### What?
depends on https://github.com/facebook/react/pull/28108
* fixes CSS Ordering issues due to CSS duplication in production mode
* The issues still happen in dev mode
* Highlights broken CSS Ordering for more dev cases, e. g. CSS in client
components
Closes PACK-2300
### What
This adds support for navigation signals like `notFound()` and
`redirect(url)` when Partial Prerendering has been enabled.
### Why
Navigation API's like `notFound()` and `redirect(url)` throw errors in
order to interrupt the rendering of components. When a page both invokes
API's that cause the render to be marked as dynamic (like
`unstable_noStore()`) and also a navigation API, these errors may race
to the end. In the case where the navigation error does not beat out the
error emitted by dynamic API's will still trigger the detection warning
that's present to warn you about situations where you may have
accidentally caught the error.
### How
This resolves this issue by explicitly checking for navigation signals
(errors) thrown during the render, and not displaying the "caught
dynamic API" error and console warning.
Closes NEXT-2037
## History
Previously, we added support for `squoosh` because it was a wasm
implementation that "just worked" on all platforms when running `next
dev` for the first time. However, it was slow so we always recommended
manually installing `sharp` for production use cases running `next
build` and `next start`.
Now that [`sharp` supports
webassembly](https://sharp.pixelplumbing.com/install#webassembly), we no
longer need to maintain `squoosh`, so it can be removed. We also don't
need to make the user install sharp manually because it can be installed
under `optionalDependencies`. I left it optional in case there was some
platform that still needed to manually install the wasm variant with
`npm install --cpu=wasm32 sharp` such as codesandbox/stackblitz (I don't
believe sharp has any fallback built in yet).
Since we can guarantee `sharp`, we can also remove `get-orientation` dep
and upgrade `image-size` dep.
I also moved an [existing `sharp`
test](https://github.com/vercel/next.js/pull/56674) into its own fixture
since it was unrelated to image optimization.
## Related Issues
- Fixes https://github.com/vercel/next.js/issues/41417
- Closes https://github.com/vercel/next.js/pull/54670
- Related https://github.com/vercel/next.js/issues/54708
- Related https://github.com/vercel/next.js/issues/44804
- Related https://github.com/vercel/next.js/issues/48820
- parsed stack traces (and error stack locations in js) have 1-based
lines and 1-based columns
- source map tokens have 0-based lines and 0-based columns
- babel code frames use 1-based lines and 0-based columns
This was not always respected. This preserves the 1-based lines and
columns in anything called a stack frame, 0-based lines and columns for
source map apis, and converts to babel’s format as needed.
Closes PACK-2341
---------
Co-authored-by: Tobias Koppers <tobias.koppers@googlemail.com>
### What?
This PR wraps up supporting rsc transforms (mostly for the assertion) in
Turbopack. PR contains a few changes to support it, including:
- adjust / expand transform rules for the corresponding contexts
- fix file name / node_modules check
- extract visitors for the assertion / transforms
This change enables most of the rsc-build* tests and some more other
tests. The only failing tests in the rsc-build-errors is due to
Turbopack not triggering hmr with empty file.
Closes PACK-2303
### What & Why
We have a modularize imports config for `next/server` before, which will
transform the `next/server` imports to directly import from the actual
file, for instance: `import { NextRequest } from 'next/server'` will
become `import { NextRequest } from
'next/dist/server/web/exports/next-request'`, where the NextRequest is
exported as default export. This is fine in most case until you're using
a ESM pkg, then it will be resolved as `{ default: NextRequest }`
according to the spec. Since it's a ESM import to a CJS module in
`next/dist`.
Since we already have the ESM alias introduced in #59852 , this can
handle the case more properly.
### How
Remove the modularize imports config for `next/server`, use the ESM api
alias instead.
Migrate the cjs optimizer tests from middleware to a separate endpoint
`/cjs/server`. As now ESM imports for next/server are not going to get
tree-shaken in dev, but since we don't have image response there it's
still fine.
Closes NEXT-2376
Closes NEXT-2374
### What
When navigating to a page with dynamic params using a certain casing,
and then following a link to another page using _different_ casing for
the same param, the router would get stuck in an infinite suspense
cycle.
### Why
On the client we normalize cache keys by lowercasing the values for
dynamic segments. However the RSC data for each segment wouldn't have
this same casing logic applied. This is causing the router to not
recognize that there is already RSC data available for that segment,
resulting in an infinite suspense cycle.
### How
The `toLowerCase()` logic shouldn't be needed here. Technically we could
leave this in place and update `matchSegment` to also apply the
lowercase logic, but currently there are too many utility functions that
parse segments to comfortably make that change. I confirmed that the bug
related to why we lowercased these router cache keys is no longer
present after making this change.
Fixes#61722
Closes NEXT-2377
### What
Client-side transitioning to a page that triggered a loading boundary
with async metadata would cause the transition to stall, potentially
getting stuck in a refetch loop.
### Why
In layout-router, we trigger a "lazy fetch" when we encounter a segment
that we don't have cache nodes for. This calls out to the server and
suspends until the data fetch is resolved, and applied to the router
tree. However after suspending but before updating the client router, we
set `childNode.lazyData` to null. When we unsuspend from the server
patch action, `childNode.rsc` might still be missing and clearing
`lazyData` means we've blown away the reference to the fetch we already
had pending, triggering a refetch loop.
### How
This removes the logic that mutates the cache node in render, as this is
not concurrent safe, and doesn't appear to be needed for anything.
Fixes#61117
Closes NEXT-2361
---------
Co-authored-by: Jiachi Liu <inbox@huozhi.im>
### What
#### Core
This PR respect the error's digest when recieves new error occurred from
server side, and it will be logged into client on production with the
same `digest` property.
If we discover the original RSC error in SSR error handler, retrieve the
original error
#### Tests
* Move the errors related tests from `test/e2e/app-dir/app` to a
separate test suite `test/e2e/app-dir/errors`
* Add a new test case for logging the original RSC error
* Add a new test case for logging the original Server Action error
### Why
This will help associate the `digest` property of the errors logged from
client with the actual generated server errors. Previously they're
different as we might re-compute the digest proper in handler that react
server renderer thinks it's a new error, which causes we have 2
different errors logged on server side, and 1 logged on client side. The
one on client side can associate to the server errors but it's from
react renderer which is not the original error.
Closes NEXT-2094
Fixes#60684
### What?
I forgot to check the `preload` option when implementing it and just
looked at the `subsets`.
This also fixes duplicate preload tags by adding them to a set in the
default `_document.tsx`
Closes PACK-2392
This PR fixes `.eslintrc.json` not being created after the user runs
`next lint` and selects an option of `Strict` or `Base`.
The reason is that the lint check was looking for `pages` and
`src/pages` only. Added `app` and `src/app` to be checked also.
Fixes: #55094Fixes: #55102
---------
Co-authored-by: JJ Kasper <jj@jjsweb.site>
### What?
Fixes `setAssetPrefix` when running on a custom server using next()
function
### Why?
Looks like when we run next custom server, there are 2 instances created
to handle this case
* main server in `/server/next.ts`
* and Render server `./server/lib/render-server.ts`
The issue mainly happens when calling `setAssetPrefix` it will update
only the main server and not render server
``` javascript
const next = require('next')
const app = next({ });
app.setAssetPrefix('my-fancy-cdn/static');
app.render(); // render server is used instead of the main server
```
### How?
when calling `setAssetPrefix` on the main server also update the render
server with the same information.
Fixes: #59940Fixes: #51223Fixes: #61383
### Related Resources
#53523#49805c9c6ff6d77/docs/03-pages/01-building-your-application/06-configuring/10-custom-server.mdx
---------
Co-authored-by: JJ Kasper <jj@jjsweb.site>
### What
This PR attempts to adjust import map to `server-only` / `client-only`
close to the existing webpack configs, makes to pass more tests.
Closes PACK-2396
### What?
Removing `autoprefixer` from the default Tailwind CSS templates. (It can
be installed afterward)
### Why?
After some investigation by @timneutkens, `autoprefixer` seems to
introduce some compilation overhead
### How?
Removing `autoprefixer` from the auto-installed dependency list, it
would be up to the developer to install this plugin if they need it.
[Slack
thread](https://vercel.slack.com/archives/C04DUD7EB1B/p1695288906722539)
### What?
Expose the `MiddlewareConfig` interface.
### Why?
You can now `import type { MiddlewareConfig } from "next/server"` to
type the `config` object in your `middleware.ts` file.
Now you an type the entire file for example like so:
```ts
// middleware.ts
import type { NextMiddleware, MiddlewareConfig } from "next/server"
export const middleware: NextMiddleware = async (req) => {
//...
}
export const config: MiddlewareConfig = {
//...
}
```
### How?
Re-exported the interface from its current location via
`server/web/types`, to colocate it with `NextMidldeware`.
I wonder if we could somehow type this file automatically, but it might
be dependent on https://github.com/microsoft/TypeScript/issues/38511
Closes NEXT-2308
[Slack
thread](https://vercel.slack.com/archives/C03S9JCH2Q5/p1706287433026409?thread_ts=1706058855.423019&cid=C03S9JCH2Q5),
[Slack
thread](https://vercel.slack.com/archives/C03KAR5DCKC/p1706659724141899)
### What
When attaching a rejection listener to a server action promise, in the case of network errors, the rejection handler would be skipped and it'd throw an error that crashes the application.
### Why
When we refactored these reducers to no longer suspend, it caused the rejection handling logic we have to no longer make sense. In this case we're working with a native promise that won't have a `status` property, so we'd re-throw the error and not call `reject`.
### How
This removes the special status handling logic and makes the rejection handler always call `reject` with the error. This will either be handled by user code or let the error bubble to an error boundary.
I also cleaned up some mutable code that is no longer needed now that these reducers aren't replayed.
Closes NEXT-1715
Closes NEXT-2323
Fixes#58638
## What?
Fixes the `should update server components pages when env files is
changed (edge)` tests. In order for changes to the environment to apply
to edge-runtime routes we need to call `clearModuleContext`, currently
that only supports a single path being provided, but in Turobpack the
compilation is much more granular than webpack, in case of webpack we
loop through all items coming out of the compilation and invalidate them
regardless, which is not needed for Turbopack. Instead, when an
entrypoint (route) is recompiled it'll automatically only invalidate
that part. For `.env` changes that don't affect compilation, which is
what the test checks, this wouldn't be sufficient as there is no
compilation difference between changing those env vars. In the case that
you change `.env` / tsconfig/jsconfig we have to clear all module
contexts, which is what this PR implements.
<!-- 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-2337
## What?
Whenever `.env` related files or tsconfig/jsconfig changes there's a
call to `invalidate()`, as far as I found the only call to
`invalidate()` even, which wasn't implemented for Turbopack yet. For
`NEXT_PUBLIC_` changes normal Turbopack HMR will kick in already but
this test was checking env vars that do not affect the compiled output,
so Turbopack would not trigger a HMR as no inputs changed. Similarly
webpack doesn't either and it implements this call in a similar way.
For edge runtime there's a different bug where changes are not
propagated even when you refresh, so while this change does fix another
bug for edge runtime it doesn't solve that underlying issue where the
values don't update to begin with. I'll investigate that next.
<!-- 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?
Fixes one of the styled-components tests. Somehow the test that checks
the warning shows up without the transform is not showing the warning
but the transform is also not enabled, so I've skipped the test as it's
not important for stable.
<!-- 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-2321
### What?
This adds a method to optionally detect disk, network, and env access
access during a build and write this to a file.
### Why?
This will be consumed by Turborepo to determine **if** a build can be
cached, and if so, **how** it should be cached.
### How?
This implements a proxy that can be selectively applied to functions to
watch their access to disk, network, and env. For Turborepo, we only
care about what can alter the build output, to achieve this, we trace
the config load, and the static page generation.
Closes
https://linear.app/vercel/issue/TURBO-1904/support-build-access-tracing-in-nextjs
Performance Testing:
Repo -
https://github.com/tknickman/nextjs-turborepo-build-trace-performance-testing
```
- - - - - - - - - - - - - - - - - Performance - - - - - - - - - - - - - - - - -
pages-single-app:
44629.53301 ms (+/- 6313.82757 ms) from 5 iterations (223318.53692 ms total)
local-pages-single-app-with-trace:
45684.00503 ms (+/- 6570.85083 ms) from 5 iterations (228585.01729 ms total)
local-pages-single-app-without-trace:
45938.76231 ms (+/- 6816.13022 ms) from 5 iterations (229830.15925 ms total)
approuter-single-app:
49517.23156 ms (+/- 7820.20687 ms) from 5 iterations (247725.16713 ms total)
local-approuter-single-app-with-trace:
50019.98247 ms (+/- 9443.82537 ms) from 5 iterations (250224.62496 ms total)
local-approuter-single-app-without-trace:
50124.07092 ms (+/- 9656.22047 ms) from 5 iterations (250726.35688 ms total)
local-large-pages-single-app-without-trace:
51582.92992 ms (+/- 12179.09895 ms) from 5 iterations (258469.36942 ms total)
local-large-pages-single-app-with-trace:
51740.25813 ms (+/- 12601.02878 ms) from 5 iterations (259329.50946 ms total)
local-xlarge-pages-single-app-with-trace:
234111.66735 ms (+/- 74629.30509 ms) from 5 iterations (1191018.63608 ms total)
local-xlarge-pages-single-app-without-trace:
239621.11837 ms (+/- 84629.16374 ms) from 5 iterations (1218078.41921 ms total)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
```
<details>
<summary>Test case keys</summary>
* `local-xlarge-pages-single-app-without-trace`: this branch, built and
linked to a local project with 5000 SSG pages and trace **disabled**
* `local-xlarge-pages-single-app-with-trace`: this branch, built and
linked to a local project with 5000 SSG pages and trace **enabled**
* `local-large-pages-single-app-with-trace`: this branch, built and
linked to a local project with 100 SSG pages and trace **enabled**
* `local-large-pages-single-app-without-trace`: this branch, built and
linked to a local project with 100 SSG pages and trace **disabled**
* `local-approuter-single-app-without-trace`: this branch, built and
linked to a local default approuter starter and trace **disabled**
* `local-approuter-single-app-with-trace`: this branch, built and linked
to a local default approuter starter and trace **enabled**
* `local-pages-single-app-with-trace`: this branch, built and linked to
a local default pages starter and trace **enabled**
* `local-pages-single-app-without-trace`: this branch, built and linked
to a local default pages starter and trace **disabled**
* `approuter-single-app`: next@latest running on the default approuter
starter
* `pages-single-app`: next@latest running on the default pages starter
</details>
TODO:
- [ ] Telemetry events
### What
When using a default slot that re-exports another page, the CSS entries
(and presumably other client reference modules, like JS entries) that
correspond with the re-exported page won't be loaded, resulting in CSS
styles not being applied.
### Why
`next-app-loader` constructs the path to the default segment but special
cases the `children` slot (which is used as the page), to mark the
segment as an empty string. This is so that the parallel default file
can be loaded. However the way that `defaultPath` is constructed, it
assumes that `actualSegment` won't be an empty string, and constructs an
invalid path like so:
`app/example//default.tsx`
When we go to look up the JS/CSS entries from the client reference
manifest, the key will be incorrect and so it won't find the files for
it, resulting in this bug.
### How
This moves the `/` delimiting to be part of the creation of the
`actualSegment` variable so that we only append it when we know we
aren't setting it to be an empty string.
Fixes#52245Fixes#49871
Closes NEXT-2309
Closes NEXT-2310
When using `next/dynamic` in server components to load a client
component with named export, we shouldn't dot into the prop name since
client component reference as it's already a valid react component type.
It would work with `default` prop but not other named exports.
Let's say `mod` is a dynamic imported module
```
mod.Button.default
```
will become the client reference key
```
mod#Button#default
```
Which means in module `mod`, get `Button` export, then `default`
property of it, which is wrong but it's a valid key in the client
reference roxy.
This PR checks if they're client module, then return itself as dynamic
imported component type for `next/dynamic` if it is one.
Fixes#61046
Closes NEXT-2229
### What
Catch-all parallel slots were being incorrectly matched to the root of their segment. For example, `@foo/[...catchAll]/page` as a parallel route on `/page.tsx` should not match on `/`, but it should match on `/foo`, `/bar`, ...etc
### Why
The catch-all route normalization logic doesn't treat optional catch-all routes differently from catch-all routes. The assumption was if any catch-all route was found, that it should match the path that shared its prefix.
### How
This updates the normalization logic to handle optional-catchall as it was in the original implementation. For regular catch-all, we ensure that the catch-all base path (for `/[...slug]` that'd be `/`) isn't identical to the path we'd match it to.
Fixes#60613
Closes NEXT-2243
Refining the message that uses "use with caution" instead of "use at
your own risk" as some experimental features was functionally stable but
we can't bring them as default for now and need to test as experiments
Closes NEXT-2286
### What
Given user infomation when the dynamic errors are thrown, e.g. bad
`cookies` or `headers` usages. Now users can tell through the error
information to see which pathname is broken, and trace down the usage.
#### before
```
Page couldn't be rendered statically because ...
This page needs to bail out of prerendering at this point because ...
```
#### after
```
Route /cookies couldn't be rendered statically because ...
Route /server needs to bail out of prerendering at this point because ...
```
### Why
When you have multi pages in your app, such as 100+, and many page might
uses these. This is hard to trace down where exactly the error is from
Closes NEXT-2283
Cloese NEXT-2265
When we apply `createActionProxy` twice to the same value, it currently
errors because we can't override the ID of it.
This PR makes sure that 1) when the value already have an ID defined, we
skip setting it again; 2) all the action IDs are being tracked even for
duplicated ones.
Note that it's technically impossible to "detect" the duplication here
(via static analyzation) and only set it once. For example:
```ts
'use server'
export async function foo () {}
export const bar = a_value_we_dont_know_yet ? foo : async () => {}
```
So, the compiler will always wrap `createActionProxy` for every exported
value and assume they're different Server Actions (hence different IDs).
With this fix, if we find that it's already defined before, we just
return the defined reference as they're strictly identical so the ID
does't matter.
Closes#54655, closes#61183.
Closes NEXT-2264
This PR fixes the cookie merging logic in Server Actions. Specifically,
when users do `cookies().set(...)` or `cookies.delete(...)` with a
`redirect()` to an internal route followed. Currently, we are just
concatenating the original cookies (request cookies) and the mutated
cookies. That introduces several issues, like it can't override or
delete an existing cookie.
Closes NEXT-2221
## What?
Currently we have a test that checks for:
```
{
"name": "my-package",
"edge-light": "./edge-light-file.js"
}
```
However we should only support it in `exports` and `imports` conditions,
which is also what packages published use currently. This updates the
tests to reflect the correct behavior in Turbopack.
<!-- 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-2262
## What?
Fixes the condition being checked to match for Turbopack which always
adds the blur.
Webpack needed to lazy eval blur during `next dev` but Turbopack can
always blur since its much faster.
Closes NEXT-2259
### What?
When using layouts in multiple parallel route slots, only 1 of the
layouts would render.
### Why?
The `resolveParallelSegments` logic responsible for populating the
loader tree was incorrectly bailing if it found another parallel route
that matched a page component.
### How?
I did my best to update this loader code with some more comments to make
it a bit easier to reason about, and also made some slight refactors.
But the gist of the fix is just ensuring that each parallel route (that
isn't a direct match on the `children` slot) is resolved as an array, so
that when the subtree is created, it doesn't skip over the slot.
Fixes#58506Fixes#59463
Closes NEXT-2222
## What?
Turbopack has the correct behavior of preferring `.ts` / `.tsx` for
first-party code. In Webpack we don't have a way to only resolve
`.ts`/`.tsx` in first-party code. Turbopack doesn't resolve `.ts`/`.tsx`
in `node_modules`.
<!-- 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-2254
When there's `useSearchParams` hook triggers the bailout to client side
rendering, users might hard to find where it's from since it could
either from users code base or third party libraries. Adding the stack
trace for it so they could at least investigate which line is throwing
from the server bundle. Will improve it in the later future when we can
give more insights.
#### After
```
⨯ useSearchParams() should be wrapped in a suspense boundary at page "/". Read more: https://
nextjs.org/docs/messages/missing-suspense-with-csr-bailout
at a (/private/var/folders/gy/kq4zjn8s0ljf9sfjyyh_nj640000gn/T/next-install-aa5f331b7f6af2
82fd9bab0f69685454d1f50dc8f3c775da23d4e5e807a970cb/.next/server/chunks/846.js:1:9912)
at h (/private/var/folders/gy/kq4zjn8s0ljf9sfjyyh_nj640000gn/T/next-install-aa5f331b7f6af2
82fd9bab0f69685454d1f50dc8f3c775da23d4e5e807a970cb/.next/server/chunks/846.js:1:22018)
at a (/private/var/folders/gy/kq4zjn8s0ljf9sfjyyh_nj640000gn/T/next-install-aa5f331b7f6af2
82fd9bab0f69685454d1f50dc8f3c775da23d4e5e807a970cb/.next/server/app/page.js:1:2518)
```
#### Before
```
⨯ useSearchParams() should be wrapped in a suspense boundary at page "/". Read more: https://
nextjs.org/docs/messages/missing-suspense-with-csr-bailout
```
Closes NEXT-2239
### What & Why
Using parallel routes with edge runtime would cause a build error when
using a default segment, because edge runtime has special handling to
[read the client reference
manifests](12c9040568/packages/next/src/build/utils.ts (L1543-L1555))
for these when determining if a page is static.
### How
In a similar fashion to how we exclude static checks on reserved pages,
I added similar handling for app pages.
Fixes#60917
Closes NEXT-2241
## What?
`exportPathMap` didn't work when Turbopack was enabled because the
`serializeNextConfig` function mutates the original values, overriding
`exportPathMap`.
This PR changes the serialization to copy the object and mutate only the
copied object.
Also refactored the test that was checking `_next`, the better way to
test that is to have the page render something dynamically, which is
what is added in this PR.
<!-- 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-2225
### What?
This fixes 2 issues with app 404 pages.
1. The root layout in a group was previously ignored when hitting the
404 page.
2. The default app 404 page was missing the correct path for dev
`/not-found` so it would fall back to the pages 404 page.
Closes PACK-2241
Fixes#60688
### What
When users're using nextjs server API that break the build, and error
with incorrect client components usage.
Instrument should be treated as server components or server-only build
target, instead of being treated as client components.
### How
We added a new layer `instrument` for instrument hook bundling, and
apply it with the rsc server webpack loaders
Fixes#57563
Closes NEXT-2181
Closes NEXT-1994
### What?
Interception routes on dynamic paths don't currently work when PPR is
turned on, and instead trigger an MPA navigation to the full route.
### Why?
Route interception relies on the `Next-Flight-Router-State` header to
extract the dynamic params necessary to convert something like
`[locale]`, which would correspond with a URL of `/en`, to something
like `["locale", "en", "d"]`. (See [this
function](fbfd7b5f81/packages/next/src/server/app-render/app-render.tsx (L129-L137))
for more info). When PPR is turned on, we currently ignore this request
header and don't provide it to the functions that render the component
tree.
Without the flight router state, this function bails out and instead
will leave the segment key as `[locale]`. When the client router goes to
diff the current tree on the client with the response from the server,
it will detect a mismatch between the current segment and the incoming
segment, and trigger an MPA navigation in [this
block](fbfd7b5f81/packages/next/src/client/components/router-reducer/reducers/navigate-reducer.ts (L414-L416)).
### How?
This special-cases interception routes to not strip this header.
Closes NEXT-2215
### What
Fixes the string id that broken when sitemap is optimized to static
route.
### Why
When sitemap is optimized to static route in production, the route
argument is changed from `[[...__metadata_id__]]` to
`[__metadata_id__]`, so the type of it is also changed from array to
string that should reflect in the loader code.
Fixes#60894
Closes NEXT-2154
## What?
Fixes `should have <head> containing <meta name=\"viewport\"> followed
by <link rel=\"preload\"> for priority image` and `should add a blur
placeholder a statically imported x` (where x is a file format) in
Turbopack.
<!-- 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-2216
# Turbopack
* https://github.com/vercel/turbo/pull/7027 <!-- Donny/강동윤 - Update `swc_core` to `v0.87.28` -->
---
### What?
Update swc crates
### Why?
Required for #57718.
`styled-jsx` crate now has a hook to transform CSS code using a
Rust-side API
### How?
Fixes#57718
Closes PACK-2256
### What?
Update terser to the latest version.
### Why?
We need
c677e28526
which adds supports for class static blocks.
### How?
Closes PACK-2285
Fixes#60837
### What
We've had the Next.js version checker in dev overlay of webpack mode.
But it was missing for turbopack. Add it in turbopack mode and also give
a small marker `"(turbo)"` to highlight turbopack mode.
Screenshot
<img width="576" alt="image"
src="https://github.com/vercel/next.js/assets/4800338/1bb1500c-fd92-43bd-a60a-ddc7cd63ce6f">
Closes NEXT-2196
Closes NEXT-2106
formalizes the concept of dynamic APIs inside Next to allow for varying
semantics beyond just staticGenerationBailout.
### Dynamic APIs
#### `markCurrentScopeAsDynamic`
useful to bail out of default caching semantics but does not imply a
Request specific data source was read. critically, this semantic is
ignored if you are inside a cache scope
#### `trackDynamicDataAccessed`
Must be called before reading any data source that is derived from
Request specific data. Currently this is `cookies()`, `headers()`, and
`searchParams`. This kind of data access inside a cache scope is
forbidden (it always should have been, but now it will error).
#### `trackDynamicFetch`
This one is unideal but the complexity of patch-fetch's current
implementation necessitates it for now. Essentially it will postpone if
we are prerendering. Long term this should be eliminated with a refactor
of patch fetch.
### Other Improvements
Also removes the `staticGenerationBailout` implementation as it has been
replaced with more specific logic in the places it was previously being
used.
One area that has also been enhanced is the proxy for app-route modules.
Previously we proxied the Request every time however when we are doing
non-static generation executions we generally don't want the overhead of
wrapping the request. In the refactor here I also improved the runtime
performance by using static proxy handlers and I believe I also fixed a
few bugs related to `clone` and `url`
In general there has been a bit of refactoring to clarify how we should
handle various render/execution states and a reduction in implicit side
effects for proper execution.
Another callout to notice is that app-route modules do not attempt a
static generation if they are force-dynamic regardless of the PPR
setting. Previously the PPR setting would opt them into this code path
which is not necessary because PPR itself does not work for routes, only
pages.
Closes NEXT-2099
fixes NEXT-2173
Fixes#59968
### TODOs
- [x] recreate [repro](https://github.com/williamli/nextjs-NEXT-2173)
- [x] patch `useSelectedLayoutSegment` to support parallel routes (see
"What")
- [x] check `useSelectedLayoutSegments` to see if it is affected
- [x] add test cases
- [x] finalise PR description
### What?
`useSelectedLayoutSegment` does not return the name of the active state
of parallel route slots.
#### Expected Behaviour
According to
https://nextjs.org/docs/app/building-your-application/routing/parallel-routes#useselectedlayoutsegments
> When a user navigates to app/@auth/login (or /login in the URL bar),
loginSegments will be equal to the string "login".
👉🏽 We should update the docs to explain `null` and __DEFAULT__ result as
well.
According to the [API reference for
useSelectedLayoutSegment](https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment#returns):
> useSelectedLayoutSegment returns a string of the active segment or
null if one doesn't exist.
> For example, given the Layouts and URLs below, the returned segment
would be:
> <img width="881" alt="CleanShot 2024-01-20 at 14 50 52@2x"
src="https://github.com/vercel/next.js/assets/179761/bfaa34c8-3139-4ec3-bd70-4346c682e36b">
#### Current Behaviour
Currently a string "children" is returned for everything inside a
parallel route with active state and `__DEFAULT__` is returned if there
is no active state for the parallel route (since the `default.tsx` is
loaded). ~`null` is returned when the `default.tsx` is not loaded
(possibly caused by another bug, see test case 5).~
#### Reproduction
[GitHub Repo](https://github.com/williamli/nextjs-NEXT-2173) is created
based on the example provided in [Next.js docs for using
`useSelectedLayoutSegment` with Parallel
Routes](https://nextjs.org/docs/app/building-your-application/routing/parallel-routes#useselectedlayoutsegments).
#### Test Cases
1. If you visit https://next-2173.vercel.app/, you get loginSegments:
__DEFAULT__ (hard navigation) or children (soft navigation after
returning from a visit to /login)
2. If you soft nav to (/app/@auth/login and /app/@nav/login)
https://next-2173.vercel.app/login, you get
1. loginSegment: `children` (expected value should be `login`)
2. navSegment: `children` (expected value should be `login`)
3. If you soft nav to (/app/@auth/reset)
https://next-2173.vercel.app/reset, you get
1. loginSegments: `children` (expected value should be `reset`)
2. navSegment: `children` (expected value should be `login`)
4. If you soft nav to (/app/@auth/reset/withEmail)
https://next-2173.vercel.app/reset/withEmail, you get
1. loginSegments: `children` (expected value should be `withEmail`)
2. navSegment: `children` (expected value should be `login`)
5. ~If you hard nav to (/app/@auth/reset/withEmail)
https://next-2173.vercel.app/reset/withEmail, you get an unexpected
result due to possibly another bug:~
* ~navSegment is `null` on the deployed (Vercel) version, the navSlot is
*not* loaded~
* ~navSegment is `__DEFAULT__` on local dev, the navSlot loads
`/app/@nav/default.tsx`.~
### Why?
In `packages/next/src/client/components/navigation.ts`,
`getSelectedLayoutSegmentPath` is called and returns the correct
segmentPath for parallel routes (even though there is a TODO comment
indicating this function needs to be updated to handle parallel routes)
but `useSelectedLayoutSegment` failed to return the correct segment when
a parallelRouteKey is provided.
### How?
`useSelectedLayoutSegment` is updated to return
selectedLayoutSegments[0] for non parallel routes (original logic), but
it will return the last segments for parallel routes (or null if nothing
is active).
```
return parallelRouteKey === 'children'
? selectedLayoutSegments[0]
: selectedLayoutSegments[selectedLayoutSegments.length-1] ?? null
```
---------
Co-authored-by: Zack Tanner <zacktanner@gmail.com>
This PR adds a warning when attempting to optimize an animated image.
```jsx
<Image src="/image.gif" />
```
The warning looks like the following:
```
The requested resource "/image.gif" is an animated image so it will not be optimized. Consider adding the "unoptimized" property to the <Image>.
```
To remove the warning, add the `unoptimized` prop.
```jsx
<Image src="/image.gif" unoptimized />
```
We don't attempt to optimized animated images because it can be very
slow (30+ seconds) and sometimes deoptimizeds (the output is larger than
the input) so its best to serve the animated image as-is.
Closes NEXT-2199
Fix NEXT-2165
### What?
Addresses the limitation of #60240, where a dummy `default` file is
required in parallel route child slot to prevent errors in dev server
rendering (`TypeError: Cannot read properties of undefined (reading
'clientModules')`) as well as errors in build and deploy (`Error:
ENOENT: no such file or directory, lstat
‘/vercel/path0/.next/server/app/parallel-route/[section]/@part/[partSlug]/page_client-reference-manifest.js’`)
Without the `default.tsx`, builds and deployments will fail with:
<img width="956" alt="CleanShot 2024-01-18 at 02 12 36@2x"
src="https://github.com/vercel/next.js/assets/179761/80ba61bd-6ec0-4b16-a393-dc9375227e19">
local dev server will also crash with:
<img width="986" alt="CleanShot 2024-01-18 at 02 13 19@2x"
src="https://github.com/vercel/next.js/assets/179761/cc500a32-b2f8-47b4-999e-e57cf5141b2f">
> TypeError: Cannot read properties of undefined (reading
'clientModules')
### Why?
Since `default.tsx` is not a compulsory when you have slot that are
specific and ends with a dynamic route segment, this PR extends support
so that it is possible mixing catch-all routes with specific
non-catchall routes without requiring an additional `default.tsx` .
This PR will allow the following test cases to pass:
```
it('should not add the catch-all route to segments that have a more specific [dynamicRoute]', () => {
const appPaths = {
'/': ['/page'],
'/[[...catchAll]]': ['/[[...catchAll]]/page'],
'/nested/[foo]/[bar]/default': [
'/nested/[foo]/[bar]/default',
'/nested/[foo]/[bar]/@slot0/default',
'/nested/[foo]/[bar]/@slot2/default',
],
'/nested/[foo]/[bar]': [
'/nested/[foo]/[bar]/@slot0/page',
'/nested/[foo]/[bar]/@slot1/page',
],
'/nested/[foo]/[bar]/[baz]': [
'/nested/[foo]/[bar]/@slot0/[baz]/page',
'/nested/[foo]/[bar]/@slot1/[baz]/page',
],
'/[locale]/nested/[foo]/[bar]/[baz]/[qux]': [
'/[locale]/nested/[foo]/[bar]/@slot1/[baz]/[qux]/page',
],
}
const initialAppPaths = JSON.parse(JSON.stringify(appPaths))
normalizeCatchAllRoutes(appPaths)
expect(appPaths).toMatchObject(initialAppPaths)
})
...
```
```it('should not add the catch-all route to segments that have a more specific [dynamicRoute]', () => {
const appPaths = {
'/': ['/page'],
'/[[...catchAll]]': ['/[[...catchAll]]/page'],
'/nested/[foo]/[bar]/default': [
'/nested/[foo]/[bar]/default',
'/nested/[foo]/[bar]/@slot0/default',
'/nested/[foo]/[bar]/@slot2/default',
],
'/nested/[foo]/[bar]': [
'/nested/[foo]/[bar]/@slot0/page',
'/nested/[foo]/[bar]/@slot1/page',
],
'/nested/[foo]/[bar]/[baz]': [
'/nested/[foo]/[bar]/@slot0/[baz]/page',
'/nested/[foo]/[bar]/@slot1/[baz]/page',
],
'/[locale]/nested/[foo]/[bar]/[baz]/[qux]': [
'/[locale]/nested/[foo]/[bar]/@slot1/[baz]/[qux]/page',
],
}
...
```
and allow parallel routes defined in this [code
repro](https://github.com/williamli/nextjs-NEXT-2165) to build.
![image](https://github.com/vercel/next.js/assets/179761/030f4fe1-3a27-41e5-bbd9-bc511f95e5d7)
### How?
`packages/next/src/build/normalize-catchall-routes.ts` is extended to
check `appPath` to see if it is:
1. the route is not a catchall
2. `isMoreSpecific` than the closest `catchAllRoute`.
where `isMoreSpecific` is defined as:
```
function isMoreSpecific(pathname: string, catchAllRoute: string): boolean {
const pathnameDepth = pathname.split('/').length
const catchAllRouteDepth = catchAllRoute.split('/').length - 1
return pathnameDepth > catchAllRouteDepth
}
```
---------
Co-authored-by: Zack Tanner <zacktanner@gmail.com>
## What?
Implements https://github.com/vercel/turbo/pull/7081. Ensures image
imports in the edge runtime have the correct asset url. Previously it
would be `/assets/file.hash.png` but it should be
`/_next/static/media/file.hash.png`.
Updates the image tests to correctly compare the values in Turbopack and
the values in Webpack. Currently it only checks webpack values, causing
the tests to fail in Turbopack.
<!-- 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-2194
### What & Why?
Interception routes depend on contextual information that are provided
via request headers. Specifically it needs to know about the
`Next-Router-State-Tree` when generating the interception route RSC
data, which isn't available at build time. This doesn't currently cause
any usage issues, but it erroneously emits static files & RSC payloads
that the client router won't be able to use and will instead fallback to
a dynamic request.
I removed some special case in an existing test since this fix also
resolves a discrepancy in behavior when PPR is turned on
### How?
This excludes interception routes from `appStaticPaths` at builds which
currently determines which pages should be statically generated.
Closes NEXT-2190
### Description
This PR refactors existing `analysis/get-static-page-info`, moves over
most of parse / ast visiting logic into next-swc's rust codebase. By
having this, turbopack can reuse same logic to extract info for the
analysis. Also as a side effect, this removes JS side parse which is
known to be inefficient due to serialization / deserialization.
The entrypoint `getPageStaticInfo` is still in the existing
`get-page-static-info`, only for extracting / visiting logic is moved.
There are some JS specific context to postprocess extracted information
which would require additional effort to move into.
Closes PACK-2088
## What?
There were a bunch of Sharp related tests failing when running the test
suite with Turbopack. The reason for this was that we automatically
detect the root of the project based on the closest lockfile (i.e.
package-lock.json). In this particular test a new package-lock.json was
added and since this suite is not yet isolated it cases problems.
This PR adds `outputFileTracingRoot` to explicitly provide the root of
the project, which ensures the right files are resolved.
Closes NEXT-2180
In both dev server and production build we both use `getStartServerInfo`
to log the basic info but for prod build we should always respect to use
"build" phase
Fixes#57927
Closes NEXT-2179
This:
- Makes makes reporting hmr changes more accurate by emitting an
explicit start event and lowering the aggregation period for reporting
completed turbo tasks
- Parameterizes the aggregation period, allowing JS subscribers to
request different intervals, such as for the next-rs-api test
- Aligns path pattern with webpack by normalizing its layer names
- Fixes a bug in `drainAndGetNext` where the stream never could drain
past the first item
- Sends `client-hmr-latency` spans from Turbopack in both page and app
router pages
Closes PACK-2252
---------
Co-authored-by: Tobias Koppers <tobias.koppers@googlemail.com>
### 🧐 What's in there?
`config.analyticsId` is a rarely-used mechanism, initially intended to
Next.js users hosting their application themselves and willing to report
Core Web Vitals to Vercel Speed Insights.
This platform specific mechanism can be replaced with the built-in
[`useReportWebVitals`](https://nextjs.org/docs/app/api-reference/functions/use-report-web-vitals).
### 🧪 How to test?
1. make a new Next.js app
1. define env variable `VERCEL_ANALYTICS_ID` to a dummy value
1. start your application in dev mode:
```shell
⚠ config.analyticsId is deprecated and will be removed in next major
version. Read more:
https://nextjs.org/docs/messages/deprecated-analyticsid
▲ Next.js 14.0.5-canary.58
- Local: http://localhost:3000
✓ Ready in 917ms
```
1. build your application:
```shell
▲ Next.js 14.0.5-canary.58
Creating an optimized production build ...
✓ Compiled successfully
Linting and checking validity of types .
⚠ The Next.js plugin was not detected in your ESLint configuration. See
https://nextjs.org/docs/basic-features/eslint#migrating-existing-config
✓ Linting and checking validity of types
✓ Collecting page data
✓ Generating static pages (4/4)
⚠ `config.analyticsId` is deprecated and will be removed in next major
version. Read more:
https://nextjs.org/docs/messages/deprecated-analyticsid
```
1. remove the env variable, add a `next.config.js` file with a dummy
`analyticsId` variable:
```js
module.exports = { analyticsId: "UA-12345678-9" };
```
1. start your application in dev mode: it'll issue the same warning.
1. build your application: it'll issue the same warning.
---------
Co-authored-by: Tim Neutkens <tim@timneutkens.nl>
`experimental.missingSuspenseWithCSRBailout` should be enabled by
default to help users to disciver unwrapped suspense boundaries.
Add more notes in the error doc about deprecation and temporary
workaround to disable it.
Closes NEXT-2157
---------
Co-authored-by: JJ Kasper <jj@jjsweb.site>
### 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
This PR fixes the issue where an inline Server Action gets exported. As
this isn't the designed use case for inline Server Actions (they're
supposed to be defined and used inside another closure, such as
components), we are not handling the export cases currently:
```ts
export async function action() {
"use server"
...
}
<form action={action}/>
```
...which gets compiled into:
```ts
export async function action() {} // No-op function
<form action={...actionReference...}/>
```
Note that everything works inside this module until you `import` that
action and use it in another module.
To tackle that, this PR changes how that works as described in
`server/27/output.js`.
Closes NEXT-2140
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>
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?
Updates snapshots for Turbopack tests. They're slightly different than
the webpack output. Generally better because column information is
preserved. The import trace is not available in Turbopack as it would
make the parent module a direct dependency of the module, meaning it
would have to recompile every time you can the parent module. We'll
figure out if it can be added in a different way at a later point.
<!-- 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-2101
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
### 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
### 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>