This PR enables the `experimental.webpackBuildWorker` to be on by
default. This flag enables logic inside Next.js to run the compilation
in an isolated worker. The reason for this is that the webpack
compilation process retains a lot of memory for the whole duration of
the build process because it uses some packages that leak. We don't need
it for the rest of the process so it's best to use it in a worker and
leave the memory to be used for static generation.
This will improve memory usage during build, avoiding OOMs caused by
webpack exceeding memory.
<!-- 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 #
-->
---------
Co-authored-by: JJ Kasper <jj@jjsweb.site>
### What?
Changes Server Actions to use a lazy `require()` statement instead of a
lazy dynamic `import()`, to fix SA in the Edge runtime.
### Why?
The Edge runtime has a restriction that it's not allowed to lazy load
more files. The problem is that dynamic `import()` does exactly that, it
defers importing those files until the call time. `require()` doesn't
have this issue, because the chunks it would load are included instead
of deferred.
### How?
Just needed to modify the actions loader entry point… after hours of
trying to get the action loader to evaluate in the node runtime and then
import the actions in the edge runtime.
Closes WEB-1874
when calls to `maybePostpone` throw but there's no postpone state, we want to handle those errors differently so that we can provide clearer messaging around how to prevent them, while still retaining any errors that were re-thrown by the user.
ex:
![CleanShot 2023-10-25 at 16 05 56@2x](https://github.com/vercel/next.js/assets/1939140/d86cce9f-f9ed-477d-8d1c-0ce7c934d073)
Apply react-server condition and related API checks for pages API.
if you're doing react SSR with renderToString in middleware it should be disallowed. Imaging it could send the rendered html code to client and you display it in browser. But it might require hydration so it can be broken.
Follow up for #57448 , same reason explained in #57448
Closes NEXT-1653
### What?
We have to walk the directory tree recursively for every page (instead
of once) to get the correct loaderTree.
With this PR we walk the directory tree and for every
`page.(js,jsx,ts,tsx)` (entrypoint) we find we walk it again to get the
loader tree for that page
Closes WEB-1868
Closes WEB-1609
### What
Fixes how to determine if given route is dynamic to match next-dev does:
462b8585b6/packages/next/src/lib/metadata/get-metadata-route.ts (L79)
We were passing calculated route instead to check if it's dynamic, so
`/sitemap` always considered as static since calculated route is
`/sitemap.xml`.
Closes WEB-1864
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Apply `react-server` resolving and server components invalid APIs
checking to middleware. We want to limit the react usage in in
middleware as so far it's not aimed for rendering purpose.
Another invalid case could be: if you're doing react SSR with
`renderToString` in middleware it should be disallowed. Imaging it could
send the rendered html code to client and you display it in browser. But
it might require hydration so it can be broken.
This PR will only let you import `react-server` export condition
packages.
Do not log the removed experiments in the start server logs, for instance `experimental.appDir` should get warned as unexpected option but it's not the valid experiment anymore
## Story Time
Metadata API introduced two exports `metadata` and `generateMetadata` to the pages and layouts under app router, as partial prerendering work is going on and people are desiring to render the metadata asynchronizly, this change will be the preparation for moving to the dynamic & asynchronized land. In short, if we can render the metadata asynchronizedly, it will benefit the performance of the initial page loading and client page transiation a lot. Any slow data fetching can be handled while the essential page "shell" is rendered.
For meta tags, there're few ones will visually affect your web page, such as `<meta name="viewport">`, `<meta name="theme color">` and `<meta name="color-scheme">`, rendering them lately after the page frame is ready might bring flickering to the page such as revreting whole page's theme color or shaking due to viewport updates. Those meta are not majorly the "metadata" for SEO, but more for user experience when opening the page. If we're rendering everything as async meta tags, it won't be ideal due to the flickering on your web pages.
## Solution Preparation
We'll want to render the meta tags separately to make sure the visual ones are rendered as blocking along with web page, and then the ones for SEO or bots can be flushed later by later, like a suspense boundary keeps emitting them into the head of html.
We optionally picked up 3 meta tag "viewport", "theme-color" and "color-scheme" to be render first into the web page with html "shell", to guarantee the layout viewport and basic styling are rendered first.
This PR introduced two module export in the page and layout files: `viewport` and `generateViewport`, in order to separate the visual meta tags from the SEO metadata.
### API
```ts
// page.js | layout.js
export const viewport = {
// viewport meta tag
width: 'device-width',
initialScale: 1,
maximumScale: 1,
interactiveWidget: 'resizes-visual',
// visual meta tags
colorScheme: 'dark',
themeColor: { color: 'cyan', media: '(prefers-color-scheme: dark)' },
}
```
There's also a dynamic API like what we did for metadata API
```ts
// page.js | layout.js
export function generateViewport() {
return { ... }
}
```
## Notice
This PR won't get SEO metadata rendered asyncronizedly, instead it's a preparation for the later work in partial prerendering and async metadata. We'll encourage the Next.js community moving to the new metadata viewport API if you're customzing those 3 meta tags. Usually you don't have to change viewport itself, so mostly like only theme-color and color-scheme could relate to it.
Instead of `Readable.toWeb` we're gonna manually convert the Node.js stream to a Web stream. `toWeb` is either having a bug, or not compatible with middleware-cloned `PassThrough` streams.
Closes#56286. The case should be already covered with existing tests.
### What
Enabling test from https://github.com/vercel/next.js/pull/57300. There may be some other test cases passing by fix, but this is the known direct offending test can be enabled.
Closes WEB-1847
### What
minor fix to match behavior to ae10b5c82b/packages/next/src/shared/lib/router/utils/remove-trailing-slash.ts (L2C4-L9)
as we're seeing a panic when route is /
```
Panic: PanicInfo { payload: Any { .. }, message: Some(byte index 1 is out of bounds of ``), location: Location { file: "packages/next-swc/crates/next-core/src/next_edge/route_regex.rs", line: 202, col: 59 }, can_unwind: true, force_no_backtrace: false }
Backtrace: 0: backtrace::backtrace::libunwind::trace
```
Closes WEB-1841
This ensures when an error occurs during a revalidate in app router that
properly throw the error fully and don't store the error page in the
cache which matches the expected behavior for full route ISR as errors
are not meant to update the cache so that the last successful cache
entry can continue being served.
Fix was tested against the provided reproduction here
https://app-dir-example-ghl01cxtn-basement.vercel.app/
Fixes: https://github.com/vercel/next.js/issues/53195
This ensures we don't unexpectedly error when a fetch attempts to cache
inside of `unstable_cache`, this also ensures `only-on-store` doesn't
unexpectedly error when `revalidate: 0` is set.
This PR introduces a build optimization to create a "partial prerender" of the page.
1. During compilation, we create a static shell for the page using your existing Suspense boundaries. Components that can be static will be included in this static shell, leaving holes for the dynamic components.
1. Using `<Suspense />`, we can define fallbacks to be included in the partial prerender, as well as the holes for the dynamic components to stream into.
This means Next.js can initially serve a static loading skeleton, kicking off the dynamic parts in parallel. Then, the dynamic components stream in on demand. Dynamic components can use `cookies()`, `headers()`, `'cache': 'no-store'`, or `unstable_noStore()` to opt-into dynamic rendering.
Co-authored-by: Zack Tanner <1939140+ztanner@users.noreply.github.com>
This doesn't need to error, we can instead warn that the functionality will not work as expected out of the box. Support can be added for outside of Next for this to behave as expected.
These are supported when deployed via the Nextjs builder ([x-ref](https://github.com/vercel/vercel/blob/main/packages/next/src/index.ts#L851-L855)).
Update the revalidate handling to perform the revalidate option coalescing in the render function closer to the render result output. This helps reduce the amount of scope leak from the render.
We introduced a data fetching logging before, and the control option was under experimental. After a bit experiments turns out users really loves it. We decide to move it to a stable option.
### Changes
We're going to move the `logging` option outside of `experimental`, and scope the `fetches` related config under `logging.fetches`.
```js
// next.config.js
logging?: {
fetches?: {
fullUrl?: boolean
}
}
```
BREAKING CHANGE
Since `next export` has been printing a deprecation warning since https://github.com/vercel/next.js/pull/47376, its safe to remove in semver-major.
The upgrade path is to simply add `output: 'export'` in `next.config.js` - everything will continue to work the same.
This config greatly improves the `next dev` experience today. And in the future, it will improve performance of `next build` because we no longer need to do two passes (build then export).
### What?
* no need to clear require cache when assets where not used previously
* make build status reporting more consistent
* report build status to client side for build indicator
### Why?
### How?
Closes WEB-1826
### What?
- fixes test 17553c5e25/test/e2e/app-dir/metadata/metadata.test.ts (L487)
The way next.js collects static metadata is read static metadata, and then read layout metadata to merge multiple metadatas into a single layout path (17553c5e25/packages/next/src/lib/metadata/resolve-metadata.ts (L347-L352))
When turbopack creates LoaderTree for the corresponding directory tree, it extracts `page` but skips metadata in result there are orphan components that have a metadata doesn't have layout metadata, as well as a component have a layout doesn't have metadata. Latter is being rendered as a page (since it have correct layout), which eventually falls back to the default metadata instead.
PR trickles down the metadata when extracting page (creating a new component with `page`) to consolidates those.
Also PR expands Metadata to have base_page property to capture where it has been originally exists, as we clone down metadata then do `fillMetadataSegment` against the current page where LoaderTree is being created it creates a wrong relative path. For example, currently
```
/icon.svg
- opengragph/
- static -> path being `/opengraph/.../icon.svg` instead of `/icon.svg`
```
When recursively traverse directory tree, capture each components with corresponding base_page to calculate instead.
Unfortunately this doesn't make pass all of the metadata tests; there are lot to dig more. Would like to scope PR in a reasonable size.
Closes WEB-1795
This PR implements encryption and decryption for Server Action bound values that are from the closure level. Explicit `.bind` values, function arguments and module-level values are NOT handled.
### Compiler
The compiler now groups all closure bound values to an array which gets wrapped with `encrypt`. And then inside the action body, it prepends an expression to recreate the values via `await decrypt`.
Since closure-closed variables will only exist on the server layer, the encryption utility has `"server-only"` annotated.
### Encryption
During build time, a private AES-GCM encryption key is randomly generated and stored in the built server manifest. Before encrypting/decrypting, an extra round of Flight server and client will be used to serialize/deserialize the value.
When encrypting, a salt that contains the action ID is provided to prevent replay attack towards different API endpoints. The encryption key can be overridden via the `NEXT_SERVER_ACTIONS_ENCRYPTION_KEY` env variable so it can be built on multiple machines on scale.
A global singleton for storing the client reference manifest was made for Flight's serialization/deserialization as that might happen outside of rendering.
After encryption, we then serialize the ArrayBuffer as Base64 to send it to the client.
This PR fixes the passing of the `--inspect` option when calling Next.js with it. It's still not great because you need to target the next file in node_modules directly but I'll add a `next --inspect` option in the future.
This:
- Uses `isServer` to use the appropriate Turbopack `FileSystem` when
creating `FileSystemPath`s
- Properly uri decodes path segments originating from `file://` uris
- Correctly reads chunks starting at the project path instead of the
root path
Closes WEB-1815
---------
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
The asset context is a better place to store the layer, because it's
affected by transitions unlike the chunking context
This PR also removes a bunch of unused code
### Why?
See https://github.com/vercel/turbo/pull/6237 for the rationale
Also needs to wait for that PR to be merged
Closes NEXT-1814
#### Turbopack Changes
* https://github.com/vercel/turbo/pull/6237 <!-- Leah - chore: move
layer from chunking context to asset context -->
---------
Co-authored-by: Tobias Koppers <tobias.koppers@googlemail.com>
Remove the experimental `serverActions` flag
Co-authored-by: Shu Ding <3676859+shuding@users.noreply.github.com>
Co-authored-by: Jiachi Liu <4800338+huozhi@users.noreply.github.com>
### What?
`globalThis.ReadableStream` and `globalThis.WriteableStream` has been exposed since Node.js 18, which is our new default requirement. (#56943)
### Why?
This simplifies the code and might result in slightly better performance.
### How?
Drop any checks of `globalThis` properties that are always defined now.
Exposes the new experimental Taint APIs using the `taint` flag which
enables experimental React.
As an example for how we can use it, I use it to taint `process.env`
with a better error message. I'm not sure where this should live since
it's a global init but it needs access to the global config. It's
unnecessary to retaint it for every render but not sure if there's a
better place for it.
---------
Co-authored-by: Jimmy Lai <laijimmy0@gmail.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This PR adds a resolver plugin to verify during bundling that when a module is unresolved, that it is not an optional peer dependency specified in the package.json of the caller. An error would happen if you try to bundle packages like `typeorm` since there are `require` calls in the code to those dependencies.
Also, swallow dynamic dependencies warnings in `require` calls error if they come from `node_modules`. They are not actionable at all generally.
We already had `domains` as "not recommended" but this PR marks it as "deprecated" and prints a warning if its detected.
I also updated all examples to switch from `domains` to `remotePatterns`.
### What?
Note: This is not a breaking change, just removing some unused code.
### Why?
Since #56896 we don't need this, as Node.js 18+ has `fetch` exposed by default.
### How?
Depends on #56896, #56909
We already didn't load `fetch` if `globalThis` had it (ie. Node.js 18+ environments), and since we are dropping support for Node.js 16, these code paths should have no effect on runtime behavior.
### Story
Since we introduced `ImageResponse` into `next/server` export, there're a few libraries relying on `next/server` that accidentally ended up with bundling og image into the bundle. As og package is quite large that could easily raise the size concern for middleware, edge runtime routes.
### Struggles
We've done optimizations. The tree-shaking strategies are tricky, we tried modularize imports and also optimize cjs require/exports to make sure you're not including og package into bundle if it's not being used. However, it's still not 100% can handle all the bundle optimization cases, such as `import {..} from "next/server.js"` could also ended up with the cjs bundle that failed the tree-shaking.
### Move on
So we decide to move og `ImageResponse` into a separate export `next/og`
Closes NEXT-1660
This avoids testing against latest exact canary version as this causes these tests to fail while the publish is still in progress. As a follow-up we can investigate moving this post publish or packing/deploying tarballs to use.
Co-authored-by: Steven <229881+styfle@users.noreply.github.com>
This PR adds the optional `limit` parameter on String.prototype.split uses.
> If provided, splits the string at each occurrence of the specified separator, but stops when limit entries have been placed in the array. Any leftover text is not included in the array at all.
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split#syntax)
While the performance gain may not be significant for small texts, it can be huge for large ones.
I made a benchmark on the following repository : https://github.com/Yovach/benchmark-nodejs
On my machine, I get the following results:
`node index.js`
> normal 1: 570.092ms
> normal 50: 2.284s
> normal 100: 3.543s
`node index-optimized.js`
> optmized 1: 644.301ms
> optmized 50: 929.39ms
> optmized 100: 1.020s
The "benchmarks" numbers are :
- "lorem-1" file contains 1 paragraph of "lorem ipsum"
- "lorem-50" file contains 50 paragraphes of "lorem ipsum"
- "lorem-100" file contains 100 paragraphes of "lorem ipsum"
This updates some code related to web streams and encoding.
- Removes some unused code related to base64 encoding/decoding (Edge runtime currently supports it natively via `Buffer`)
- Prefer readable stream `pull` versus `.on("data", (chunk) => { ... })` event handlers (simplifies execution)
- Utilize `pipeTo` and `pipeThrough` on web streams to remove custom code related to stream pumping
- Updates pipe readable function to utilize web streams first class rather than relying on manual pumping + stream management
- This also takes advantage of the `AbortController` when piping so that the response can use it to cancel the stream
We currently log when a worker is restarted but not when we send the kill signal, which can create a delta in logs of cryptic errors while the worker is exiting. This explicitly logs when we're terminating the static worker prior to a restart, and also adds an optional logger fn so that we pretty-print the messages.
[slack x-ref](https://vercel.slack.com/archives/C061DJBG8PN/p1697491350970269)
## History
We used to pass `onLoad` through directly to the underlying img so `onLoadingComplete` was introduced in order to handle the case when `placeholder="blur"` was used and `onLoad` would trigger before the placeholder was removed.
We have since changed the behavior of `onLoad` so that it acts the same as `onLoadingComplete` and therefore `onLoadingComplete` is no longer needed.
## What is this PR doing?
This PR marks `onLoadingComplete` as deprecated in favor of `onLoad`. In the future, we may remove `onLoadingComplete`.
I think some of the runners are missing `yarn` globally installed so its attempting to install with corepack. But the default behavior of corepack is to use the repo version (pnpm in this case) so running `yarn` will error. This PR disables corepack strict mode to avoid that problem.
This PR introduces a new API, `unstable_noStore`, which will allow users to declaratively opt out of caching anywhere during static generation in the same way that you can specify `cache: 'no-store'` on a fetch call in Next.js.
An important caveat and difference from just calling `cookies()` to opt-out of static generation is that this won't opt you out when called from within `unstable_cache` and instead defers to the cache configuration to it.
```
import {unstable_noStore as noStore} from 'next/cache';
export default async function Component() {
noStore();
const result = await db.query(...);
}
```
<!-- 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 #
-->
This PR therefore introduces to always set response status code to 500
unless it is a `NotFoundError` or `RedirectError`. This PR would fix
issue #56235. See also:
https://codesandbox.io/p/sandbox/nice-panini-2z3mcp .
**Current Behavior**
At the moment, when an unexpected error occurs during app server
rendering, a 200 ok is returned as status code. This seems to be
undesirable because of the success status CDNs will cache the error
pages and crawlers will index the page considering the error content as
the actual content.
**Desired Behavior**
This issue is related to discussion
https://github.com/vercel/next.js/discussions/53225. Even though I
understand that the response status code cannot be set if streaming has
started, in my view it would be best to set the response status to 500
whenever it can (so before the streaming has started) for SEO and (CDN)
http caching. This would also be consistent with how 404s currently
work; that is, response status code is set to 404 if `NotFoundError`
occurred before streaming (related
[issue](https://github.com/vercel/next.js/issues/43831) &
[PR](https://github.com/vercel/next.js/pull/55542)).
Ideally, when a runtime error happens after streaming, a `<meta
name="robots" content="noindex" />` would also be added. But I didn't
want to make the PR too complex before receiving feedback.
---------
Co-authored-by: Vũ Văn Dũng <me@joulev.dev>
Co-authored-by: Tobias Koppers <tobias.koppers@googlemail.com>
### What?
Update Babel packages across the board
### Why?
Since you ship vendored presets and plugins it's impossible for people to update this stuff at their own pace - independently from Next. So users of `next/babel` are currently stuck with old versions and, for example, they might not be able to use the TS `satisfies` operator.
### How?
I just updated ranges (to pinned ones) where I could find them, run `corepack pnpm i` and re-run build scripts in the `packages/next`.
Fixes#43799
### What?
BREAKING CHANGE: Bump the minimum required Node.js version.
### Why?
Node.js 16 has reached end-of-life in September.
Bumped to `18.18.2` since it contained some security-related patches: https://nodejs.org/en/blog/vulnerability/october-2023-security-releases
### How?
Bumped `engines` where needed, upgraded the workflows.
This will allow us to remove quite a few polyfills, I'll open separate PRs for those.
Looked for `webpack(config` in the test suites and disabled the ones that are testing webpack specifically. There are a few more that are not skipped as they should be implemented for Turbopack.
Closes WEB-1702
This PR implements initial support for the `next/dynamic` in Turbopack,
more specifically resolving some hydration errors and other components
boot up cases.
Previously, turbopack had partial next/dynamic support via its own mode
(https://github.com/vercel/next.js/pull/56389/files#diff-e1af4f79cb88a73f819a25443d15ed4b1ffabcbb879256caa59b751fad46d7c4L68),
which does a transform against `next/dynamic` wrapped import to embed
dynamically resolvable chunk ids like
(ad42b610c2/packages/next-swc/crates/next-transform-dynamic/tests/fixture/wrapped-import/output-turbo-dev-server.js).
However, since next.js relies on static path to the chunks to the
dynamic import and passing those ids in between client-server to ensure
component load (and avoid hydration errors), it doesn't work out of the
box. This PR changes turbopack's behavior to closely mimic what current
next.js's webpack plugin does, by
1. Traverse the module graph, find out `dynamic(import())`
2. Generate chunks for those imports, creates a partial LoadableManifest
per each imports
3. Merge partial manifest into a single `react-loadable-manifest.json`
4. For the id, use static (Webpack mode) instead of dynamic so we can
embed it in `react-loadable-manifest` as well as next.js can use it to
pass it between server-client context.
I left a small comment to the implementation
(https://github.com/vercel/next.js/pull/56389/files#diff-bf12ed2c69d0bc89a06884779da4ae44967eb8becada031dea12bedef28e2622R155)
for the lifecycle of this feature in case to fix further.
This makes to pass most of the basic next-dynamic related integration
tests, except if the import have webpack specific features like
ad42b610c2/test/development/basic/next-dynamic/pages/dynamic/multiple-modules.js (L5).
---------
Co-authored-by: Tim Neutkens <tim@timneutkens.nl>
Since Turbopack doesn't use eval-source-map the CSP nonce will pass correctly, nice improvement over the current state where you can't check CSP in dev.
Fixes a bunch of the Turbopack test failures for `test/e2e/app-dir/app/index.test.ts`. Not sure how this passed with webpack before as the dep was indeed missing.
### What?
Adding back `x-forwarded-*` headers.
### Why?
Starting with #52492, these headers were lost.
### How?
We can populate these headers before executing a request.
Closes NEXT-1663
Fixes#55942
`useParams` is not referentially equal between renders which can lead to unexpected behavior when used as a dep.
This memoizes the response from `useParams` similar to `useSearchParams`.
[slack x-ref](https://vercel.slack.com/archives/C04DUD7EB1B/p1697145987740229)
This change is to pick the esm assets for RSC server layer and server rendering side, this is for production and development perf purpose, also to let them apply with the ESM related optimization such as tree-shaking, barrel files optimizations, etc.
We found a few packages that can't be optimized easily in bundling because we're using "main" field so the packages are not able to be tree-shaked, ending up with large bundle in the dist. This will change a lot for the bundling improvements as some packages are only having "main" and "module" field. So switching from CJS to ESM means better bundling, more optimization, and faster code.
#56501 was a precondition for this, as previously the bundling strategy was applied to some library but triggered the invalid hooks erroring.
### Other Monior Change
Previously we'll prefer to resolve CJS as there're 2 versions of react, using CJS assets will help let them pass by require-hook to use canary react for app router bundling assets. But now we changed the approach to bundling nextjs runtime and react packages. Now we dropped the condition that prefered to resolve CJS exports for externals, since if you're putting them in `serverComponentsExternalPackages`, they're not using the built-in react, so could potentially having trouble if any dependency is using react but excluded in bundles. So far we didn't see any report to this.
Closes NEXT-1286
In [55841](https://github.com/vercel/next.js/pull/55841), this file was reworked to improve type safety and readability, but it changed the behavior of how we were invoking methods on the worker. Specifically, when a restart occurred, this timeout wrapping function was referencing an already ended worker, resulting in a "Farm is ended, no more calls can be done to it" build error.
This PR ensures that we're fetching the method from the current `this._worker` at the time of invocation, not at the time of method creation.
[Slack x-ref](https://vercel.slack.com/archives/C04KC8A53T7/p1697064752635179?thread_ts=1696952142.759769&cid=C04KC8A53T7)
### What?
instead of include known passing tests
also updates the update test manifest
### Why?
Newly added test cases should always pass turbopack (or at least you would need to manually opt-out of it.
### How?
Uses a exclude list of tests instead of an allow list
Closes WEB-1752
<!-- 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 #
-->
this is a follow-up to #48018 (don't add `isolatedModules: true` to
`tsconfig.json` when `verbatimModuleSyntax: true` is set), which also
handles the case where `verbatimModuleSyntax: true` is set in a base
tsconfig which is being referenced via `tsconfig#extends`.
---------
Co-authored-by: Zack Tanner <zacktanner@gmail.com>
This applies the predefined list of packages in server-external-packages.json as always external when used by app router in Turbopack
Test Plan: Added integration tests
Closes WEB-1709
This adds a test that asserts that, without additional configuration like `experimental.bundlePagesExternals`, Next.js does not bundle `node_modules` for pages.
Closes WEB-1708
This PR flattens the recursive optimization logic of our barrel optimization loader. So now if there're any recursive `export * from ...`, they won't be created as multiple individual Webpack modules, but optimized in one module.
With this change, we are running SWC transform to get the export map directly inside the barrel loader (instead of a separate loader rule). And that map is recursively calculated and cached in memory.
I also published https://unpkg.com/browse/recursive-barrel@1.0.0/ to give this a test. It contains 4 levels of 10 `export *` expressions, which is 10,000 modules in total. Without this change, it takes ~30s to compile and with this change, it goes down to ~7s.
When we landed #51179 it broke library like `apollo-client` as it's bundling client hooks into RSC bundle, so our RSC linter caught them and reported fatal errors. But those client hook APIs won't get executed in RSC. The original purpose of erroring on invalid hooks for server & client components was to catch bugs easier, but it might be too strict for the 3rd party libraries like `apollo-client` due to few reasons.
We changed the rules only applying on user land source code. For 3rd party packages if they're not being imported correctly into proper server or client components, we're still showing runtime errors instead of fatal build errors.
x-ref: https://github.com/apollographql/apollo-client/issues/10974
Closes NEXT-1673
The PR supersedes the https://github.com/vercel/next.js/pull/53150, which is way too outdated, has way too many conflicts, and also heavily relies on GitHub Copilot (which makes the progress slow and tedious).
The PR uses [`json-schema-to-zod`](https://github.com/StefanTerdell/json-schema-to-zod) (instead of the GitHub Copilot) to generate the zod schema, and manually replaces all generated `z.customRefine` with my hand-written zod schema.
TODO:
- [x] Convert schema
- [x] Reduce `z.any()` usage
- [x] Create human-readable errors from the `ZodError`
- [x] Update test cases to reflect the latest error message
-----
The benefit of using zod over ajv:
- Easier maintenance: zod schema is straightforward to compose.
- Better typescript support: config schema now strictly reflects the `NextConfig` type.
- Smaller installation size: by replacing `ajv` and `@segment/ajv-human-errors` w/ `zod`, I am able to reduce installation size by 114 KiB.
- Better Extension: the zod error message is easy to customize.
-----
In the previous PR https://github.com/vercel/next.js/pull/56083, @feedthejim replaces `zod` w/ `superstruct`. `superstruct` is lightweight and fast, which makes it perfect for creating simple schemas for RSC payload. But, this also means `superstruct` has its limitations compared to `zod`:
- `superstruct`'s syntax is different, and some utilities's usage is counter-intuitive:
- `z.array(z.string()).gt(1)` vs `s.size(s.array(s.string()), 1)`
- `z.numer().gt(1)` vs `s.size(s.number(), 1)`, `s.min(s.number(), 1)`
- `z.boolean().optional().nullable()` vs `s.nullable(s.optional(z.boolean()))`
- `superstruct` has weaker TypeScript support and worse DX compared to `zod` when composing huge schema:
- `zod.ZodType + z.object()` can provide a more detailed type mismatch message on which specific property is the culprit, while `Describe + s.object()` provides almost no information at all.
- `zod`'s schema is more powerful
- `z.function()` supports `z.args()` and `z.returns()`, while `superstruct` only has `s.func()`
- zod also has Promise type `z.promise()` and intersection type `z.and()`
- `superstruct`'s error is harder to parse compared to `zod`'s `ZodError`
So in the PR, I re-introduced `zod` for `next.config.js` validation.
### What?
This implements Server Actions inside the new Turbopack next-api bundles.
### How?
Server Actions requires:
1. A `.next/server/server-reference-manifest.json` manifest describing what loader module to import to invoke a server action
2. A "loader" entry point that then imports server actions from our internal chunk items
3. Importing the bundled `react-experimental` module instead of regular `react`
4. A little 🪄 pixie dust
5. A small change in the magic comment generated in modules that export server actions
I had to change the magic `__next_internal_action_entry_do_not_use__` comment generated by the server actions transformer. When I traverse the module graph to find all exported actions _after chunking_ has been performed, we no longer have access to the original file name needed to generate the server action's id hash. Adding the filename to comment allows me to recover this without overcomplicating our output pipeline.
Closes WEB-1279
Depends on https://github.com/vercel/turbo/pull/5705
Co-authored-by: Tim Neutkens <6324199+timneutkens@users.noreply.github.com>
Co-authored-by: Jiachi Liu <4800338+huozhi@users.noreply.github.com>
There should be no shared react packages in our server runtime. rsc should always be separate from ssr.
This update reconfigures the runtiem to eliminate shared react modules. the jsx runtime will now be separate for RSC and SSR. this is necessary because the implementations for the jsx runtime rely on React and they need to see the right versions.
Additionally I fixed an alias so that the shared subset react is used when using react-server condition.
I also fixed a bug in 2 tests related to class/className.
Note: this PR blocks upgrading React canary due to internal changes in how React state is managed in when using the `react-server` condition
When the function name is omitted webpack generates a name from the loader config which can be really long un-necessarily. Providing a name for the default function alleviates this. cc @shuding who found this
Today when we hydrate an SSR'd RSC response on the client we encounter import chunks which initiate code loading for client components. However we only start fetching these chunks after hydration has begun which is necessarily after the initial chunks for the entrypoint have loaded.
React has upstream changes that need to land which will preinitialize the rendered chunks for all client components used during the SSR pass. This will cause a `<script async="" src... />` tag to be emitted in the head for each chunk we need to load during hydration which allows the browser to start fetching these resources even before the entrypoint has started to execute.
Additionally the implementation for webpack and turbopack is different enough that there will be a new `react-server-dom-turbopack` package in the React repo which should be used when using Turbopack with Next.
This PR also removes a number of patches to React src that proxy loading (`__next_chunk_load__`) and bundler requires (`__next_require__`) through the `globalThis` object. Now the react packages can be fully responsible for implementing chunk loading and all Next needs to do is supply the necessary information such as chunk prefix and crossOrigin attributes necessary for this loading. This information is produced as part of the client-manifest by either a Webpack plugin or Turbopack.
Additionally any modifications to the chunk filename that were previously done at runtime need to be made in the manifest itself now. This means we need to encode the deployment id for skew protection and encode the filename to make it match our static path matching (and resolutions on s3) when using `[` and `]` segment characters.
There are a few followup items to consider in later PRs
1. we currently bundle a node and edge version of react-server-dom-webpack/client. The node version has an implementation for busboy whereas the edge version does not. Next is currently configured to use busboy when handling a fetch action sent as multipart with a node runtime. Ideally we'd only bundle the one platform we are buliding for but some additional refactoring to support better forking is possibly required here
This PR also updates react from 09285d5a7 to d900fadbf.
### React upstream changes
- https://github.com/facebook/react/pull/27439
- https://github.com/facebook/react/pull/26763
- https://github.com/facebook/react/pull/27434
- https://github.com/facebook/react/pull/27433
- https://github.com/facebook/react/pull/27424
- https://github.com/facebook/react/pull/27428
- https://github.com/facebook/react/pull/27427
- https://github.com/facebook/react/pull/27315
- https://github.com/facebook/react/pull/27314
- https://github.com/facebook/react/pull/27400
- https://github.com/facebook/react/pull/27421
- https://github.com/facebook/react/pull/27419
- https://github.com/facebook/react/pull/27418
### What?
Deduplicates our env var injection between the JS and rust side
Closes WEB-937
---------
Co-authored-by: Tim Neutkens <tim@timneutkens.nl>
Co-authored-by: Zack Tanner <zacktanner@gmail.com>
### What?
Fixes the pages router not receiving a hash when being linked from the
app router.
### Why?
The hash being removed breaks sites that rely on it for client side
features.
### How?
The hash gets omitted from the URL when used as a key for the
preflightCache. Once it's clear that it's an external URL and that it's
not empty we can use the initial href to send the hash as well.
Not completely sure if there's an edge case that might break, I added an
extra check for when the hash is only used to scroll the page.
This might need an additional test case just for
`navigate-reducer.test.tsx`.
Fixes#56212
---------
Co-authored-by: Zack Tanner <zacktanner@gmail.com>
Co-authored-by: JJ Kasper <jj@jjsweb.site>
Fixes#53190.
Next.js App Router comprises two categories of resources, same-origin ones (RSC payload, in the form of inline `<script />`) and possibly third-party ones (chunks that respect the `assetPrefix`). The latter should also respect the `crossOrigin` option from `next.config.js`.
Co-authored-by: Jiachi Liu <4800338+huozhi@users.noreply.github.com>
Reland #54403
Also modifies the implementation of #55950 to not change the prefetch behavior when there is flight router state - we should only check the entire loader tree in the static prefetch case, otherwise we're inadvertently rendering the component tree for prefetches that match the current flight router state segment. ([slack x-ref](https://vercel.slack.com/archives/C03S8ED1DKM/p1695862974745849))
This includes a few other misc fixes for static prefetch generation:
- `next start` was not serving them (which also meant tests weren't catching a few small bugs)
- the router cache key casing can differ between build and runtime, resulting in a bad cache lookup which results suspending indefinitely during navigation
- We cannot generate static prefetches for pages that opt into `searchParams`, as the prefetch response won't have the right cache key in the RSC payload
- Layouts that use headers/cookies shouldn't use a static prefetch because it can result in unexpected behavior (ie, being redirected to a login page, if the prefetch contains redirect logic for unauthed users)
Closes NEXT-1665
Closes NEXT-1643
Skips additional production-only tests.
Follow-up to #56089.
In this PR I went through all of `test/integration` looking for `nextBuild(` and added the skipping logic.
### What?
clear require cache only when there has been changes
Before we cleared the require.cache after every ensurePage call. This is
too much. The new approach compares the hashes of all emitted files with
the previous hashes and only clears require.cache when they differ.
### Why?
reloading a page and client navigation is slow due the re-requiring
server files
Closes WEB-1686
This ensures we properly set the `isReady` flag when building with `experimental-compile` and enables our main app dir test suite to ensure we don't regress on it.
This test failed for Turbopack because of the rename from `i18n` to `__i18n` to not use that config. Turbopack does checking of config options to ensure it doesn't run when an option is not implemented, so that caused the test run to bail out.
Disable server components and server actions SWC transform when it's running jest. You can only do basic DOM testing like what we described in #54891 instead the server action itself.
Closes#53065
Closes NEXT-1473