<!-- 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
- 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?
- Use a `cssModules` option to configure the `next-flight-css-loader.ts`
based on the match resource.
- Added types
- Ran prettier
### Why?
NextJs supports css modules and global css files.
The `next-flight-css-loader.ts` is capable of dealing with both formats.
However under the hood the loader shares almost no code for css modules
and global css files.
To branch into the correct behaviour the `next-flight-css-loader.ts`
checks the extension of the file using
`this.resourcePath.match(/\.module\.(css|sass|scss)$/)`.
`this.resourcePath` does not include the information from webpacks `!=!`
import syntax.
One solution would be to use `this._module.matchResource` instead of
`this.resourcePath`.
But imho passing it from the webpack.config.js instead of duplicating
the css module file regexp felt cleaner.
### Further questions
- Should we update the loader banner comment?
- Can we drop `this.data.__checksum` in the pitch loader function for
css modules? (it would speed up css modules and for me it looks like it
isn't needed anymore for css modules because of
2eeb0c7f49
(4. April by @shuding)
- Should we split the loader into two loaders?
Fixes#52208
---------
Co-authored-by: Shu Ding <g@shud.in>
The current message isn't very clear about `"use server" function` and
`"use server" file`, and there's no link to docs to explain it further:
```
"use server" functions are not allowed in client components.
You can import them from a "use server" file instead.
```
This PR makes it a bit more verbose:
```
It is not allowed to define inline "use server" annotated Server Actions in Client Components.
You can either mark the entire file by putting "use server" at the top, or pass them down through props from a Server Component.
Read more: https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions#with-client-components
```
## What?
Uses a pre-created regex instead of having webpack run path-to-regexp on the list of patterns. Saves a few milliseconds.
Adds `node_modules` to ignored in order to skip a lot of stat calls at the end of the compilation.
This will likely have a big impact on applications using Yarn PnP as each stat call causes a lookup through `.pnp.cjs`.
### Issue
When the og module is a shared module being imported in both page and metadata image routes, it will be shared in the module graph. Especially in the edge runtime, since the `default` export is being used in the metadata image routes, then it can't be easily tree-shaked out.
### Solution
Separate the image route to a separate layer which won't share modules with the page, so that image route is always bundling separately and the `@vercel/og` module only stays inside in that layer, when import image metadata named exports (size / alt / etc..) it can be still tree shaked.
Co-authored-by: Jiachi Liu <4800338+huozhi@users.noreply.github.com>
As discussed in https://vercel.slack.com/archives/C03ENM5HB4K/p1687999628589119 and #51910, it makes sense to have a known list for packages (mostly polyfills) that we know are having dynamic code (`eval`, `new Function`) but are safe to run in the Edge Runtime because that dynamic code will never be executed.
### What?
When there's a parallel route adjacent to a tree that has no page
component, it's treated as an invalid entry in `handleAppPing` during
dev HMR, which causes an infinite refresh cycle
### Why?
In #51413, an update was made to `next-app-loader` to support layout
files in parallel routes. Part of this change updated the parallel
segment matching logic to mark the parallel page entry as `[
'@parallel', [ 'page$' ] ]` rather than `[ '@parallel', 'page$' ]`.
This resulted in `handleAppPing` looking for the corresponding page
entry at `client@app@/@parallel/page$/page` (note the `PAGE_SEGMENT`
marker) rather than `client@app@/@parallel/page`, causing the path to be
marked invalid on HMR pings, and triggering an endless fastRefresh.
### How?
A simple patch to fix this would fix this is to update `getEntryKey` to
replace any `PAGE_SEGMENT`'s that leak into the entry which I did in
59a972f53339cf6e444e3bf5be45bf115a24c31a.
The other option that's currently implemented here is to only insert
PAGE_SEGMENT as an array in the scenario where there isn't a page
adjacent to the parallel segment. This is to ensure that the
`parallelKey` is `children` rather than the `@parallel` slot when in
[`createSubtreePropsFromSegmentPath`](59a972f533/packages/next/src/build/webpack/loaders/next-app-loader.ts (L298)).
This seems to not cause any regressions with the issue being fixed in
51413, and also solves this case, but I'm just not 100% sure if this
might break another scenario that I'm not thinking of.
Closes NEXT-1337
Fixes#51951
## What?
Ensures the router instance passed for `next/navigation` in Pages Router is a stable reference. For App Router the router instance is already a stable reference, so making this one stable too would fix#18127.
## How?
Added `React.useMemo` around `adaptForAppRouterInstance`, previously it was recreated each render but that's not needed for this particular case. The searchParamsContext and pathnameContext do need a new value each render in order to ensure they get the latest value.
Fixes#18127
Fixes NEXT-1375
### What
Support `scroll={false}` for Link component in app router. This can be
used when you don't need to scroll back to top again when route url
changes. For instance hash query changes, if you want to keep the
scrolling as it is, you can use this option.
### How
Handling the `scroll` option in navigation reducer on client side.
Fixes#50105
Fixes NEXT-1377
---------
Co-authored-by: Jiachi Liu <inbox@huozhi.im>
### What?
Add all passing tests
### Why?
We enforced that they all run turbopack and these are passing.
If any of these tests would become red, that indicated a problem.
Currently we are validating the `experimental.serverActions` flag when creating the actual entries for Server Actions, this causes two problems. One is that syntax errors caught at compilation time are still shown, even if you don't have this flag enabled. Another problem is we still traverse the client graph to collect these action modules even if the flag isn't enabled.
This PR moves that check to be happening at compilation time, which addresses the two above but also brings the extra benefit of showing the exact span and module trace that errors:
<img width="974" alt="CleanShot 2023-07-03 at 20 26 34@2x" src="https://github.com/vercel/next.js/assets/3676859/1676b1f6-e205-4963-bce4-5b515a698e9c">
### Issue
When you edit .env* files, the pages under app dir that using env vars are not triggering hot reload
### Fix
Triggering serverComponentChanges hot reload action when we detect env or tsconfig related change. There's a time period that we need to wait before the compilation is finished. First we save a flag `reloadOnDone` if we need to reload when after compilation is done, by determining if `envChange` is `true` (we already know this in dev server). Then in the compilation hooks, we refresh RSC page once it's finished.
### Extra change
since we're checking `event.action` in client hot reloader, and throwing error for unknown action, filter devPagesManifestUpdate out from unexpected action as it sometimes triggered as error in console. Introduced in #51516
Fixes NEXT-1261
In the dev server, we need to call `getStaticInfoIncludingLayouts` for the middleware file to extract its `matchers` field. However, that's currently executed in both app and pages workers. This method is expensive as it depends on the SWC binary to be loaded.
This PR changes it to invoke it as an IPC method, so only the router worker (which runs the compilation) loads SWC, instead of all 3 of them.
This also fixes duplicated console messages of:
```
Using locally built binary of @next/swc
```
For our test app, I'm seeing a 150~250ms improvement:
![CleanShot 2023-07-02 at 18 29 22@2x](https://github.com/vercel/next.js/assets/3676859/be78b79b-2eb4-4f04-92dc-3640e12cde23)
Haven't measured about the memory impact yet, but it should be a lot.
This adapts the new route module rendering to support edge as well.
- Added a new `routeModule` export to the Edge SSR Loader
- Updated some tests to validate page state
Fixes NEXT-1327
When looking at [some sites](https://rsc-llm-on-the-edge.vercel.app/) with a large amount of chunks streamed, I noticed that the inlined Flight data array can be optimized quite a lot. Currently we do:
```js
self.__next_f.push([1,"d5:[\"4\",[\"$\",\"$a\",null,..."])
```
1. The `self.` isn't needed (except for the initial bootstrap tag) as React itself has `<script>$RC("B:f","S:f")</script>` too.
2. After the bootstrap script tag, all items are an array with `[1, flight_data]` and `flight_data` is always a string. We can just push only these strings.
3. We use `JSON.stringify(flight_payload)` to inline the payload where the payload itself is a string with a lot of double quotes (`"`), this results in a huge amount of backslashes (`\`). Here we can instead replace it to use a pair of single quotes on the outside and un-escape the double quotes inside.
Here's a side-by-side comparison of a small page:
<img width="1710" alt="CleanShot 2023-06-30 at 11 41 02@2x" src="https://github.com/vercel/next.js/assets/3676859/398356ec-91d5-435c-892d-16fb996029e8">
For a real production page I saw the HTML payload reduced by 11,031 bytes, a 3% improvement.
Note that all the tests are not considering gzip here, so the actual traffic impact will be smaller.
This PR changes some Webpack loaders to be synchronous as they don't have async code inside. Some of them will scale quiet a lot such as `next-flight-client-module-loader` and we don't want to waste some extra ticks there, as well as got potentially queued after some other events like file I/O.
We show the "Application error: a client-side exception has occurred (see the browser console for more information)" error incorrectly when a server-side error occurs (a digest is present) when we should be showing an error saying it is in fact a server side error and should check the logs there. This change will make the error message more accurate for users to look up
Fixes NEXT-1263
Unlike other routes, these two entries are needed for every request so there is no reason to have them disposed. This avoids wasting extra dev server resource to get them re-compiled.
Increase `maxInactiveAge` to be `60` seconds and `pagesBufferLength` to be `5`. This change makes it infrequent to have expired entry compilations from recent accessed routes when running the dev server.
### What?
The updates `edge-runtime` to the latest version
### Why?
https://github.com/vercel/edge-runtime/pull/428 fixes `consumeUint8ArrayReadableStream` so that when we break iteration early (due to client disconnect), we cleanup the inner stream. That will fire the stream's `cancel` handler, and allow devs to disconnect from an AI service fetch.
### How?
`edge-runtime` maintain a `try {} finally {}` over the inner stream's iteration. When we early break, JS will call `it.return()`, and that will resume `consumeUint8ArrayReadableStream` with an abrupt completion (essentially, the `yield` turns into a `return`). We'll be able to trigger the `finally {}` block with that, and we call `inner.cancel()` to cleanup.
Fixes https://github.com/vercel-labs/ai/issues/90
Filter out the invalid images in metadata og/twitter `images` filter to avoid crash when falsy image slides in.
Add filtering for now as the erroring doesn't show the proper trace pointing to where it's original introduced, might introduce other validation in the future.
## What?
Currently we use 3 separate webpack compilers:
- server
- client
- edge
All of these were creating their own input filesystem (which is used to
read file, stat, etc.). Changing them to share a single inputFileSystem
allows the `cachedFileSystem` to be reused better, as `stat` and
`readFile` can be cached across the 3 compilers.
For the page on vercel.com we've been testing this shaves off 300-400ms
on a cold compile (no cache, deleted `.next`).
<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:
## For Contributors
### Improving Documentation
- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide
### Adding or Updating Examples
- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md
### Fixing a bug
- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md
### Adding a feature
- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md
## For Maintainers
- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change
### What?
### Why?
### How?
Closes NEXT-
Fixes #
-->
---------
Co-authored-by: Shu Ding <g@shud.in>
remaining:
- add tests
caveat: this only works at the route level, we won't inherit from the layout or anything. I think that's fine
Co-authored-by: Florentin / 珞辰 <8146736+ecklf@users.noreply.github.com>
### What?
This PR fixes `next/link`'s `<Link />` missing many `<a />` props when
`experimental.typedRoutes` is enabled.
### How?
It does that by changing `AnchorHTMLAttributes<HTMLAnchorElement>` in
LinkRestProps to
`DetailedHTMLProps<AnchorHTMLAttributes<HTMLAnchorElement>,
HTMLAnchorElement>`, which contains all `<a />` props.
Fixes#51907
---------
Co-authored-by: Shu Ding <g@shud.in>
This PR changes `fs.stat` calls (to check if a file exists or not) to be
aggregated as `fs.readdir` calls and cached during the entire loader
pass. This is because we have a huge amount of file to check, but they
are always in a small amount of directories.
For example, a route that's 5-directory deep (`/a/b/c/d/page.js`) can
have up to 4,000 special segments and metadata files to check. However
they're always under these 5 directories. So instead of 4,000 `fs.stat`
calls let's just do 5 `fs.readdir` calls.
Didn't measure it carefully but a quick local test shows a 20~30%
improvement.
<details>
<summary>Another idea for future improvements</summary>
Currently, we create a MissingModuleDependency for any combination of
possible metadata filename. But in reality, we only need to track them
incrementally by index. For example if `icon1.js` is missing, it's kinda
waste to still track `icon2.js`~`icon9.js` because `icon1.js` will be
added first. This change should at least reduce the number of file
watchers by 80% and the initial compilation time by 0.5~1s, depending on
the actual route.
</details>
---------
Co-authored-by: Tim Neutkens <tim@timneutkens.nl>
### Description
This PR refactors the Image component so that the core logic can be consolidated into a single function.
This allows usage outside of `<Image>`, such as:
1. Working with [`background-image`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-image) or [`image-set`](https://developer.mozilla.org/en-US/docs/Web/CSS/image/image-set)
2. Working with canvas [`context.drawImage()`](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images) or simply `new Image()`
3. Working with [`<picture>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture) media queries to implement Art Direction or Light/Dark Mode images
### Example
```tsx
import { unstable_getImgProps as getImgProps } from 'next/image'
export default function Page() {
const common = { alt: 'Hero', width: 800, height: 400 }
const { props: { srcSet: dark } } = getImgProps({ ...common, src: '/dark.png' })
const { props: { srcSet: light, ...rest } } = getImgProps({ ...common, src: '/light.png' })
return (<picture>
<source media="(prefers-color-scheme: dark)" srcSet={dark} />
<source media="(prefers-color-scheme: light)" srcSet={light} />
<img {...rest} />
</picture>)
}
```
### Related
fix NEXT-257
Co-authored-by: Jiachi Liu <4800338+huozhi@users.noreply.github.com>
`reactProductionProfiling` was a next config working for pages before mainly for profiling react, this PR also enables it for pages.
### Chanegs
* Add react profiling entry and related alias
* Fix `reactProductionProfiling` is missing in next config type and schema
Closes#51131
## Bug
- [x] Related issues linked using `fixes #number`
- [ ] Integration tests added -> this is a pretty niche edge case, do
you want me to?
- [x] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)
Fixes#45024
Co-authored-by: JJ Kasper <jj@jjsweb.site>
### What?
Adds `payload` to the external package list
### Why?
To prevent developers using
[Payload](https://github.com/payloadcms/payload) modules within Next.js
from having to add this in their next config.
### What?
This ensures the `request.signal` `AbortSignal` that every Pages API and App Route handler receives aborts when the client disconnects.
### Why?
Now that we [support cancelling](https://github.com/vercel/next.js/pull/51594) responses mid-stream, it's important that we can communicate that abort to developer code. Eg, for AI endpoints that have an streaming `fetch` connection to the some 3p AI service, it's important that they're able to abort that stream when the client's browser disconnects.
### How?
Just need to listen for `error` events on Node's `IncomingMessage` request object, and forward that to an `AbortController`. After that, propagate the signal through the server to web-style handlers.
After migrating a Next.js app from Pages Router to App Router and using as many RSC as possible, I notice that the client js bundle size actually increases by 5%. It turns out that Next.js has introduced a lot of code to the client bundle.
<img width="1354" alt="image" src="https://github.com/vercel/next.js/assets/40715044/c7216fee-818b-4593-917e-bf0d2a00967a">
The PR is an attempt to reduce the client bundle size.
This PR makes the server code be minified.
## Why
This will improve performance of the server code because of the lesser
size, lesser time to parse and lesser code via tree sharking.
Cons: this should lead to increased build times, so a
`disableServerMinification` config was added
<!-- 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 #
-->
link NEXT-1319
Improve the problems mentioned in #45080.
- Adding error retries (3 attempts) to font fetching. When you have a slow network, it might take >3s to load.
- Improve the error message to tell you that you might have unstable network connection.
- Do not cause build error (caused by missing `AbortController`) in Node 14 (even if we don't support Node 14, better to pass the build instead of hard error).
### What?
Slack thread:
https://vercel.slack.com/archives/C050WU03V3N/p1687889719318819
In Node 16, the ReadableStream is not on the global but instead under
the `stream` package. We should polyfill the global with that
implementation, if available
### Why?
Fixes passing ReadableStream from the Node.js runtime to the vercel/ai
SDK.
To enable the ability of leveraging current `pathname` and configured `metadataBase` for other canonical like urls, we support those urls with auto resolving with `pathename` and `metadataBase` like canonical url, then you could just configure relative paths like below
```js
openGraph: {
url: './abc', // will be resolved based on pathname and metadata base
},
itunes: {
appId: 'my-app-id'
appArgument: './native-app'
}
```
Fixes#51829
Closes NEXT-1302
### What?
Node.js sets stdout to non-blocking by default, rust expects it to be blocking
so when logging a lot of data, it can happen that rust receives an error while writing causing it to panic, the error is just that the resource is temporarily unavailable, but rust doesn't handle this case
See https://github.com/napi-rs/napi-rs/issues/1630
## What?
In the first implementation of App Router a year ago I added `return
null` for this case which is incorrect as we have to suspend rendering
when doing a navigation.
The logic in `app-router.tsx` already handles that automatically. The
logic in layout-router is no longer needed as the flightData will be
applied automatically in the reducer.
## How?
Removed the logic when the fetch returns a path to mpaNavigate to.
<!-- 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 #
-->
Removed an unnecessary dependency mapping from the plugin.
Here's a quick visualization of this change. We have to traversal the module graph twice. The first iteration goes through all server modules and creates the client entries. And the second iteration collects info from all client modules.
Before this PR, the second iteration starts from server entries so it traversals both layers. With this PR, the second iteration will start from client entries only:
<img width="870" alt="CleanShot 2023-06-27 at 10 01 08@2x" src="https://github.com/vercel/next.js/assets/3676859/f0b7a0c6-0ade-483a-8645-48e2a8a6c9d0">
This is a ~100ms improvement for HMR of complicate apps.
### What?
`next build` is incorrectly reporting file size stats for the root path
when using the app dir
### Why?
In #50768, the denormalization logic was removed for appDir routes, but
`pagesManifest` has the root page keyed by `/` while the actual path
will be `/index`.
### How?
This re-adds a simpler denormalize function that just replaces `/index`
with `/`.
semi-related: #42819Fixes#51692
link NEXT-1306
---------
Co-authored-by: JJ Kasper <jj@jjsweb.site>
Co-authored-by: Jiachi Liu <inbox@huozhi.im>
This is already the default for production build, but we are also enabling it for development. It has small perf impact as gzip takes time, but it significantly improves the disk usage and time for reading and writing to the filesystem. This is especially the case when working on a large codebase and we are transpiling and bundling more modules now.
## Background
Currently we're track all imported CSS modules by an entry, in the
client manifest:
```js
// client manifest
{
entryCSSFiles: {
'app/entry_name': {
modules: ['app/foo.css', ...]
}
}
}
```
And then, in the font manifest we track all emitted assets (fonts) by
each CSS module:
```js
// font manifest
{
app: {
'app/foo.css': [
'static/font/abc.woff', ...
]
}
}
```
These two fields are only used together by `get-preloadable-fonts.tsx`,
so it can know which font files need to be preloaded for this entry.
(Although previously we use `.modules` for something else, but it's gone
now)
## Changes
Since we only need the font assets per entry, it's unnecessary to track
these in the module level and then join them together. This PR removes
the `modules` field from the client manifest, and changes the font
manifest to directly keep the entry—font mapping.
This gets rid of one module traversal from the client manifest plugin.
An annoying issue that slows down compilation times in dev for Next is
that we might trigger compilation of a page via hover on app.
We do this because we want the same experience in production and dev and
the prefetching is important for instantaneous loading states.
The alternative in this PR is that we don't prefetch at all anymore in
dev but instead, when we handle navigation, we can force a prefetch
navigation.
The slight compromise with this approach is that you can't test
prefetching anymore in dev.
<!-- 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 #
-->
link NEXT-1317
Instead of traversing the entire client module graph twice (!), this PR
changes it to only traverse the client **entry** modules only. Because
of the way we create client entries, all client modules' _boundaries_
can be retrieved via all outgoing connections of all chunks' entry
modules, filtered by `next-flight-client-entry-loader`.
This brings down the time complexity from `2 * num_client_modules` to
`num_client_entry_modules`.
Closes#51240.
Additional notes from @timneutkens
- Removed `module.unsafeCache` as it seemed to be leaking modules across
multiple compilations, this should help with memory usage
- Changed entry-loader to have consistent module import map (sort it) to
ensure cache key is consistent
---------
Co-authored-by: Tim Neutkens <tim@timneutkens.nl>
Limit the number of Watchpack's watchers to 20 for the routing worker which runs Watchpack. By default this value is 2000 on macOS and 10000 on Windows, which can hold too much resource.
This PR fixes tree-shaking for the metadata image generation module
(e.g. `opengraph-image.js` and other conventions) when the page has
`runtime = 'edge'`.
## Details
The first step of this fix is to change this from the loader:
```js
import * as exported from "./opengraph-image.js"
```
to be necessary fields only (so the `default` export can potentially be
removed):
```js
import { alt, size } from "./opengraph-image.js"
```
To know which fields are exported, we need to load the module first via
Webpack loader's `loadModule` API and check its
`HarmonyExportSpecifierDependency` dependencies.
This is the first step to make it tree-shakable. Since we have
`./opengraph-image.js` used in another entry, the actual image API route
`opengraph-image/route.js`:
```js
import * as image from "./opengraph-image.js"
```
Webpack still treats both as the same module and generates one chunk for
it. We want to "fork" it into two modules. The technique here is to add
a noop resource query and make it:
```js
import { alt, size } from "./opengraph-image.js?__next_metadata_image_meta__"
```
So it won't be shared in the chunk (as it's a different request), and
can be concatenated inline.
However that's not enough, the inlined result will still have all
imports from our `opengraph-image.js`, including `import { ImageResponse
} from 'next/server'`. Because we can't simply add `"sideEffects":
false` in Next.js' package.json, we need a way to mark this import as
side-effect free. I went through
https://github.com/webpack/webpack/blob/main/lib/optimize/SideEffectsFlagPlugin.js
and used the same method to mark that module with
`module.factoryMeta.sideEffectFree = true`.
With all these added, the page bundle will no longer contain the
`ImageResponse` instance.
## Result
The difference is quite amazing, for the new added test (an empty Edge
runtime page with an opengrah image file) here're the before/after
metrics for the `page.js` server bundle:
Edge bundle size: 892kB → 500kB.
Build time: 26.792s → 8.830s.
### What?
Interception route rewrites are not properly parsing catch-all segments,
which leads to "missing parameter name" errors when passed to
`pathToRegexp`.
### Why?
The existing `toPathToRegexpPath` function ignores `...` and keeps it as
part of the regexp path. This means `pathToRegexp` will attempt to
handle `/foo/bar/:...baz` and `/foo/bar/:[...baz]` rather than
`/foo/bar/:baz*`
### How?
The regex used for matching the path was updated to support the dynamic
optional segment, and then we special case catch-all segments
Fixes#51784
---------
As noted in the comments, it's necessary to always add optional dependencies as missing dependencies even if they exist because they might be deleted and re-added.
Closes#51763.
Close the circle after #51104. The name "size limit" can be confusing as it could also mean the size of the Server Action function itself, so this PR changes it to `serverActionsBodySizeLimit` and makes sure it's well documented.
This adds support for matching against the user-agent header when doing rewrites client side.
Currently a rewrite like this will fail because the user-agent header is not provided, and so next.js tries to prevent infinite rewrites:
```
{
source: '/:path*',
destination: 'https://example.com/:path*',
missing: [
{
type: 'header',
key: 'User-Agent',
value: '.*(?:Electron).*'
},
],
}
```
Adding in the user-agent header allows this rewrite to pass.
Adding `nextConfig.output` to next-info output so that we could determine if users're using standalone mode if the reproduction is not clear or missing sometimes
Example output
```
Relevant Packages:
next: 13.4.8-canary.1
eslint-config-next: 13.4.8-canary.1
react: 18.2.0
react-dom: 18.2.0
typescript: 5.1.3
Next.js Config:
output: standalone
```
<!-- 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
- 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?
Add configuration options to modify the `bodyParser` size as it used to
be available in Page Router.
### Why?
Server Actions "Error: Body exceeded 1mb limit" cannot be resolved since
the body-parser limit size is hardcoded to `1mb`.
### How?
Closes NEXT-
Fixes #
-->
### What?
Add configuration options to modify the `bodyParser` size as it used to
be available in Page Router for APIs.
```js
export const config = {
api: {
responseLimit: false | '8mb'
},
}
```
Reference: [API Routes Response Size
Limit](https://nextjs.org/docs/messages/api-routes-response-size-limit)
### Why?
Server Actions "Error: Body exceeded 1mb limit" cannot be resolved since
the body-parser limit size is hardcoded to `1mb`.
```js
// /packages/next/src/server/app-render/action-handler.ts
// ...
const actionData = (await parseBody(req, '1mb')) || ''
// ...
```
Reference:
https://github.com/vercel/next.js/blob/canary/packages/next/src/server/app-render/action-handler.ts#L355
### How?
- Added option "serverActionsLimit" as `SizeLimit` type to
`config-shared.ts`
- Modified `action-handler.ts` to validate `serverActions` &
`serverActionsLimit` options in nextConfig
- Added conditional `serverActionsLimit` value and `1mb` if falsy
**Working on testing**
Fixes#49891 | #51097 | #51099
---------
Co-authored-by: JJ Kasper <jj@jjsweb.site>
Co-authored-by: Shu Ding <g@shud.in>
This PR addresses a problem where the `createServerReference` is using
the default condition of flight client (gets resolved to the Node
build), but we use the Edge build of flight client for SSR. This causes
2 flight clients to exist during SSR.
This removes calls for rendering files in `pages/` via the server code and relies instead relies on the bundled `routeModule` to perform the rendering.
Future cases that try to call the legacy render will hit a new:
```
Invariant: render should have used routeModule
```
Error. These cases should be reported.
## What?
Adds a default modularizeImports that ensures `lucide-react`, `@mui/icons-material`, `lodash`, and `react-bootstrap` do not cause a massive amount of modules to be compiled in development.
For example `@mui/icons-material` re-exports 10600 (10K+) modules from a single file. Even though it does not affect production bundle size it does affect build time, especially in development, and even more so when your filesystem is slow (e.g. what we're seeing on Windows).
Related issue: #48748 (not closing)
Co-authored-by: Shu Ding <3676859+shuding@users.noreply.github.com>
Request data flow in the server
```
request ---> router worker (1) ---> ipc ---> render worker app (2)
|-----> render worker pages (3)
```
When it's hitting `_next/*` unmatched routes in standalone server, it will render 404, but when you hit `_next/*` it will render app not-found as the app router is always enabled, but router worker isn't set up with require-hook for proper built-in react version, then the app-render will fail with `./server.edge` exports not found error.
We detect if it's in the render worker, then do the app paths rendering instead of directly looking up for app paths in route worker. This could avoid unexpected accesses to the app-render
Fixes#51482Fixes#50232Closes#51506
Reverts changes in #51172
fix NEXT-1260
When conflicted pages occur between app and pages server used to throw error and you need to solve the conflicts and restart the server.
This PR capture the error during files aggregation, and send to client to display the error for files confliction. This will send all the conflicts to client and it will still error until you solve all of them. But since the server is not stuck by errors, client can recover once the error is solved.
Closes NEXT-1283
The next-metadata-route-loader emitted content with `"next/server"` is still using cjs version which is not get tree-shaked on edge runtime, This PR adds a new esm entry for it and mapped it that on edge runtime so unused exports can be tree-shaked. This case happened when users are using ImageResponse from `"@vercel/og"` instead of `"next/server"`.
2nd change is adding another alias to map `@vercel/og` package to vendored og package inside next.js, this way we could merge the two package instead of bundled both of them
Fixes: NEXT-1303
changed `require.reoslve("next/dist/xxx")` to `${NEXT_PROJECT_ROOT}/xxx}` to avoid to be traced by nft.
Continuing on changes to move the rendering logic into the bundles.
- Unifies edge render functions: `appRenderToHTML` and `pagesRenderToHTML` becomes `renderToHTML`
- When an error occurs, the error module's match is used so the module's internal render can be used (easing transition away from using the server's render method)
- Improved test resiliance
### What?
Paths with interception markers adjacent to dynamic segments are not correctly parsed, which leads to the path match logic failing.
### Why?
`getParametrizedRoutes` checks for brackets but isn't expecting to receive an interception marker. For example, a path of `/photos/(.)[author]/[id]` results in the following regex:
`/^\/photos\/\(\.\)\[author\]\/([^/]+?)(?:\/)?$/`
This will not match a path of `/photos/(.)zack/1` since it retained the `[author]` brackets.
`getSegmentParam` has a similar issue when getting values for path params, though we can just skip the interception markers and go straight to the params.
Closes NEXT-1166, NEXT-1013
Fixes#48143Fixes#49614
link NEXT-1013
### What?
This is an alternative to #51330, which only support aborting the response (doesn't support back-pressure). If the client cancels the request (HMR update, navigates to another page, etc), we'll be able to detect that and stop pulling data from the dev's `ReadableStream` response.
### Why?
We want to allow API routes to stream data coming from another server (eg, AI services). The responses from these other servers can be long running and expensive. In the case the browser aborts the connection, it's critical that we stop streaming data as soon as possible.
### How?
By checking whether `response.closed` is set during the `for await (…)` iteration, we're able to detect that the client has aborted the connection. Cleanup of the `ReadableStream` is handled implicitly by the async iterator when the loop ends.
The one catch is our use of http-proxy for worker processes. It does not properly detect a client disconnecting (but does handle back-pressure). In order to fix that, I've manually added event listeners to detect the disconnect and cancel the proxied req/res pair.
Re: [WEB-1185](https://linear.app/vercel/issue/WEB-1185) (we still need back-pressure)
Fixes https://github.com/vercel/next.js/issues/50364
Fixes https://github.com/vercel-labs/ai/issues/90
### Fixing a bug
- [x] Related issues linked using `fixes #number`
- [x] 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
### What?
Currently, when the check on validating the type of `revalidate` is run,
we use the `Number` function to parse the value of `revalidate`, however
the `Number` function takes a
[`StringNumericLiteral`](https://tc39.es/ecma262/2023/#prod-StringNumericLiteral)
which doesn't allow the usage of the `_` separator to format your
numbers. This PR allows you to add numeric separators in the
`revalidate` export.
### Why?
When configuring the actual code, we should be allowed to use numeric
separators as it is a syntax that is supported by most runtimes.
### How?
A simple `replaceAll` call that removes all `_`s between digits.
Closes NEXT-1122
Fixes#49485
---------
Co-authored-by: JJ Kasper <jj@jjsweb.site>
Small QOL improvements to `RenderResult` and `RouteModule` setup. This
also adds a test to verify that headers aren't sent on responses that
have already been sent.
---------
Co-authored-by: JJ Kasper <jj@jjsweb.site>
### What?
this forces all tests to use turbopack independent of the way they invoke next dev
### Why?
some tests were not running turbopack
fixes WEB-1187
follow up on #51413 where I kinda forgot to support parsing layout files in sub routes in a parallel segment.
This should fix it by making sure that we check at all level of the app loader tree and by creating an implicit inner `children` for all parallel slot
link NEXT-1301
When working with React Server Components, it's essential to have a
clear understanding of how they function and how to troubleshoot any
errors that may arise. This PR adds links to our documentation whenever
an error related to React Server Components occurs.
### What?
While looking into some things related to the FileSystemCache, I came
across this typo introduced in #49227. Not sure how it's currently
manifesting but figured it'd be worth correcting
Currently an "action module" (files with `"use server"` on top) can be
imported by both the server and client layers. In that case, we can't
fork that action module into two modules (one on the server layer, one
on the action layer), but only create it once on the server layer.
This ensures that the action module instance doesn't get forked.
Closes#50801.
fix NEXT-1265
### What?
* allow to use `runtime = "edge"` for app dir in turbopack
* move common imports from next-app-loader to
`packages/next/src/server/app-render/entry-base.ts`
* move common turbopack code to communicate between JS and Rust into
separate files
### Why?
A lot test cases depend on edge rendering
### How?
---------
Co-authored-by: Alex Kirszenberg <alex.kirszenberg@vercel.com>
This contains the original POC for `next build --turbo`. The implementation is _just enough_ to get pages building, and doesn't support the app router yet.
I'll write more details here on the implementation and what the next steps are next week.
Necessary changes on the Turbo side: https://github.com/vercel/turbo/pull/4998
This PR fixes a bug in which the layout files were not picked up if they were direct children of a parallel route slot.
Note: there's a bunch of other files that I've used for debugging that are not used for the test but I'm leaving them for future me.
link NEXT-969
There're 3 layers in the RSC module graph: server → client → action. "Action" means that a Client Component re-enters the server layer by importing a file with `"use server"`, and it should behave the same as the server layer but you can't enter the client layer again (hence we have a 3rd layer name).
Since the action layer has the same behavior and module resolution rules, it should be bundled just like the server layer.
Closes#50658. Originally the issue was that `auth/next` isn't being bundled on the action layer, and it has the async local storage imported. Because of that, that storage comes from node_modules instead of the server bundle.
fix NEXT-1290
This attempts to avoid IPv6 and IPv4 resolve issues across network
setups by locking down our internal IPC requests to just one address for
consistency. This way there aren't issues when `localhost` resolves to
one or the other in different cases.
x-ref: https://github.com/vercel/next.js/issues/49677
This PR updates `.vercel.approvers` files to fix some validation errors
and to more closely match desired behavior for assigning and notifying
members of the team for reviews that was discussed on an internal Slack
thread.
- Owners files for `.cargo/` and `.config/` are moved to their
respective directories instead of being placed at the root.
- Fixes the `@vercel/next-js` team name (it uses a dash instead of a
period)
- Adds `:notify` to reviewers so that all of the people listed are
notified of the pull request, but only a single person would be
requested as a reviewer.
- `@vercel/web-tooling:optional` was made optional so that they are not
requested for any change to `pnpm-lock.yaml` but still have the ability
to approve PRs that modify it.
---------
Make sure we are using `var` instead of `const` as we always put the new
appended statements to the end of the module body, but they can still be
referenced before in the HOC case in the runtime. This causes a runtime
error.
Tl;dr: `a = 1; var a` is fine, but `a; const a = ...` will result in a
compilation error.
Closes#49344.
It's valid to want to output JSON instead of HTML for the bundle
analyzer so we can expose this specific config the same as
`openAnalyzer`. cc @mknichel
Remove the Server CSS manifest and related logic, and use the chunkGroup
CSS files instead for each entry to inject stylesheet links.
Why was that manifest needed in the first place? When implementing CSS
collection for RSC and nested layout initially, we collect CSS imports
at each layer and create corresponding client entries. But then soon got
hit by the problem of duplication and improper tree-shaking. Two layers
can have the same CSS imported so we solved it in a way that "if an
upper layer imports this module, skip it in child layers". Note that
this is deduped by module, so we need to keep the information of "layer
(entry) → CSS modules" somewhere, in a manifest.
Another reason is that we create the client entry before Webpack
optimizes modules, so we can inject the client entry into the same
compilation. But that means the collected client modules from the server
layer are not properly optimized (DCE). **This is a general issue at the
moment that's not specifically related to CSS, although using that
manifest to collect DCE'd info and join the original collected CSS files
with that info temporarily solved it.** That's why I disabled some tests
related to font CSS collection and want to improve it in a more general
way.
Why is that not needed anymore? Main reason is to keep a good balance
between duplication and number of chunks, and delegate the decision to
Webpack's splitChunks plugin. It is not possible to get to a point of 0
duplication unless we ship every CSS module as a single chunk. And since
in #50406 we made the duplication better but at the chunk asset level,
instead of the original module level.
Prior work: #50406, #50610.
### What?
Fixes https://github.com/vercel/next.js/issues/50129
### Why?
The current denormalization of app dir paths doesnt account for the
normalization done in `normalizeAppPath`, causing build log outputs for
certain paths such as anything under a route groups to be incorrect
### How?
There's 2 ways this could be fixed:
1.) Denormalize the app dir paths by reading the
`app-path-routes-manifest.json` and mapping back to the original file
path
2.) (what I chose to do) Normalize the keys of `appBuildManifest`
### Result
App dir paths, including route groups, now have their correct output
size
<img width="494" alt="image"
src="https://github.com/vercel/next.js/assets/93682696/0eee79b8-7d60-4c88-b07a-dfb750aa9592">
---------
Co-authored-by: JJ Kasper <jj@jjsweb.site>
This cleans up some setup functions within the route modules, improves logic around headers, and handles the case where the URL is invalid better for routes using the request adapters.
Similar to tags and paths, when `cookies().set()` is called we have to
invalidate the client router cache as well so routes with
`cookies().get()` will not holding the stale data. This is critical for
auth and other scenarios.
In the future we can have an optimization to only invalidate routes that
actually rely on cookies, similar to paths.
This PR fixes a few reports that we were double fetching when navigating via a link that had prefetch false.
## Context
The bug was happening because we were inadvertently eagerly fetching even if we potentially bailed out of the optimistic navigation, which would then trigger another fetch from going through the regular navigation path.
There's potentially another bug here where we should potentially not bail out of optimistic navigation in the cases reported but we can fix that later.
fix#49844
link NEXT-1287
## What?
While looking at the CPU profile of booting up Vercel's site I noticed
that we call `getPageStaticInfo` a lot. Looking into this more it turns
out `getPageStaticInfo` is currently called for all routes, `pages` and
`app`, even though the data is only being used to keep track of which
routes are edge functions, however, this is already tracked as part of
the build output so this didn't make sense to me. First I tried
commenting out this entire block and all tests were passing, so I
removed it except for middleware as middleware can provide a `matcher`
which does need to be known before compiling the file as of right now.
After that change a different set of tests started failing, specifically
the one that checks if we warn correctly. Interestingly by fixing
`getPageStaticInfo` being called early and for all routes it also caused
these warnings to no longer trigger as there was a case in the manifest
plugin that called `getPageStaticInfo` with less information. Calling
`getPageStaticInfo` there was not needed either as we call
`getPageStaticInfo` at the beginning of the build for each entrypoint so
we already have the information required, it just had to be passed down
so that the manifest plugin could use it.
For Vercel's site this change improves booting the dev server by over 1
second.
Related to #48748
<!-- 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
- 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: Jiachi Liu <inbox@huozhi.im>
### What?
Adds mikroORM to external package list
### Why?
To prevent developers using
[MedusaJS](https://github.com/medusajs/medusa) modules with NextJS from
having to add this in their next config.
---------
Co-authored-by: JJ Kasper <jj@jjsweb.site>
When navigating to a route with a hash parameter, the layout router
jumps to the element by scrolling to the node's `offsetTop` value.
However, this will ignore `scroll-padding`, which deviates from browser
behavior.
It looks like this isn't an issue in the pages router which currently
makes use of
[`scrollIntoView`](https://github.com/vercel/next.js/blob/canary/packages/next/src/shared/lib/router/router.ts#L2262).
Closes NEXT-1171
Fixes#49612
---------
### What?
Add all available options to cli commands
Consistent formatting for all options
### Why?
Options were not consistent across all commands, some were missing
Co-authored-by: Steven <229881+styfle@users.noreply.github.com>
Co-authored-by: JJ Kasper <22380829+ijjk@users.noreply.github.com>
Tweak code owners after some testing and feedback.
- Move the Next.js team up to be optional global code owners (so that everyone can review but are not tagged for review). Global individuals should still be tagged if there are no specific `.vercel.approvers` files in subdirectories.
- Adds @vercel/devex to image files so there's coverage on those files for the docs
- Target specific folder and files for Styfle to get notified
- Deletes some rules in the old GitHub codeowners
This removes the `__internal_nextjs_integration_test` compile-time feature. This would end up requiring an additional set of build targets for running integration tests was only used for two cases:
* Determining whether to read from an env var to load mocked Google fonts responses in next/font/google tests. This now uses the presence of this variable to determine whether to use mocked responses.
* Enabling the `next-dev/serializable` feature. This is now set directly instead.
Test Plan:
* Integration tests with Turbopack.
* Manual test of next/font/google with Turbopack
Both of our bundlers won't split different exports of a module into different chunks, we can rely on https://github.com/facebook/react/pull/26624 to simplify the structure. This reduces the size of the client reference manifest by ~70%.
Fixes#50232
Passing down the private env into `'render-server'` module to pick up the proper react with require-hook in standalone server
fix NEXT-1260
We already have a warning when using `next export` with `output: export` because the `next export` is effectively a no-op (the exported output was already generated during `next build`).
However, this PR ensures that `next export -o <dir>` throws an error when `output: export` is defined because the files were already emitted to the `distDir` in the `next build` step and we can't safely no-op at this point.
We also guide the user to the correct solution which is to use `output: export` along with `distDir: <dir>` in your next.config.js (instead of mixing legacy behavior with the new behavior).
fix#48207
fix NEXT-980
Follow up for #50548
There're some packages like `aws-sdk-js-v3` which doesn't have a exports field yet:
```
"main": "./dist-cjs/index.js",
"types": "./dist-types/index.d.ts",
"module": "./dist-es/index.js",
```
This PR let u pick up by the js assets based on main fields, will prefer `"module"` field instead of `"main"`
Closes NEXT-1286
Add a `NEXT_CPU_PROF` environment variable to programmatically profile CPU for the router worker and two render workers. This is helpful because the `--cpu-prof` isn't reliably writing the result (#27406) especially with our multi-process architecture.
![CleanShot-2023-06-12-GS9p3SbN@2x](https://github.com/vercel/next.js/assets/3676859/b7cf80d2-a35a-4e90-978d-dec70be89f90)
### What?
* enable turbopack tests in new CI
* split pre-build step into native and JS builds to allow to start
native tests faster
* update swc_core to sync with turbo
* update turbopack
### Why?
Running our test suite is still important as long we don't have the full
integration test suite enabled.
### Turbopack updates
* https://github.com/vercel/turbo/pull/5215 <!-- OJ Kwon - ci(workflow):
upload benchmark results to datadog -->
* https://github.com/vercel/turbo/pull/5239 <!-- OJ Kwon -
fix(swc_plugin): use shared runtime -->
* https://github.com/vercel/turbo/pull/3090 <!-- CHEN Yuan - Docs: prior
to run testcases, add guides to install dependencies for testcases. -->
* https://github.com/vercel/turbo/pull/5264 <!-- Tobias Koppers - update
test runner -->
---------
Co-authored-by: JJ Kasper <jj@jjsweb.site>
Adding a `_rsc` query for RSC payload requests so that they can be
differentiated on resources level for CDN cache for the ones that didn't
fully respect to VARY header.
Also stripped them for node/edge servers so that they won't show up in
the url
x-ref:
https://github.com/vercel/next.js/pull/49140#issuecomment-1549405009Closes#49140
Closes NEXT-1268
This is a temporary fix before we can ship #51018 (more details there). If there're multiple chunk groups holding the same CSS module, we use files from the first one. This has some flaws but still better than our current status.
Like how we handled RSC loader transform before, we also apply swc
loader to middleware to make sure the imports optimization is applied so
og package won't be bundled
Fixes#50492
### What?
When `verbatimModuleSyntax: true` is set, `isolatedModules: true` are not allowed by TS
### Why?
Next always adds `isolatedModules: true` which causes TS error.
### How?
- Fixes#46509
fix NEXT-689
Co-authored-by: Steven <229881+styfle@users.noreply.github.com>
There are some incoming docs / MDX changes where prettier will throw an error when using the older version. Updating prettier before I bring in those changes.
Looks like the most notable change is adding parentheses around `typeof` checks in TypeScript.
**Before**
```
export type Locale = typeof i18n['locales'][number]
```
**After**
```
export type Locale = (typeof i18n)['locales'][number]
```
We need to spread the module into an object instead of access the module exports that could not exist, to avoid triggering the warning. Fix the bad loader change introduced in #50548
```
Attempted import error: './middleware.js' does not contain a default export (imported as '
mod').
- info Using locally built binary of @next/swc
- warn You are using an experimental edge runtime, the API might change.
- wait compiling...
- warn ../../../../packages/next/dist/build/webpack/loaders/next-middleware-loader.js?abso
lutePagePath=%2FUsers%2Fhuozhi%2Fworkspace%2Fnext.js%2Ftest%2Fe2e%2Fapp-dir%2Fapp%2Fmiddle
ware.js&page=%2Fmiddleware&rootDir=%2FUsers%2Fhuozhi%2Fworkspace%2Fnext.js%2Ftest%2Fe2e%2F
app-dir%2Fapp&matchers=!
Attempted import error: './middleware.js' does not contain a default export (imported as '
mod').
- wait compiling...
```
Manifests tend to be really big and our strategy is to inline them in the edge function script itself and we're hitting some constraints this way.
This PR switches this behaviour via inlining the script and creating a JS object at runtime instead, with the hope that the parsing time will be faster as JSON.parse is very well optimised in V8.
The end goal ofc is to have smaller manifests but this should be a good stopgap.
link NEXT-1273
Encode the state tree where the content could contain unicode when
request the RSC payload, to avoid the fetch failure due to bad encoding
for headers
Fixes#48728
fix NEXT-1258
After enabling Draft Mode, `router.refresh()` was incorrectly causing the page to crash and do a full page refresh.
This PR fixes this case.
Co-authored-by: Steven <229881+styfle@users.noreply.github.com>
Instead of using azAvgWidth for next/font/google, use xWidthAvg as the webpack implementation does. For now, next/font/local in both the webpack and Turbopack implementations continue to use azAvgWidth. We should align these in the future.
Test Plan: We now pass 26 next/font tests in Turbopack, up from 22.
To resolve issue #49382, we found layer doesn't get applied for dynamic imports, so we fixed it on webpack side in https://github.com/webpack/webpack/pull/17310
This PR is to upgrade webpack to 5.86.0 with that patch as a precedence. After this we need to fix the `next/image` client components is missing in client reference manifest when using dynamic imports to fix the issue.
This is an optimization to make the plugin faster, we're currently doing
redundant work `getAppPathRequiredChunks()` for all modules during
`recordModule()` while it's not changing.
For RSC server layer so far we bundle all dependencies, ESM format is the better one rather than CJS to analyze and tree-shake out the unused parts. This PR changes pick the condition names that are in ESM format first for server layer.
Also fixes the misorder of condition names of edge runtime, `conditionNames` should only contain either ESM or CJS, previously the main fields are mixed with conditon names which is not expected for webpack, we separate them now.
Since we're picking ESM instead CJS now, the error of require `exports * from` doesn't exist anymore, but if you're using a CJS dependency which require a ESM package, it will error. This is the existing behavior for our webpack configuration but could happen on server layer bundling
Other related changes:
* Imports are hoisted in ESM, so migrate`enhanceGlobals` to a imported module
* Use `...` to pick the proper imports by import expression, and prefer the `react-server` / `edge-light` condition names for corresponding cases
* Remove edge SSR duplicated `middleware` export checking