Reverts vercel/next.js#57154
Brings back the changes but uses the compiled version of async-retry instead. Previously these changes causes an error as async-retry wasn't installed.
### What?
Use [Turborepo generators](https://turbo.build/repo/docs/core-concepts/monorepos/code-generation#custom-generators) instead of plop.
Turborepo generators are built on top of plop, but include some additional tooling to make working in monorepos easier. It also supports zero config typescript for configs.
### Why?
Same Team!
### How?
Ported the existing plopfile to a turbo generator config
Co-authored-by: Jiachi Liu <4800338+huozhi@users.noreply.github.com>
### What?
Update SWC crates. This PR fixes a regression of `swc_core`.
The important PR: https://github.com/swc-project/swc/pull/8153
### Why?
There was a regression in `swc_core`.
### How?
- Fixes#56408
Closes WEB-1811
---------
Co-authored-by: Tobias Koppers <tobias.koppers@googlemail.com>
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>
### What?
Add the same re-retrieval process for subseted font files of Google Font as for CSS files.
+ make use of [async-retry](https://github.com/vercel/async-retry)
### Why?
It was reported in #45080 that Japanese fonts such as Noto Sans JP were frequently `Failed to fetch`.
A retry process was added in #51890, but it did not resolve the issue completely ( https://github.com/vercel/next.js/pull/51890#issuecomment-1614558064 ).
Here is my reproduction code with 13.5.5-canary.4 (please run locally).
https://stackblitz.com/edit/stackblitz-starters-n8zxlq?file=app%2Fpage.tsx
<details>
<summary>And my local error log is here(folded)</summary>
```
$ npm run -- dev
> nextjs@0.1.0 dev
> next dev
⚠ Port 3000 is in use, trying 3001 instead.
▲ Next.js 13.5.5-canary.4
- Local: http://localhost:3001
✓ Ready in 23.9s
○ Compiling /page ...
FetchError: request to https://fonts.gstatic.com/s/notosansjp/v52/-F6jfjtqLzI2JPCgQBnw7HFyzSD-AsregP8VFBEj757Y0rw_qMHVdbR2L8Y9QTJ1LwkRmR5GprQAe69m.4.woff2 failed, reason:
at ClientRequest.<anonymous> (/mnt/c/Users/berlysia/Downloads/stackblitz-starters-n8zxlq/node_modules/next/dist/compiled/node-fetch/index.js:1:65756)
at ClientRequest.emit (node:events:514:28)
at TLSSocket.socketErrorListener (node:_http_client:495:9)
at TLSSocket.emit (node:events:514:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
type: 'system',
errno: 'ETIMEDOUT',
code: 'ETIMEDOUT'
}
⨯ Failed to download `Noto Sans JP` from Google Fonts. Using fallback font instead.
Failed to fetch `Noto Sans JP` from Google Fonts.}
FetchError: request to https://fonts.gstatic.com/s/notosansjp/v52/-F6jfjtqLzI2JPCgQBnw7HFyzSD-AsregP8VFBEj757Y0rw_qMHVdbR2L8Y9QTJ1LwkRmR5GprQAe69m.28.woff2 failed, reason:
at ClientRequest.<anonymous> (/mnt/c/Users/berlysia/Downloads/stackblitz-starters-n8zxlq/node_modules/next/dist/compiled/node-fetch/index.js:1:65756)
at ClientRequest.emit (node:events:514:28)
at TLSSocket.socketErrorListener (node:_http_client:495:9)
at TLSSocket.emit (node:events:514:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at processTicksAndRejections (node:internal/process/task_queues:82:21)
at runNextTicks (node:internal/process/task_queues:64:3)
at listOnTimeout (node:internal/timers:540:9)
at process.processTimers (node:internal/timers:514:7) {
type: 'system',
errno: 'ETIMEDOUT',
code: 'ETIMEDOUT'
}
...(15 errors emitted)
```
</details>
I've found that the issue is not limited to fetching CSS, fetching subset font files is also failing.
By adding retry handling to the fetch of individual subseted font files as well, I (almost) never see `Failed to fetch` anymore.
The issue tends to become more apparent when downloading a larger number of subsetted fonts.
This suggests that the problem is more likely to occur with larger fonts, such as those designed for CJK languages.
### How?
Add the same re-retrieval process for subseted font files of Google Font as for CSS files.
Related to #51890#53239#45080#53279
### 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.
### 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
Upgraded dotenv to v16. Breaking changes are:
- Multiline parsing support
- Support inline comments
- Backtick support
[See their changelog](https://github.com/motdotla/dotenv/blob/master/CHANGELOG.md)
## Feature
- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [x] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`
Co-authored-by: Balázs Orbán <18369201+balazsorban44@users.noreply.github.com>
### What?
Step 3 in our chunking refactors extracts ChunkItem::as_chunk into a new ChunkType trait. This new trait isn't useful yet, but will eventually allow us to collect ChunkItems of a similar type into a lists, and perform chunking over all similar items at once.
### Why?
In the end we want to avoid creating chunks from modules directly, but enforce everything going through the ChunkingContext to be chunked. This allows us to replace the existing chunking algorithm with a much more efficient one that avoid duplication between chunks in first place and doesn't require a post-chunking optimization.
### How?
https://github.com/vercel/turbo/pull/6123
Re: https://github.com/vercel/next.js/pull/56504
Closes WEB-1724
Co-authored-by: Tobias Koppers <1365881+sokra@users.noreply.github.com>
### What?
The second step in our chunking refactoring, this removes our use of Module::as_chunk and Module::as_root_chunk. Instead, the only way to generate a chunk is directly from a root ChunkItem.
### Why?
In the end we want to avoid creating chunks from modules directly, but enforce everything going through the ChunkingContext to be chunked. This allows us to replace the existing chunking algorithm with a much more efficient one that avoid duplication between chunks in first place and doesn't require a post-chunking optimization.
### How?
https://github.com/vercel/turbo/pull/6120
Re: https://github.com/vercel/next.js/pull/56467
Closes WEB-1721
Co-authored-by: Tobias Koppers <1365881+sokra@users.noreply.github.com>
### What?
This change moves a few methods around.
Module::as_chunk is moved to ChunkItem::as_chunk as temporary intermediate state.
EcmascriptPlaceable::as_chunk_item is moved to ChunkableModule::as_chunk_item. This generalizes the concept of converting a Module into a ChunkItem
### Why?
This is the first step of refactoring the chunking. In the end we want to avoid creating chunks from modules directly, but enforce everything going through the ChunkingContext to be chunked. This allows us to replace the existing chunking algorithm with a much more efficient one that avoid duplication between chunks in first place and doesn't require a post-chunking optimization.
### How?
see https://github.com/vercel/turbo/pull/6104
Closes WEB-1715
Co-authored-by: Justin Ridgewell <112982+jridgewell@users.noreply.github.com>
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.
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
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.
Depends on vercel/turbo#6036
This constructs a general asset prefix (depending on if basePath and/or assetPrefix is defined), and sets it on Next's and Turbopack's chunking context.
Test Plan: Use a `create-next-app` with corresponding Next.js PR and basePath and assetPrefix specified.
Tested:
- Browser (async) chunk loading
- Static asset loading on server and browser
Closes WEB-1666
**TL; DR**
The PR updates the `jest-worker` to the latest `@27` (which is `jest-worker@27.5.1`) and pre-compile.
---
I use `config.experimental.workerThreads` for my personal website built with Next.js, and I noticed that the react alias (from `require-hook`) is not working, causing `react-dom-server-webpack/client.edge` to fail to resolve.
So I modify the `node_modules/next/dist/build/worker.js` in my personal website project folder to print `process.env.__NEXT_PRIVATE_PREBUNDLED_REACT`:
<img width="761" alt="image" src="https://github.com/vercel/next.js/assets/40715044/f22d72f8-ffd4-49d0-831a-ee3bfd0513ca">
To my surprise, the `process.env.__NEXT_PRIVATE_PREBUNDLED_REACT` prints `undefined` with `config.experimental.workerThreads: true`:
<img width="760" alt="image" src="https://github.com/vercel/next.js/assets/40715044/ad8add14-7ac3-45f5-8f1e-2fec18397410">
But If I disable worker threads with `config.experimental.workerThreads: false`, the `process.env.__NEXT_PRIVATE_PREBUNDLED_REACT` is passed down correctly.
So I dig a little deeper. It turns out to be an old issue of `jest-worker` and has been fixed in https://github.com/jestjs/jest/pull/12069 (in that PR, the custom `env` was passed down to `jest-worker`'s `forkOption`). The bugfix was released in `jest-worker@27.4.0`, but Next.js is still using `jest-worker@27.0.0-next.5`, hence the issue.
We've rearchitected Next.js+Turbopack so Turbopack does not run
reimplement pieces of Next.js in its devserver. This:
- Removes the `next-dev` binary, which is no longer reachable through
`next --turbo`.
- Removes its test suite, as much of it is tested (and often more
thoroughly) by the Next.js test suite
- Removes its benchmark suite, which should be covered by
`Turbopack-bench` by
https://github.com/vercel/turbo/tree/main/crates/turbopack-bench
Test Plan: CI
Closes WEB-1652
### What?
I made `styled-jsx` configurable. It uses `swc_css` by default, and with
`useLigntningcss: true`, it uses it.
https://github.com/swc-project/plugins/pull/207
### Why?
### How?
Closes NEXT-
Fixes #
Closes WEB-1532
### 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.
### What?
Upgrade TypeScript to the latest version as of this PR. **This does not affect users, as the change is only for our repository.**
### Why?
Part of some upcoming PRs to try to clean up cookie handling, now that `getSetCookie` is available. Since we use `undici`, which [implements it](https://github.com/nodejs/undici/pull/1915), we can get rid of some code to rely more on the platform.
This PR is needed to get the types for `Headers#getSetCookie` which was added in 5.2
### How?
I needed to update some dependency types to get build to pass, but other than that, only needed to bump from `5.1.6` to `5.2.2`, so hopefully all is fine.
## What?
In Next, rendering a route involves 3 layers:
- the routing layer, which will direct the request to the correct route to render
- the rendering layer, which will take a route and render it appropriately
- the user layer, which contains the user code
In #51831, in order to optimise the boot time of Next.js, I introduced a change that allowed the routing layer to be bundled. In this PR, I'm doing the same for the rendering layer. This is building up on @wyattjoh's work that initially split the routing and the rendering layer into separate entry-points.
The benefits of having this approach is that this allows us to compartmentalise the different part of Next, optimise them individually and making sure that serving a request is as efficient as possible, e.g. rendering a `pages` route should not need code from the `app router` to be used.
There are now 4 different rendering runtimes, depending on the route type:
- app pages: for App Router pages
- app routes: for App Router route handlers
- pages: for legacy pages
- pages api: for legacy API routes
This change should be transparent to the end user, beside faster cold boots.
## Notable changes
Doing this change required a lot of changes for Next.js under the hood in order to make the different layers play well together.
### New conventions for externals/shared modules
The big issue of bundling the rendering runtimes is that the user code needs to be able to reference an instance of a module/value created in Next during the render. This is the case when the user wants to access the router context during SSR via `next/link` for example; when you call `useContext(value)` the value needs to be the exact same reference to one as the one created by `createContext` earlier.
Previously, we were handling this case by making all files from Next that were affected by this `externals`, meaning that we were marking them not to be bundled.
**Why not keep it this way?**
The goal of this PR as stated previously was to make the rendering process as efficient as possible, so I really wanted to avoid extraneous fs reads to unoptimised code.
In order to "fix" it, I introduced two new conventions to the codebase:
- all files that explicitly need to be shared between a rendering runtime and the user code must be suffixed by `.shared-runtime` and exposed via adding a reference in the relevant `externals` file. At compilation time, a reference to a file ending with this will get re-written to the appropriate runtime.
- all files that need to be truly externals need to be suffixed by `.external`. At compilation time, a reference to it will stay as-is. This special case is needed mostly only for the async local storages that need to be shared with all three layers of Next.
As a side effect, we should be bundling more of the Next code in the user bundles, so it should be slightly more efficient.
### App route handlers are compiled on their own layer
App route handlers should be compiled in their own layer, this allows us to separate more cleanly the compilation logic here (we don't need to run the RSC logic for example).
### New rendering bundles
We now generate a prod and a dev bundle for:
- the routing server
- the app/pages SSR rendering process
- the API routes process
The development bundle is needed because:
- there is code in Next that relies on NODE_ENV
- because we opt out of the logic referencing the correct rendering runtime in dev for a `shared-runtime` file. This is because we don't need to and that Turbopack does not support rewriting an external to something that looks like this `require('foo').bar.baz` yet. We will need to fix that when Turbopack build ships.
### New development pipeline
Bundling Next is now required when developing on the repo so I extended the taskfile setup to account for that. The webpack config for Next itself lives in `webpack.config.js` and contains the logic for all the new bundles generated.
### Misc changes
There are some misc reshuffling in the code to better use the tree shaking abilities that we can now use.
fixes NEXT-1573
Co-authored-by: Alex Kirszenberg <1621758+alexkirsz@users.noreply.github.com>
This bumps `undici` to the latest version to match the one used in newer Node.js versions', potentially fixing compatibility issues.
I also cleaned up some related `global as any` usage.
by @jridgewell:
### What?
This integrates Turbopack's HRM protocol within the existing HMR
WebSocket, and implements the server-side of the Next's and Turbopack's
protocols for use in next-api.
### Why?
HMR makes the development experience.
### How?
The (new) Turbopack HMR protocol allows reusing the existing
`sendMessage` and `addMessageListener` API's already used by our HMR
singleton in Pages. (App apparently doesn't have a per-chunk HMR, only
per-page, so it's HMR signals are describe below.)
For the next-api server-side, I implemented the following events:
- `reloadPage`, for Pages when `_document` changes
- `middlewareChanges` when middleware is added/deleted, or modified
- `serverOnlyChanges` for Pages when a loaded page's server graph
changes
- `serverComponentChanges` for App when a loaded app page's server graph
changes
We reuse the already implemented `addedPage`, `removedPage`, and
`devPagesManifestUpdate` (done via webpack, so we should eventually port
that over to the Turbopack listeners).
I don't know exactly where `built`, `building`, and `sync` should be
integrated, so they're just not sent currently. Additionally, the
client-sent events aren't implemented in the new HMR server.
Depends on https://github.com/vercel/turbo/pull/5814
Closes WEB-1453
---------
Co-authored-by: Justin Ridgewell <justin@ridgewell.name>
## What
Adds a reworked version of webpack's [built-in memory cache garbage
collection
plugin](853bfda35a/lib/cache/MemoryWithGcCachePlugin.js (L15))
that is more aggressive in cleaning up unused modules than the default.
The default marks 1/5th of the modules as "up for potentially being
garbage collected". The new plugin always checks all modules. In my
testing this does not cause much overhead compared to the current
approach which leverages writing to two separate maps. The change also
makes the memory cache eviction more predictable: when an item has not
been accessed for 5 compilations it is evicted from the memory cache, it
could still be in the disk cache.
In order to test this change I had to spin up the benchmarks but these
were a bit outdated so I've cleaned up the benchmark applications.
---------
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
### Problem
One style of `not-found` has `precendence` property with "undefined" value, which can't be handled by React Float, then during navigation the style could not load properly, lead to the style missing in issue #53210.
### Solution
Always enable `precendence` for all links, so all the css styles of page and convention components can be hoist by react properly. Float will decide which one should be handled. Previously this change only applies to template, actually we can apply it to all components so that they can all be handled properly especially during client navigation.
Related react change: https://github.com/facebook/react/pull/27265Fixes#53210
### What & Why
emotion-js has its own [jsx transform](https://emotion.sh/docs/typescript#emotionreact) which is being applied when `compiler.emotion` is enabled in `next.config.js`.
Thanks to emotion-js team that provided an emotion-js example setup with app router [here](https://github.com/emotion-js/emotion/issues/2928#issuecomment-1319792703), so that we can use it as test example with app router. Based on the setup, we create a test case working with emotion js but failed with error mentioned in #41994 that some client hooks appearing in server components. That is because the emotion-js jsx factory includes some client hooks.
### How
For server components, css-in-js is not recommended to apply so we disabled the transform before, the emotion jsx factory is a separate config that should also not be applied in server components. So in this case we still use react jsx factory instead of the emotion-js one for server components then it won't error. The test case can also be used as an example for basic emotion-js use case with app router.
Fixes#41994
Closes NEXT-1368
Fixes#52365
In #52275 that eslint config changed to a fixed canary version to leverage the improvement of `react-hooks` eslint plugin but breaks the installation when 3rd party packages having strict matching for certain version of eslint plugin.
This PR allows both previous version and the canary version be present.
### What?
Strip the relative path prefix (`_next/`) when generating the `PageLoaderAsset`. This is necessary because the page loader will internally use `__turbopack_load__`, which prepends the prefix back onto the path.
### Why?
Without this, we'd try loading `_next/_next/path/to/file.js`, because we'd prepend the prefix onto a path that already contains it.
### How?
When generating the page loader asset, we "proxy" the `OutputAsset` onto a path which has the prefix removed.
~~Depends on https://github.com/vercel/turbo/pull/5717~~
Closes WEB-1377
Reverts vercel/next.js#53578
This PR (#53578) will break client components test, revert it for now.
Can repro by adding `"use client"` to `app/page.tsx` in `test/production/jest/server-only.test.ts`
```
FAIL app/page.test.jsx
● Test suite failed to run·
Cannot find module 'private-next-rsc-mod-ref-proxy' from 'app/page.jsx'·
Require stack:
```
### 🧐 What's in there?
This is another attempt to allow testing server-only code with Jest.
### 🧪 How to test?
There's an integration tests which can be triggered with `pnpm testheadless server-only`
Here is a more comprehensive setup:
<details>
<summary><code>app/lib/index.ts</code></summary>
```ts
import 'server-only'
export function add(num1: number, num2: number) {
return num1 + num2
}
```
</details>
<details>
<summary><code>app/lib/index.test.ts</code></summary>
```ts
import { add } from '.'
it('adds two numbers', () => {
expect(add(1, 3)).toEqual(4)
})
```
</details>
<details>
<summary><code>app/client-component.tsx</code></summary>
```ts
'use client'
import { useState } from 'react'
export default function ClientComponent() {
const [text, setText] = useState('not clicked yet')
return <button onClick={() => setText('clicked!')}>{text}</button>
}
```
</details>
<details>
<summary><code>app/client-component.test.tsx</code></summary>
```ts
import { fireEvent, render, screen } from '@testing-library/react'
import ClientComponent from './client-component'
it('can be clicked', async () => {
render(<ClientComponent />)
const button = screen.getByRole('button')
expect(button).toHaveTextContent('not clicked yet')
await fireEvent.click(button)
expect(button).toHaveTextContent('clicked!')
})
```
</details>
<details>
<summary><code>app/server-component.tsx</code></summary>
```ts
import { add } from '@/lib'
export default function ServerComponent({ a, b }: { a: number; b: number }) {
return (
<code role="comment">
{a} + {b} = {add(a, b)}
</code>
)
}
```
</details>
<details>
<summary><code>app/server-component.test.tsx</code></summary>
```ts
import { render, screen } from '@testing-library/react'
import ServerComponent from './server-component'
it('renders', () => {
render(<ServerComponent a={2} b={3} />)
expect(screen.getByRole('comment')).toHaveTextContent('2 + 3 = 5')
})
```
</details>
<details>
<summary><code>app/page.tsx</code></summary>
```ts
import Link from 'next/link'
import ClientComponent from './client-component'
import ServerComponent from './server-component'
export default function Page() {
return (
<>
<h1>Hello World</h1>
<Link href="/dave">Dave?</Link>
<p>
<ClientComponent />
</p>
<p>
<ServerComponent a={5} b={2} />
</p>
</>
)
}
```
</details>
<details>
<summary><code>app/page.test.tsx</code></summary>
```ts
import { render, screen } from '@testing-library/react'
import Page from './page'
it('greets', () => {
render(<Page />)
expect(screen.getByRole('link')).toHaveTextContent('Dave?')
expect(screen.getByRole('heading')).toHaveTextContent('Hello World')
expect(screen.getByRole('button')).toHaveTextContent('not clicked yet')
expect(screen.getByRole('comment')).toHaveTextContent('5 + 2 = 7')
})
```
</details>
<details>
<summary><code>app/[blog]/page.tsx</code></summary>
```ts
import { Metadata } from 'next'
import Link from 'next/link'
type Props = {
params: { blog: string }
}
export async function generateMetadata({
params: { blog: title },
}: Props): Promise<Metadata> {
return { title, description: `A blog post about ${title}` }
}
export default function Page({ params }: Props) {
return (
<>
<div>
<Link href="/">Back</Link>
</div>
<h1>All about {params.blog}</h1>
</>
)
}
```
</details>
<details>
<summary><code>app/[blog]/page.test.tsx</code></summary>
```ts
import { render, screen } from '@testing-library/react'
import Page from './page'
it('has the appropriate title', () => {
const title = 'Jane'
render(<Page params={{ blog: title }} />)
expect(screen.getByRole('heading')).toHaveTextContent(`All about ${title}`)
expect(screen.getByRole('link')).toHaveTextContent('Back')
})
```
</details>
<details>
<summary><code>app/layout.tsx</code></summary>
```ts
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
```
</details>
<details>
<summary><code>jest.config.js</code></summary>
```ts
const nextJest = require('next/jest')
const createJestConfig = nextJest({ dir: './' })
module.exports = createJestConfig({
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/test-setup.ts'],
})
```
</details>
<details>
<summary><code>package.json</code></summary>
```ts
{
"name": "rsc-test",
"version": "0.0.0",
"private": true,
"scripts": {
"test": "jest"
},
"devDependencies": {
"@testing-library/jest-dom": "latest"
}
}
```
</details>
<details>
<summary><code>test-setup.ts</code></summary>
```ts
import '@testing-library/jest-dom'
```
</details>
The app should run and all test should pass.
### ❗ Notes to reviewers
#### The problem:
1. next/jest configures jest with a transformer ([jest-transformer](https://github.com/vercel/next.js/blob/canary/packages/next/src/build/swc/jest-transformer.ts)) to compile react code with next -swc
2. the transformers configures next -swc for a given environment: Server or Client, based on jest global environment
3. Based on the environment, next -swc checks for invalid usage of `import('server-only')` `“use client”`, `export const metadata` or `export async function generateMetadata`
4. Because the global test environment is either jsdom or node, the same test suite can not include both client and server components
#### Possible mitigations
*A. Using jest projects*
When configured with [multiple projects](https://jestjs.io/docs/next/configuration/#projects-arraystring--projectconfig), Jest can launch different runners with different environment. This would allow running server-only code in node and client-only code in jsdom.
However, it requires user to completely change their jest configuration. It would also require a different setup when scaffolding new app-directory project with create-next.
*B. Using doc blocks*
Jest allows changing the environment per test file [with docBlock](https://jestjs.io/docs/configuration#testenvironment-string).
However, by the time jest is invoking next -swc on a source file to transform it, this information is gone, and next -swc is still invoked with the (wrong) global environment.
The PR #52393 provides a workaround for files with `import('server-only')`, but does not allow testing pages with metadata.
*C. Always compile for node*
Our jest-transformer could always configure next -swc for server:
- pass Server-specific validations `import('server-only')` `export const metadata` or `export async function generateMetadata`
- does not complain about `"use client"`
This is what this PR is about!
Fixes#47299
Co-authored-by: Jiachi Liu <4800338+huozhi@users.noreply.github.com>
Followup on the https://github.com/vercel/next.js/pull/52520. The enhancements:
1. Both `fetch` and `http(s)` APIs are intercepted in the testmode.
2. The loopback mode that would allow the test-side to use any fetch-mocking library of their choice.