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>
In preparation for the refactor of cache utils in subsequent PRs, this PR moves the one-off prefetch cache utils into a shared `prefetch-cache-utils` file, and also relocates the `buildCustomRoute` util into an isolated lib so that it can be imported into base-server (in a future PR).
This PR does not make any changes to these functions.
Closes NEXT-2394
### 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
In #61649 the paragraph `"This function allows you to redirect the user
to another URL. It can be used in..."` describing `notFound` was copied
as is from the `redirect` jsDoc
---------
Co-authored-by: JJ Kasper <jj@jjsweb.site>
### 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>
<!-- 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
### How?
Closes NEXT-
Fixes #
-->
### What?
This PR introduces a ground work to generate wasm bindings package from
our napi bindings. This doesn't actually replace anything yet, however
aim to establish our napi bindings package can be built against wasm32
target.
### Why?
We currently have two bindings package to generate native / wasm target
support, one for napi and one other for wasm. Recently napi-rs started
to support to generate bindings for the wasm directly - which means we
can get rid of the wasm-pack based bindings code entirely and maintain a
single bindings code only.
This'll makes our `next-swc` simpler as well, since the invocation to
the bindings now becomes identical we don't have to additional wasm
specific logics to invoke functions (i.e transform, transformsync..).
Also napi generates wasi-supported wasm bindings, provides few more
features to the current wasm bindings.
#### Good
- Async napi binding fn works transparently (`transform`, `minify`...)
- (Experimental) thread supports depends on node.js runtime
- Wasi support: i.e it can even read filesystem directly!
#### Things to consider
- node.js's wasi support is experimental yet
- napi-rs's wasm support is in beta yet, specifically `packaging`
generated wasm output.
Due to `things to consider` reasons, this PR does not replace existing
wasm target yet. We should be able to plan out things later.
**What happens to the turbopack api in napi bindings?**
Simply put, this **does not support turbopack in wasm**. Build works by
disabling turbopack (more notably, underlying dependency doesn't support
wasm) features. It is something to explore separately.
Closes PACK-2367
There is a branch at https://github.com/vercel/next.js/pull/61586 shows
quick demo for importing, running sync / async / read external files.
### 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?
Let the developer check the instance of `ReadonlyURLSearchParams` to
match against `URLSearchParams`
### Why?
`useSearchParams()`'s return type is `ReadonlyURLSearchParams` which
implements all the methods of `URLSearchParams`, therefore its type
should be extended from `URLSearchParams` as well. Deprecated methods
are also implemented to throw an error, so no runtime behavior is being
changed
### How?
Mark the unavailable methods as `@deprecated` which will visually mark
them in IDEs:
![image](https://github.com/vercel/next.js/assets/18369201/f3de2858-14ac-4021-981d-b0267610faa7)
This is similar how `ReadonlyHeaders` extends `Headers`, added in:
#49075
[Slack
thread](https://vercel.slack.com/archives/C03KAR5DCKC/p1706628877916779)
Closes NEXT-2305
### 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 adds JSDoc comments to the most common public APIs to improve
the DX in IDEs like VSCode.
### Why?
Currently, we provide no information on some of the most used APIs in
IDEs, which makes it harder than it needs to be to look up the extra
information.
<details>
<summary><b>Before:</b></summary>
<img
src="https://github.com/vercel/next.js/assets/18369201/8b6092e8-8f9b-49da-a3df-b07a59982069"
width="640"/>
</details>
<details>
<summary><b>After:</b></summary>
<img
src="https://github.com/vercel/next.js/assets/18369201/30216f76-414a-43b0-9aa6-2fdd742ab3fe"
width="640"/>
</details>
### How?
Using JSDoc comments, I added a basic description to most public APIs
that link back to the current docs for more details. The description is
kept minimal to avoid out-of-sync documentation.
Note: In the future, the flow could be reversed here, and our API
Reference docs could actually be generated from a single source of
truth, the source code itself. However, this will require more work by
re-organizing our public API submodules in a single directory, (related
#61525), so the API docs are easy to maintain even without a deeper
knowledge of the codebase.
Note: These comments should also be extended to
methods/properties/arguments in these public APIs in the future.
Closes NEXT-2357
[Slack
thread](https://vercel.slack.com/archives/C03KAR5DCKC/p1706735292633029)
See here for additional context
https://github.com/vercel/edge-runtime/pull/795 but TLDR is due to a bug
in the `npmcli` we aren't able to publish Next.js releases after this
package was upgraded.
We can re-land the upgrade after that PR is landed/published.
Reverts vercel/next.js#61030
Closes NEXT-2367
### 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)
## Improving Documentation
### The following changes have been made to the official repository's
**Readme.md**:
- Shortened link text across the readme.
- Added additional descriptions for more details.
- Added bold text to highlight emphasis on important topics
- Changed heading sizes to indicate first headings (h1) for each section
instead of second headings (h2) which was previously being used
- Merged _'Who is using Next.js?'_ section with _'Getting Started'_
section for a more professional, cleaner look.
### The following changes have been made to the repository's
**Contribution docs**:
- Fixed two typos in the docs
---------
Co-authored-by: Sam Ko <sam@vercel.com>
Co-authored-by: Delba de Oliveira <32464864+delbaoliveira@users.noreply.github.com>
fixes#61390
### What?
Added encodeURIComponent to encode revalidateTag value beforing
appending it to the url.
### Why?
If a tag contains special characters the tag wont be revalidated because
the special characters arent encoded.
By encoding the tag any special characters can be used.
Check out issue #61390 for further explanation
I believe this is the reason why users report the revalidateTag as
unreliable. They might be using special characters in their tags to make
sure they are unique, but when deployed to vercel and the fetch cache is
used revalidateTag fail to revalidate them.
### How?
By encoding revalidateTag with encodeURIcomponent the tag can contain
special characters.
Closes NEXT-
Fixes#61390
---------
Co-authored-by: JJ Kasper <jj@jjsweb.site>
### 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?
We need the manifest to pass a bunch of preloading tests.
Currently, this is just a dumb implementation that preloads all fonts
and always sets size-adjust to true.
Google fonts are also still requested from Google directly it seems and
therefore never preloaded.
## 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 #
-->
Follow up for #61463
Basically the fix in #61463 was not correct. I added a log to see which
react is resolved in `dynmiac-rendering` module, and the got this:
The module with incorrect react version is from
`next.js/packages/next/dist/compiled/next-server/app-route.runtime.prod.js`
which resolves `react` as `./dist/compiled/react/index.js` even
experimental react should pop in here.
Then I found the app-route runtime doesn't have check for the react exp
env, then I added there to make it aligned with app-page runtime
Closes NEXT-2327
Closes NEXT-2294
### What
The `arg` in the worker callback is alwasy `any`, when we access the
page path the argument could be in different form as the arg types are
different.
This PR align the argument type to object for `isPageStatic`,
`getDefinedNamedExports`, `hasCustomGetInitialProps` methods in static
worker. So they can share the similar shape of type of argument when
accessing `page` path. This will avoid the case that logged `page` in
the warning is `undefined`
Import the helpers from utils instead of workers as the worker itself
don't need to contain other exports that is not used for static worker.
### Why
This PR align the callback type of callback argument type of static
worker, so that we could get the actual page path value in a type-safe
way. We have 4 methods for static worker, `exportPage`, `isPageStatic`,
`getDefinedNamedExports`, `hasCustomGetInitialProps`, which the rest of
3 methods share the same format of warnings but their argument are
different. It's easily ended up with wrong argument type, and log with a
bad page path in the warning.
Closes NEXT-2289
### 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
This ensures we don't do un-necessary IPC calls during image optimizing
and leverage the internal request handler for fetching internal static
images/resources.
x-ref: https://github.com/vercel/next.js/issues/58248
Closes NEXT-2318
### What?
avoid sending issues turbopack messages to browser
### Why?
they trigger fake HMR events and are not used on client side anyway
Closes PACK-2338
### 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
Reverts changes from #61173 & #60240 (while leaving the tests that were
added).
There are too many spots where considering `/default` routes as pages
needs to be carefully considered in different runtimes, and it turns out
that it's not actually needed to handle the case that it was originally
added for. I confirmed that the test that added the case it was intended
to fix (`parallel-routes-catchall-default`, along with the unit tests in
`normalize-catchall-routes`) are still passing as expected.
<!-- 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 #
-->
#61159 fixed the documentation by removing incorrect information stating
that the type parameter must be set to 'page' when the path contains a
dynamic segment. This PR reflects this change in the warning message,
while confirming that the condition for the warning is already correct.
Additionally, I changed the word "affect" to "effect," assuming it was a
typo. In the documentation, I corrected myself and changed the wording
from "argument is required" to "parameter is required".
### 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
This PR is refactoring only and doesn't change the logic, therefore no
tests were added.
The improvement here is readability:
- separate functions to fetch external vs internal image (in the future,
we could improve perf of internal image routing)
- types of the arguments are more specific (rather than passing in
complete NextConfig)
> Note: Its easier to review with whitespace hidden:
https://github.com/vercel/next.js/pull/61172/files?w=1
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
Context:
- on app router, we bundle all the code used both on server and client
- sentry used to be incompatible with that, however a raw require call
on production to Sentry leads to a 350ms impact on cold boots/initial
load
- it might be ok to bundle now, let's try it out
<!-- 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-2250
## 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
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
# 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?
`ANALYZE=1` is set in CI, but this shouldn't emit stats.
### Why?
It sometimes causes the `lint` step to fail as prettier checks these
stats files too
Closes PACK-2280
### 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
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>
The PR continues from #58038 aiming to reduce the installation size
further, and **improve performance in doing so**.
Most of `micromatch`'s APIs are essentially wrappers/alias of
`picomatch`, supplemented with additional features facilitated by a
transitive dependency `braces`. However, Next.js doesn't use those
"extra features". Switching from `micromatch` to `picomatch` can avoid
introducing the transitive dependency `braces`.
The PR also improves some globs' performance by hoisting.
- `micromatch.makeRe` is just an alias of `picomatch.makeRe`
-
90dc0cd3e1/index.js (L387C30-L387C30)
- `micromatch.isMatch(str, patterns, options)` equals
`picomatch(patterns, options)(str)`
-
90dc0cd3e1/index.js (L123)
- `micromatch.matcher` is just an alias of `picomatch`
-
90dc0cd3e1/index.js (L104C1-L104C40)
---------
Co-authored-by: Sam Ko <sam@vercel.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>
It seems that when tracing build dependencies our server tracing was
analyzing all server chunks un-necessarily and when a very large
dependency like `ace-builds` is creating large chunks it can slow down
builds drastically so this ensures we eagerly apply our shared ignores
to avoid this over tracing.
Build times before [with provided
repro](https://github.com/MartinXPN/next-slow-build-reproduction):
```sh
▲ Next.js 14.1.0
Creating an optimized production build ...
✓ Compiled successfully
✓ Linting and checking validity of types
✓ Collecting page data
✓ Generating static pages (5/5)
✓ Collecting build traces
✓ Finalizing page optimization
✨ Done in 437.29s.
```
Build times after [with provided
repro](https://github.com/MartinXPN/next-slow-build-reproduction):
```sh
▲ Next.js 14.1.1-canary.0
Creating an optimized production build ...
✓ Compiled successfully
✓ Linting and checking validity of types
✓ Collecting page data
✓ Generating static pages (5/5)
✓ Collecting build traces
✓ Finalizing page optimization
✨ Done in 42.38s.
```
Closes: https://github.com/vercel/next.js/issues/58759
Closes NEXT-2161
Issue: https://github.com/vercel/next.js/issues/60853
### What?
Added `@sentry/profiling-node` to the server-external-package object so
that sentry users who want to use this package don't have to manually
add this package in the experimental nextjs config entry.
### Why?
Package bundling will fail as shown in the following issue if not added
to this exclude list.
https://github.com/getsentry/profiling-node/issues/170
---
Fixes#60853
`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?
Add support for auto-importing `headers()` and `cookies()`
### Why?
Improve the auto-import experience in IDEs like VScode
### How?
Re-export the `next/headers` type references
Closes NEXT-2146
### What
Follow up for #59852 , now you can use `next/og` if your nextjs app is
marked as ESM with `"type": "module"` in package.json.
### How
It's a bug in external handling, we shouldn't ESM import error for local
requests. Previously you'll see the below error but the
og import shouldn't be errored as it's not external package
```
Module not found: ESM packages (/.../app/opengraph-image.js) need to be imported. Use 'import' to reference the package instead
https://nextjs.org/docs/messages/import-esm-externals
```
Closes NEXT-2147
### What?
Follow-up to #60579 and #60750. Checking `startsWith` is not enough
because it hides the rest of the stack. Changed the test to check the
snapshot for Turbopack and webpack.
Fixes a bug where the stack lines showed `http (NaN:NaN)` as the source
lines.
Added support for source lines that don't have a open in editor.
<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:
## For Contributors
### Improving Documentation
- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide
### Adding or Updating Examples
- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md
### Fixing a bug
- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md
### Adding a feature
- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md
## For Maintainers
- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change
### What?
### Why?
### How?
Closes NEXT-
Fixes #
-->
Closes NEXT-2128
### Fixed a Test Case
- Tests fixed:
`packages/next/src/build/normalize-catchall-routes.test.ts`, the
function call `normalizeCatchAllRoutes(appPaths)` was removed by
accident in this [merged commit
](efebba80a7 (diff-e3c0d3c6e15d8b035a3252a1ada2b04d5dd33010885fed8f6d689f75aa80bff5))
rendering the test case pointless
REF NEXT-1984
This PR stabilizes the previously introduced experimental config options
for providing a custom cache handler (for both ISR as well as the Data
Cache) and for disabling or configuring the in-memory cache size. The
example usage would be as follows:
```js
// next.config.js
module.exports = {
cacheHandler: require.resolve('./cache-handler.js'),
cacheMaxMemorySize: 0 // disable default in-memory caching
}
```
This PR also updates the documentation to better reflect how to use the
custom cache handler when self-hosting. Further information will be
added in a following PR that also includes a full example of a custom
cache handler that implements `revalidateTag` as well as passing in
custom cache tags. The API reference docs have been updated here, as
well as a version history added.
I also noticed that we currently have two duplicated versions of the ISR
docs in the Pages Router docs: both for rendering and for data fetching.
Data Fetching is the correct location for this page. There were no other
references to the rendering version in the docs, so that must have been
an accident. I'll need to a get a redirect going for that regardless.
Tests have been updated for `cacheHandler` and I added a new test for
`cacheMaxMemorySize`.
---------
Co-authored-by: Jiachi Liu <inbox@huozhi.im>
## What?
Skip postcss config resolving in node_modules for Turbopack. This
matches current Next.js on webpack closer as that only resolves the
postcss config from the project root. The additional feature Turbopack
has is that it can find a postcss config relative to the css being
compiled. This is useful for e.g. reducing the amount of overhead
certain postcss plugins that only have to run against a single file take
(i.e. Tailwindcss).
Depends on github.com/vercel/turbo/pull/7012 landing first.
<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:
## For Contributors
### Improving Documentation
- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide
### Adding or Updating Examples
- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md
### Fixing a bug
- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md
### Adding a feature
- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md
## For Maintainers
- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change
### What?
### Why?
### How?
Closes NEXT-
Fixes #
-->
Closes NEXT-2109
---------
Co-authored-by: Tobias Koppers <tobias.koppers@googlemail.com>
This reapplies the `experimental.missingSuspenseWithCSRBailout` option
to bail out during build if there was a missing suspense boundary when
using something that bails out to client side rendering (like
`useSearchParams()`). See #57642
Closes [NEXT-1770](https://linear.app/vercel/issue/NEXT-1770)
The following spans are either added or displayed by default:
* `NextNodeServer.findPageComponents` - page components
resolution/require
* `NextNodeServer.getLayoutOrPageModule` - load modules (webpack or
turbopack)
This would allow different apps to setup fetch instrumentation similar
to `@opentelemetry/instrumentation-http` and
`@opentelemetry/instrumentation-fetch` without duplicating fetch spans
and avoiding confusion with context propagation.
This ensures when a dependency has a recursive require our should ignore
handling doesn't accidentally loop back and forth.
x-ref: https://github.com/lovell/sharp/issues/3944
Closes NEXT-2121
As Barrel Optimization might split one file into multiple different
modules, i.e. when you import different values from it, the target file
might be transformed differently, we can no longer rely on the file path
as the identifier of the client reference.
This fix adds a suffix (`'@' + this._module.matchResource`) to the
identifier so it looks like
`/filepath/file.js@__barrel_optimize__?names=Foo`.
Here's also a quick diagram to explain:
![CleanShot-2024-01-16-QzlxzMKy@2x](https://github.com/vercel/next.js/assets/3676859/99f25975-b965-4ae0-91f2-269a6a0d7458)
Closes#59804.
Closes NEXT-2108.
---------
Co-authored-by: Jiachi Liu <inbox@huozhi.im>