### What?
* add support for middleware manifest and edge adapter for pages API
routes
* improve the error reporting a tiny bit
### Why?
### How?
Closes WEB-1428
When `fallback: false` is set and you visit a dynamic segment (e.g. `/[slug]`), the router server was getting stuck in a `x-no-fallback` loop and eventually would fail because it was matching the output at `check_fs` before attempting to resolve dynamic routes in the `check: true` block.
Closes NEXT-1557
This is the first step to enable the automatic "modularize imports"
optimization for some libraries. It transforms named imports like
`import { A, B, C as F } from 'foo'` to a special loader string: `import
{ A, B, C as F } from "barrel-optimize-loader?names=A,B,C!foo"`.
In a follow-up PR we'll apply corresponding optimization with another
SWC transformer.
### What
When the global `window.Promise` is proxied, things that rely on custom Promise properties (e.g. the `status` field) break. In the case of navigation events, the prefetch cache is never identified as being fulfilled, so navigation hangs in an infinite loop.
### How?
This ensures that the value being stored in the prefetch cache have the expected Promise signature even when proxied.
x-ref: https://github.com/vercel/next.js/discussions/53746
[slack x-ref](https://vercel.slack.com/archives/C03S8ED1DKM/p1692626697034029)
This fixes a `CurCacheHandler is not a constructor` error when the custom cache handler path is transpiled from ESM -> CJS (resulting in the handler being attached to the `default` property on the module's exports)
Closes NEXT-1558
Fixes#54453
This removes the client-side polling logic that we're doing on every HMR
tick in favor of events like `addedPage` / `removedPage`. It was leading
to a lot of misc issues & confusion surrounding error/404 pages being
polled needlessly.
Instead this updates `addedPage` / `removedPage` to be emitted on the
server, so that we can leverage those hooks to reload when necessary.
Fixes#10024Fixes#51132
Closes NEXT-1372
related discussion: https://github.com/vercel/next.js/discussions/40000
---------
## 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
Follow up for #54202, use swc AST to determine the directives. Also add server actions directives for extendibility here in case we might need it in the future
Closes NEXT-1538
For the server compilation, we currently transpile the dynamic import
expression to `null` if `ssr` is disabled. However to make the Server
Actions layer work (as it can be created again from a Client Component),
we can't do that optimization.
This PR changes it to always keep that import expression when
`react_server_components` (App Router) is enabled, no matter which layer
it's on.
Closes#52672.
### What?
Let Next.js enable React Strict Mode by default for the App Router.
This caught a bug with the `AppRouterAnnouncer` added in #47018 which
should be fixed as well.
### Why?
This logic:
a0d1d728b9/packages/next/src/build/webpack-config.ts (L326-L333)
assumes that the default value of `reactStrictMode` is `null`, but it
was set to `false` in #46656.
### How?
This PR reverts the default value to `null`.
Closes NEXT-1484
Fixes#53315
---------
Co-authored-by: Tim Neutkens <tim@timneutkens.nl>
Previously we were appending the data routes to the dynamic routes array
which didn't ensure the data routes come before the normal dynamic
routes allowing a catch-all to override the data route.
Fixes: https://github.com/vercel/next.js/issues/53887
This PR merges the app renderer worker into the router process. This
improves the memory overhead mostly.
There're future work to do to get rid of the IPC server for router and
app renderer, as they're now merged in one process.
Fixes NEXT-1492
This ensures we properly populate locale information with `skipMiddlewareUrlNormalize` enabled as we shouldn't provide incorrect values even if we are skipping normalizing.
Fixes: https://github.com/vercel/next.js/issues/53646
A long-running server action shouldn't block page navigation. This makes use of a global mutable to detect when a navigation event occurs -- this change will unblock other reducers (such as navigation).
If we bailed on the action, we trigger a `router.refresh()` to ensure any side effects from the action are refetched.
Closes NEXT-1131
Fixes#49425
in #54059 the nonce attribute was added to preinitialized scripts to when using this CSP directive. The test added asserts there is at least one script that has the nonce attribute. I've changed this to 2 because currently our builds produce at least two "main" scripts, the main chunk and the webpack runtime. The way we bootstrap there is always exactly one bootstrap script which means if we only assert that there is one script with a nonce we might not be asserting anything about the preinit script path. If we ever update our webpack config to produce a single main script this test will fail but we should never do that (it's bad for caching) and so it shouldn't happen and if it does it will hopefully force us to consider if we're making a mistake
Additionally I've added another test that is more e2e. it asserts that the page bootstraps even when using CSP (in prod). In Dev it asserts the CSP attributes but it expects the bootstrap to fail because our dev mode violates the CSP directive with eval.
Fixes#54055.
A bug recently introduced in https://github.com/vercel/next.js/pull/53705 made it so that we were now preinitializing some of our scripts slightly better, but in doing so, we failed to pass in a nonce. This broke nonce-based CSP usage. The fix was to add the `nonce` to our `ReactDOM.preinit` calls.
Manual testing shows that this change fixes the error and the nonce is now passed in as expected.
Co-authored-by: Dan Ott <360261+danieltott@users.noreply.github.com>
This PR changes the heuristic in the client cache to only check and show the prefetched data when it was prefetched or last read 30s ago vs keeping it around as long as it was accessed within 30s.
### What & Why
Add base path handling for the url in redirect error if the `basePath` is configured.
This is only break for server rendering case as the `basePath` is missing in the `Location` header. When running `next build`, everything is managed well with app router and base path on client side so it didn't break.
### How
Adding `basePath` if it's presented for `Location` header.
Update the `RenderOpts` type as basePath is already passed down in it, also update them for turbopack entries
Fixes#54163
Closes NEXT-1529
### 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
In the past few rounds of improving metadata image routes bundling, we have improved the bundling strategy and also updated [the usage tutorial of using custom fonts in og image routes](https://vercel.com/docs/functions/edge-functions/og-image-generation/og-image-examples) which should load the font in the image route handler.
Adding some tests to ensure custom fonts are working with metadata
Closes#48081
This fixes the compilation of `export { action as renamed }` syntax. Previously it's compiled as `export var action = ...` and with this fix, it will be `export var renamed = ...`.
Closes#54229.
Image Optimization API currently does not work if a custom loaderFile is specified in next.config.js, even if loader is explicitly set to 'default', because it is currently being overridden to 'custom' simply because a loaderFile is specified. This is unnecessary and causing the Image Optimization API routes not to be initialized since the change to the config happens before the routes are initialized.
[Sandbox Reproduction](https://codesandbox.io/p/sandbox/purple-pine-t7hhgl?file=%2Fimage-loader.js%3A8%2C1)
- Fixes#53415
For group routes, unlike normal routes, the root layout is located in the "group"'s segment instead of root layer.
To make it also able to leverage the default not found error component as root not found component, we need to determine if we're in the root group segment in the loader tree, and add the not-found boundary for it.
If you compre the loader tree visually they will look like this:
Normal route tree structure
```
['',
{ children: [segment, {...}, {...}]},
{ layout: ..., 'not-found': ... }
]
```
Group routes
```
[''
{ children: ['(group)', {...}, { layout, 'not-found': ... }]}
{}
]
```
Comparing to normal case, we go 1 layer down in the tree for group routes, then insert the not-found boundary there
Fixes#52255
Closes NEXT-1532
### What?
When running Next in standalone mode, `process.env` is not made
available to the render workers, making it impossible to access
environment variables that aren't provided in `.env` files.
### Why?
`initialEnv` is undefined in `createWorkers` when the server is started
in standalone mode.
### How?
This initializes the workers with `process.env` in case `initialEnv` is
unavailable, similar to the behavior of `loadEnvConfig()`
Closes NEXT-1508
Fixes#53367
Follow up to https://github.com/vercel/next.js/pull/54081 -- this was
restoring the router tree improperly causing an error on bfcache hits
Had to override some default behaviors to prevent `forward` / `back` in
playwright from hanging indefinitely since no load event is firing in
these cases
Fixes#54184
Closes NEXT-1528
Fixes#54174
We should only add default not-found boundary to loader tree components for root layout. It was accidently added for children routes before
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?
When cloning a `Request` with `NextRequest` the second argument needs to take precedence over the `Headers` set on the original request.
### Why?
Follow-up of #53157
I checked the `Request` spec https://fetch.spec.whatwg.org/#request-class and following the order of execution, `init.headers` should indeed override the headers if the first param was `Request`.
I verified this in the browser too:
```js
const req1 = new Request("http://n", {headers: {"x-header": "foo"}})
const req2 = new Request(req1, {headers: {"x-header-2": "bar"}})
Object.fromEntries(req2.headers) // {x-header-2: "bar"}
```
So we should match `NextRequest` with this behavior.
### How?
Pass the `init` to `super` when cloning the request.
Closes NEXT-1521
Fixes#54094
When an mpa navigation takes place, we currently push the user to the new route and suspend the page indefinitely (x-ref: #49058). When navigating back, if the browser opts into using the [bfcache](https://web.dev/bfcache/), it will remain suspended and `pushRef.mpaNavigation` will be true. This means that anything that would cause the component to re-render will trigger the mpa navigation again (such as hovering over another `Link`, as reported in #53347)
This PR checks to see if bfcache is being used by observing `PageTransitionEvent.persisted` and if so, resets the router state to clear out `pushRef`.
Closes NEXT-1511
Fixes#53347
### What & Why
Previously when rendering the root `/_not-found` in production, we'll always override the parallel routes component children with not-found component, this will break the navigation in build mode from root 404 `/_not-found` path.
### How
The new solution is to change the root `/_not-found` rendering strategy. Previously the loader tree of `/_not-found` look like this
```js
['',
{
children: ['not-found', {}, {}]
},
{ layout: ..., 'not-found': ...}
]
```
it's not a pretty valid tree, which could lead to problems during rendering.
New solution is to change the children to render a page, but the page content is `not-found.js` component. The new tree of root not-found will look like
```js
['',
{
children: ['__PAGE__', {}, {
page: ... // same as root 'not-found'
}]
},
{ layout: ..., 'not-found': ...}
]
```
This change could fix the navigation on the root not-found page.
Fixes#52264
### 🧐 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>
### What?
When navigating to a new page with fixed or sticky positioned element as the first element, we were bailing on scroll to top behavior, which often isn't expected.
### Why?
Currently, we decide to bail on scroll to top behavior on navigation if the content that is swapped into view is visible within the viewport. Since fixed/sticky positioned elements are often intended to be relative to the current viewport, it's most likely not the case that you'd want it to be considered in this heuristic. For example, if you were scrolled far down on a page, and you navigated to a page that makes use of a sticky header, you would not be scrolled to the top of the page because that sticky header is technically visible within the viewport.
### How?
I've updated the previous implementation that was intended to skip targeting invisible elements to also skip over fixed or sticky elements. This should help by falling back to the next level of the layout tree to determine which element to scroll to.
I've deleted the `// TODO-APP` comments as I couldn't think of a scenario in which we'd need a global scrollTop handler -- if we've bailed on every element up the tree, it's likely the page wasn't scrollable.
Some additional considerations:
- Is the warning helpful or annoying?
- Is the parallel route trade-off an acceptable one? (ie, a parallel modal slot might not be considered in the content visibility check unless if it’s fixed positioned)
Closes NEXT-1393
Fixes#47475
### What?
Skip logging `/404` for pages routes in `next build` when app router root not-found is present
### Why?
When app router's root not-found is used it can cover all the not found cases, and for static rendering it can already replace the `404.html`. So in the tree view we don't need to log the pages `/404` when those cases are covered by app router.
`getEntryKey` had some logic to remove `children` if it was part of the entry (originally it was intended to fix an issue with parallel slots that were used in place of a page, but wasn't working as intended). However, this breaks pages that are named `children`.
Updating this again to implement what I think was the intended behavior in 4900fa21b0 which is to point to the correct entry when a parallel slot is used in place of a page component.
- x-ref: #52362
Closes NEXT-1514
Fixes#53072
Partial fix for #54012: do not generate a blur image in the image loader when the image is detected to be animated, rather than returning the *entire* animated image as the blur image.