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
This PR adds an option to forcefully bundle node_modules packages in `pages` on the server. This should benefit cold boots for projects that uses pages, at the cost of build time increase.
This consolidates our trace handling between turbotrace and the default
`nodeFileTrace` handling to prevent over-tracing. With node-file-trace
it's extremely more efficient to trace in a single `nodeFileTrace` run
so that all resolving/analysis etc can be efficiently cached.
Furthermore, this reduces the amount of chunks we need to trace by
waiting until post build since automatically statically optimized paths
don't need to be traced as they are rendered to purely HTML and never
re-rendered.
This reduces builds times by upwards of 4 - 5 minutes on larger
projects.
Investigating problems this is causing where incorrect flight data is being generated (potentially not correctly bailing on non-static data) causing navigation issues.
Reverts #54403
### Why?
`permanentRedirect` currently still returns a 307 response if called inside a route handler
<img width="465" alt="image" src="https://github.com/vercel/next.js/assets/44609036/e0cddd37-0292-4865-a423-7bf11ad6beae">
This PR tries to fix that.
### How?
Make `handleTemporaryRedirectResponse` (now renamed `handleRedirectResponse`) accept a status value, then `getRedirectStatusCodeFromError` is used to retrieve that status (307 or 308).
### What?
fixes
```
[Error: Invalid segment components, catch all segment must be the last segment
Debug info:
- Execution of directory_tree_to_entrypoints_internal failed
- Invalid segment components, catch all segment must be the last segment] {
code: 'GenericFailure'
}
```
Closes WEB-1668
Re-export the original route segment config in metadata routes loader, so they can be picked up by app route module wrapper
Closes#54057
Closes NEXT-1645
The barrel optimization loader creates a virtual module to re-export
from the original file, which causes the situation that now there are 2
modules with the same resource but only one of them is the actual code.
When the code contains `"use client"`, the Flight plugin has to collect
its `buildInfo` and generate the manifest and client entry module.
However, we currently deduplicate module by resource in the traversal
logic to avoid unnecessary loops. To make it work together with the
virtual barrel module, we'll need to prefix the resource path to make it
different from the original module.
Closes#54967.
Closes#55609.
Closes#55566.
This PR implements progressive enhancement for `useFormState`:
1. Inline the form state in `__next_f` and use it for hydration.
2. Encode the new form state based on the action return value, and pass
it to Flight/Fizz.
Also fixed a problem caused by inconsistent React tree structure between
static-generation and non-static-generation.
### What?
A follow up to https://github.com/vercel/next.js/pull/55975, this will
list every flakey test in the turbopack suite so that we can run the
remaining passing tests.
### Why?
More tests is more better.
### How?
Trial and error. Gonna let CI tell me what's flakey with a few runs.
Closes WEB-1651
Inferring the protocol from the request meta is not reliable when the next server is running over `http` but sitting behind an https proxy. This instead plumbs the experimental https flag through to the optimizer so we can more reliably determine the protocol
Fixes#55971
### What?
This PR fixes import source for turbopack's compiler.emotion config, mimics the current webpack configuration behavior.
Unfortunately this does not fixes the whole emotion transform with appdir yet, it looks like there are additional problems with server components.
Closes WEB-1655
This ensures we don't block sending the stream down when handling stale revalidates, in edge runtime we leverage the existing `waitUntil` handling and in node.js runtime we couple this into our pipe readable handling to wait to close the writable until after the promise resolves.
x-ref: https://github.com/vercel/next.js/issues/54193
Noticed a couple of directories had unit tests in `dist` which are being
run and reported during the Turbopack runs. These are generally quite
small so I'm not expecting this to have much effect on the package size
or CI runs, just making sure the data is correct.
<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:
## For Contributors
### Improving Documentation
- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide
### Adding or Updating Examples
- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md
### Fixing a bug
- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md
### Adding a feature
- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md
## For Maintainers
- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change
### What?
### Why?
### How?
Closes NEXT-
Fixes #
-->
### What
#51394 introduced a pretty strict type of return value of route type
that causing failure with `next build`.
There're few ways of writing a app route, it could contain few return
values based on the usage:
* return a `Response` or promise of it
* return `NextResponse` of promise of it, since it's extended from
`Response`, same type
* use `redirect()` or `notFound(), since it returns `never`, and the
below code is not reached, the handler itself could still return void.
e.g. using `redirect` in a `GET` route
We loosed the type so `redirect()` can be still allowed without
specifying the return value there.
Related typescript issue:
https://github.com/microsoft/TypeScript/issues/16608#issuecomment-309327984
### How
* Re-enable the bail on types / build error in the app-routes tests
* Separate the tests, move runtime erroring ones to
`test/e2e/app-dir/app-routes-errors`
* Add new case to app-routes tests of mixed return value
Closes#55623
Related #55604
This fixes some scenarios where executing a server action after navigation can cause the action to behave incorrectly (double submitting, not resolving). There are two separate issues:
- `canonicalUrl` and `pendingNavigatePath` were not constructed using the same function (`createHrefFromUrl`) so in certain situations they'd be comparing different values
- a fulfilled inFlightServerAction should not be invoked again
Closes NEXT-1655
Closes NEXT-1654
Fixes#55845Fixes#55814Fixes#55805
### What?
Updates `run-test.js` to allow running individual test cases inside a test file.
### Why?
So that we can dramatically increase Turbopack's test coverage. Turbopack has implemented most (but not all) necessary features from the webpack bundles. But a single failing test case would prevent us from running any case inside a test file. With case filtering, we're able to run the cases we know will pass and prevent regressions on those.
### How?
Case filtering is only exposed via the `NEXT_EXTERNAL_TESTS_FILTERS` ENV, which points to a JSON file containing a map of test files with the test cases inside those files that are known to pass.
The known-passing test cases can be updated after Turbopack's daily integration test run by running `test/build-turbopack-tests-manifest.js`, which will update the `test/turbopack-tests-manifest.json` manifest.
Closes WEB-1640
Co-authored-by: Tobias Koppers <1365881+sokra@users.noreply.github.com>
### What?
This PR enables basic support for next.config.js's `distDir` config. PR have two main pieces, one for honoring distDir and construct output path other than `.next`, and secondly assign `process.env.__NEXT_DIST_DIR` to client / edge. The latter increased size of PR bit as had to downstream to the compile_define calls.
Corresponding tests are enabled to verify its behavior.
Closes WEB-1610
The IPC request to `imageOptimizer` assumed the server was listening on http, so this updates it to pull the protocol from `getRequestMeta` instead. This also adds the option to pass in a path to the CA Root so that the dev server can add it to `NODE_EXTRA_CA_CERTS`
Closes NEXT-1646
Fixes#55706
### What?
Minor improvement to test fixture to clean up the instance if explicitly specified to continue test. This is required to run turbopack related tests.
Closes WEB-1634
### What?
In some test failures we've been observing test result is not written at
all like
```
Failed to load test output [Error: ENOENT: no such file or directory, open 'test/e2e/app-dir/edge-runtime-node-compatibility/edge-runtime-node-compatibility.test.ts.results.json'] {
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: 'test/e2e/app-dir/edge-runtime-node-compatibility/edge-runtime-node-compatibility.test.ts.results.json'
}
```
scrolling up, it was due to whole test process was taken down by calling
process.exit explicitly.
We want to collect test results for the failures still, so the PR amends
it for the cases if it's specified to continue on error.
Closes WEB-1628
## Why?
Although the left padding makes the output looks good in the terminal, it causes this weird alignment in almost all bug reports:
```yaml
Operating System:
Platform: win32
Arch: x64
Version: Windows 10 Pro
Binaries:
Node: 18.12.0
npm: N/A
Yarn: N/A
pnpm: N/A
Relevant Packages:
next: 13.5.2-canary.2
eslint-config-next: 13.5.2
react: 18.2.0
react-dom: 18.2.0
typescript: 5.2.2
Next.js Config:
output: N/A
```
If I want it to look nice in the bug report
```yaml
Operating System:
Platform: darwin
Arch: arm64
Version: Darwin Kernel Version 23.0.0: Thu Aug 17 21:23:02 PDT 2023; root:xnu-10002.1.11~3/RELEASE_ARM64_T8112
Binaries:
Node: 20.3.1
npm: 9.6.7
Yarn: 1.22.19
pnpm: 8.6.12
Relevant Packages:
next: 13.5.2
eslint-config-next: N/A
react: 18.2.0
react-dom: 18.2.0
typescript: 5.2.2
Next.js Config:
output: N/A
```
I have to paste this to a text editor and manually remove the first four spaces on every lines.
### How?
This PR removes that four-space padding to make future bug reports look a bit nicer.
### What?
Closes WEB-1615
I thought I couldn't grab the correct count of test suite in the datadog
as I was seeing huge count mismatches. Actually, it was because we were
not running all of the tests.
PR amends
- run all the tests under manifests
- ensure all the test list in the manifest actually exists
lastly and sadly
- disable few tests too flaky
In order to support updates to the prerendering pipelines, this breaks out some of the prerendering
code into discrete chunks importable for each route kind rather than them all sharing the same
function.
Some small optimizations were made, namely some matcher memoization (only the last one) that should
help with large builds locally.
When errors are thrown in middleware it could re-send headers for the same response
```
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at __node_internal_captureLargerStackTrace (node:internal/errors:490:5)
at new NodeError (node:internal/errors:399:5)
at ServerResponse.setHeader (node:_http_outgoing:645:11)
at origSetHeader (/next.js/packages/next/src/server/base-server.ts:777:16)
at ServerResponse._res.setHeader (/next.js/packages/next/src/server/base-s
erver.ts:777:16)
at setHeader (/next.js/packages/next/src/server/base-http/node.ts:84:15)
at renderErrorImpl (/next.js/packages/next/src/server/base-server.ts:2790:
11)
at <anonymous> (/next.js/packages/next/src/server/base-server.ts:2777:19)
at trace (/next.js/packages/next/src/server/lib/trace/tracer.ts:213:14)
at DevServer.renderError (/next.js/packages/next/src/server/base-server.ts
:2776:24)
at DevServer.renderError (/next.js/packages/next/src/server/next-server.ts
:1299:18)
at DevServer.handleRequestImpl (/next.js/packages/next/src/server/base-ser
ver.ts:1185:23) {
code: 'ERR_HTTP_HEADERS_SENT'
}
```
Migrate middleware-errors test to e2e test to avoid flaky assertion due to duplicated logging collected in integration test.
Closes NEXT-1629
`isAppLayer` condition was missing `app-metadata-route` layer, made it
as a util now like other webpack layer utils, add metadata route layer
to the group. Then `React.cache` can be available there.
Also update regex to be compatible across platform
Fixes#55561
Closes NEXT-1635
This consolidates how we're evaluating when to opt into `react@experimental` since it's sprinkled in a lot of spots. Also adds a new flag to opt into the experimental channel
Closes NEXT-1632
We need to disable the default treat `middleware` and `pages/api` as
server-only, unless users explictly import "server-only" to poison it.
This will avoid the case that when a library is mixing "client-only" API
and shared components API in one bundle, and the shared API is used in
middleware or `pages/api` that might cause error. See the test case
added.
Follow up for #55394
### `useSearchParams`
server router's query includes both search params and path params, this PR eliminate the path params from `useSearchParams` to make it aligned between app router and pages router
### `useParams`
For pages, we extract the params keys with `getRouteRegex`, and pick them out from `router.query`
Fixes#54242
Closes NEXT-1536
Users want to use `server-only` to restrict the middleware / app routes / pages api, but now it's failing as we're treating them as different webpack layers, but validating the `server-only` only with server components layers.
Here we modify the rules a bit to let everyone can use "server-only" for the bundles that targeting server-side.
For next-swc transformer, we introduce the new option `bundleType` which only has `"server" | "client" | "default"` 3 values:
* - `server` for server-side targets, like server components, app routes, pages api, middleware
* - `client` for client components targets such as client components app pages, or page routes under pages directory.
* - `default` for environment like jest, we don't validate module graph with swc, replaced the `disable_checks` introduced [#54891](https://github.com/vercel/next.js/pull/54891).
Refactor a bit webpack-config to adapt to the new rules, after that `server-only` will be able to used in the server-side targets conventions like middleware and `pages/api`
Fixes#43700Fixes#54549Fixes#52833
Closes NEXT-1616
Closes NEXT-1607
Closes NEXT-1385
Now that we are bundling the react runtime for app router we can remove
the esm loader as that was the reason it was added when bringing the
server back into a single process.
x-ref: https://github.com/vercel/next.js/pull/55362
---------
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
I based my changes on #49331, which did this for useFormStatus.
While I was editing the file, I noticed that useOptimistic was incorrectly categorized as a `react-dom` package export, but it's actually exported from `react`. So I fixed that, too.
Co-authored-by: Zack Tanner <1939140+ztanner@users.noreply.github.com>
While investigating the `next start` CPU profile noticed that this
function was called many times and that the JSON.parse happened for each
of them. This replaces that to no longer be needed and leverages the
require cache instead. The reason I didn't go for memoizing this
function is that it would add further complexity and potential for
leaking memory compared to the approach implemented 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 #
-->
## What
This PR changes Next.js to bundle its vendored React libraries so that the App Router pages can use those built-in versions.
## Why
Next.js supports both Pages and App Router and we've gone through a lot of iteration to make sure that Next.js stays flexible wrt to the version of React used: in Pages, we want to use the React provided by the user and in the App Router, to be able to use it, we need to use the canary version of React, which we've built into Next.js for convenience.
The problem stems from the fact that you can't run two different instances of React (by design).
Previously we have a dual worker setup, where we would separate completely each Next.js versions (App and Pages) so that they would not overlap with each other, however this approach was not great performance and memory wise.
We've recently tried using an ESM loader and a single process, but this change would still opt you into the React canary version if you had an app page, which breaks some assumptions.
## How
A list of the changes in this PR:
### New versions of the Next.js runtime
Since we now compile a runtime per type of page (app/route/api/pages), in order to bundle the two versions of React that we vendored, we introduced a new type of bundle suffixed by `-experimental`. This bundle will have the bleeding edge React needed for Server Actions and Next.js will opt you in into that runtime automatically.
For internal contributors, it means that we now run a compiler for 10 subparts of Next.js:
- next_bundle_server
- next_bundle_pages_prod
- next_bundle_pages_turbo
- next_bundle_pages_dev
- next_bundle_app_turbo_experimental
- next_bundle_app_prod
- next_bundle_app_prod_experimental
- next_bundle_app_turbo
- next_bundle_app_dev_experimental
- next_bundle_app_dev
![image](https://github.com/vercel/next.js/assets/11064311/f340417d-845e-45b9-8e86-5b287a295c82)
### Simplified require-hook
Since the versions of React are correctly re-routed at build time for app pages, we don't need the require hook anymore
### Turbopack changes
The bundling logic in Turbopack has been addressed to properly follow the new logic
### Changes to the shared contexts system
Some context files need to have a shared instance between the rendering runtime and the user code, like the one that powers the `next/image` component. In general, the aliasing setup takes care of that but we need the require hook for code that is not compiled to reroute to the correct runtime. This only happens for pages node_modules.
A new Turbopack resolving plugin has been added to handle that logic in Turbopack.
### Misc changes
- `runtime-config` (that powers `next/config`) has been converted to an `.external` file, as it should have been
- there are some rules that have been added to the aliases to support the usage of `react-dom/server` in a server-components. We can do that now since the runtime takes care of separating the versions of React.
Co-authored-by: JJ Kasper <22380829+ijjk@users.noreply.github.com>
### What?
`_devPagesManifest.json` and `_devMiddlewareManifest.json` will fail to load when using an asset prefix. In conjunction with i18n, this causes the app to get caught in an infinite load loop.
### Why?
We're expecting these paths to be exact matches but when there's an assetPrefix specified, they won't be matched.
### How?
This copies similar behavior to how we handle [`webpack-hmr`](2e2211d27b/packages/next/src/server/lib/router-server.ts (L681)) by doing a partial match on the URL when serving it
Closes NEXT-1618
Fixes#55389
### What?
Pages marked with `generateStaticParams` don't currently support server actions, and instead return a 405 Method Not Allowed, with no action being taken on the client. Additionally, pages that are marked static & use server actions are opted into dynamic rendering.
### Why?
The page that has `generateStaticParams` is marked as `isSSG` [here](ee2ec3dd1d/packages/next/src/server/base-server.ts (L1337)).
As a result, the request is short-circuited because a POST request isn't supported on static pages. Upon detecting a server action on a page marked SSG, we bypass the static cache and go straight to the lambda.
This PR introduces an experimental option to the prerender manifest that will allow for selectively bypassing the static cache
This also removes the need to bail out of static generation
Closes NEXT-1167
Closes NEXT-1453
Fixes#49408Fixes#52840Fixes#50932
Removes setLazyProp from the hot path when handling requests. Noticed in
the CPU profile that `Object.defineProperty` is not ideal so this
ensures it's only called where it's needed, which is in `pages`
rendering and `pages/api`.
Also added a test for `getServerSideProps` reading cookies, which is
supported but a test was missing.
<!-- 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 #
-->
Some tests may depend on `latest` to help us catch problems earlier. This adds support for the `resolutions` field for tests to allow pinning of deps that may be problematic upstream.
### What?
Follow-up of #54926.
While that PR's main fix is no longer necessary due to the removal of render workers, I figure that some changes are nice-to-have and have isolated them into this PR. This includes fixing `appUrl` and `networkUrl` in `start-server`, fixing docs and removing some unnecessary template literals in `turbopack-warning`.
### How?
`appUrl` now tries to use `hostname` instead of `actualHostname` (an address like `example.com` seems to be more useful here than an IP like `xxx.xxx.xxx.xxx`), and `networkUrl` is now prefixed with `http://`.
Other simple changes include fixing docs.
Co-authored-by: Zack Tanner <1939140+ztanner@users.noreply.github.com>
We have dropped `experimental.appDir` option, to share the insights that can be removed, add a warning `"App router is enabled by default now, <experimental.appDir> option can be safely removed.'" `
There're few places calling `loadConfig` to access nextjs config for different purpose, and every of them will do validation of next config scheme and could log the warnings potentially to cause duplicated warnings. To address that issue this PR limit the places when should the warnings be logged in certain places, mainly the `next` command entry. Refactor the API here to make it more explicit
Previous logging redeisgn also might trigger duplicated compilation, for instance you compiled page A but then editing another component it might still displaying page A is recompiled. Now we always display `"Compiled .."` message when there's a recompilation but avoid the unnecessary ones such as initial edge compilor ready but there's no modules inside. Then when it recompiles or recovers from error nextjs server will tell "Compiled .." instead of the specific page which might be not related.
Also refactors a minor issue: When `silent` option is set to `true`, auto recorrect next config option from `loadConfig` API like `traillingSlash` is not working
Closes NEXT-1610
Co-authored-by: JJ Kasper <22380829+ijjk@users.noreply.github.com>
## Logging Improvements
* Delay server start logging
Post start logging after request handler is created, so when error
occurred like missing "app" or "pages" directory it won't log start
server message, instead it will only show error message.
* Fix jsconfig hmr case
Previously the `jsconfig.json` is patched too early that didn't trigger
the hmr reload, this PR enables it to show on the
* Adding timestamp for "ready" event
Display a timesmap after "ready" message, so we can monitor how long
does it take, and keep perfing on it
* Polish logging format
* Starts with captital letter
* align the indentation
![image](https://github.com/vercel/next.js/assets/4800338/fb87e0c4-3965-48da-86ef-a178e77d83f2)
### What?
Minor PR brings back turbopack beta message. We'll need to improve the actual checks per progress, but that might need auditing what's working vs not later.
Closes WEB-1517
This fixes a "bug" where Sentry was trying to access some of the internal async storages and it would fail because their imports would be compiled as-is instead of using the special rules for Next externals as we are short-cutting it for `next/dist` requests for some reason.
Not a bug per se because this is technically an undocumented API but I think it's a reasonable fix since we don't provide an API for that. The alternative for them would be to try to play around with the bundling, which is not a good use of anyone's time.
### What
Found a flaky test like https://github.com/vercel/next.js/actions/runs/6125719281/job/16628276301?pr=55118#step:29:174, `get-port` throws by port is not available. Peeking bit, there seems an upstream fix hope to improve the situation but unfortunately it happened after get-port switched to native esm only, so bumping is non trivial work. Instead adapting get-port-please as a replacwement but leave get-port as fallback for a while to verify its stability. Once we are certain, we can remove old get-port entirely.
Closes WEB-1518
### What?
This PR refactors test cases from next-dev, tests basic tailwind rendering with turbopack. It still runs against plain next.js too. While checking, noticed there's a stub fixture (css-fixture/with-tailwindcss) but those fixture seems not being used in the test. Moved those and utilized. Since this test runs against next.js / turbopack both anyway, moving fixture should not be a huge regression I believe.
### What?
https://vercel.slack.com/archives/C04KC8A53T7/p1694190462958199
I realized we throws an error attempt to destory against undefined instance when `beforeAll` fails in any reason. This is quite redundant error since if next instance doesn't exist, likely there's an upstream test failures already and destory against undefined error is not useful to debug anyway.
PR replaces `nextTestSetup`'s teardown first, for the remaining places calling `next.destory` explicitly will be amended later.