Commit graph

4423 commits

Author SHA1 Message Date
Balázs Orbán
96a59344e8
fix(app): enable React Strict Mode by default (#53375)
### 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>
2023-08-22 20:17:17 +02:00
JJ Kasper
c89f97ea56
Fix data route ordering in dev (#54364)
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
2023-08-22 10:19:54 -07:00
Shu Ding
5584e5743a
Merge app renderer process (#54143)
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
2023-08-22 14:38:42 +02:00
Steven
f6d2aa09de
fix: minimum node version 16.14.0 (#54331)
- Fixes https://github.com/vercel/next.js/issues/54269
- Related to https://github.com/vercel/next.js/pull/54285
2023-08-22 08:58:53 +00:00
JJ Kasper
d54ed07b3c
Fix missing locale info for middleware data request (#54357)
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
2023-08-21 22:34:42 +00:00
Jiachi Liu
70231ef7cd
test: add case for marking _document with edge runtime (#54316)
Can't repro anymore, add a test case for issue 45189

Closes #45189
Closes NEXT-1396
2023-08-21 20:56:46 +00:00
JJ Kasper
0e91c79f57
Fix windows next-swc builds (#54353)
Fixes this build error on windows due to invalid path:

```sh
 Error: error: invalid path 'test/e2e/app-dir/app/app/bootstrap/[[...*]]/ClientComponent.js'
 Error: The process 'C:\Program Files\Git\cmd\git.exe' failed with exit code 128
```

x-ref:
https://github.com/vercel/next.js/actions/runs/5930602201/job/16080672888#step:7:62
2023-08-21 13:35:12 -07:00
Zack Tanner
892839ff83
fix: server actions blocking navigation events (#54307)
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
2023-08-21 20:34:42 +00:00
Josh Story
3370022ac2
add test case for CSP with bootstrap scripts and preinit modules (#54348)
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.
2023-08-21 18:49:21 +00:00
Steven
6773ea8636
fix: improve error message when output: export in app router (#54202)
There are a few cases that are not handled by App Router when using `output: export` config.

A few of them are expected, but some are yet to be implemented. Regardless of the intent of the future, this PR ensures the error messages match what was documented to be [unsupported](https://nextjs.org/docs/app/building-your-application/deploying/static-exports#unsupported-features).

- Documentation: https://github.com/vercel/next.js/pull/53592
- Issue: #48022
2023-08-21 14:45:00 +00:00
Nikhil Bhargava
24cd55c09f
Adds nonce to preinit scripts (#54059)
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>
2023-08-20 13:55:02 +00:00
Jimmy Lai
6aa07fb999
app-router: tweak prefetch cache status heuristics (#53864)
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.
2023-08-20 11:25:48 +00:00
Jiachi Liu
f2a3fd9fc3
Handle basePath for redirect() (#54277)
### 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
2023-08-20 03:32:52 +00:00
Jiachi Liu
311eea4c6a
Fix emotion-js transform for server components (#54284)
### 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
2023-08-20 03:14:16 +00:00
Jiachi Liu
85606472e4
Add test for using custom font in metadata image routes (#54274)
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
2023-08-19 14:29:18 +00:00
Zack Tanner
adc413b3fb
add experimental https support to next dev (#54016)
This adds an `--experimental-https` flag to `next dev` which will generate a self-signed certificate via [mkcert](https://github.com/FiloSottile/mkcert) and use it for the dev server.

also supports passing in pre-existing certs via `--experimental-https-cert` and `--experimental-https-key`

x-ref: https://github.com/vercel/next.js/discussions/33768 https://github.com/vercel/next.js/discussions/10935
2023-08-19 01:04:06 +00:00
Shu Ding
0e78798f37
Fix renamed export of Server Actions (#54241)
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.
2023-08-18 20:41:32 +00:00
David Goguen
a0749a5103
feat(image): add support for custom loaderFile when loader: default (#53417)
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
2023-08-18 20:05:17 +00:00
Jiachi Liu
c305bf6afb
Add default not found to loader tree of group routes root layer (#54228)
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
2023-08-18 16:56:55 +00:00
Zack Tanner
803bbe5c93
fix process.env not being available in standalone mode (#54203)
### 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
2023-08-18 16:04:48 +02:00
Kim In Seop
132d3e8f97
fix: invalid module transform for @headlessui/react (#54206)
occured since #54188

- `*`: use kebabcase instead of lowercase
- Transition: `components/transitions/transition`
- Tab: `components/tabs/tabs`

```plain
- wait compiling /not-found (client and server)...
- error ./node_modules/.pnpm/@headlessui+react@1.7.17_react-dom@18.2.0_react@18.2.0/node_modules/@headlessui/react/dist/headlessui.esm.js:2:0
Module not found: Can't resolve '/Projects/node_modules/.pnpm/@headlessui+react@1.7.17_react-dom@18.2.0_react@18.2.0/node_modules/@headlessui/react/dist/components/tab/tab'
```




Co-authored-by: Shu Ding <3676859+shuding@users.noreply.github.com>
2023-08-18 10:33:33 +00:00
Zack Tanner
c676f9357e
fix bfcache restoration behavior (#54198)
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
2023-08-18 00:05:26 +02:00
Jiachi Liu
e20c8c824c
Assign default not-found boundary if custom not-found is not present for root layer only (#54185)
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
2023-08-17 18:27:27 +00:00
Jiachi Liu
02c258dd91
Revert "fix(47299): allow testing pages with metadata in jsdom test environment" (#54160)
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:
```
2023-08-17 08:49:08 +00:00
Jiwon Choi
043114773f
fix: cookies().has() breaks in app-route (#54112)
- Added `has` to ResponseCookies in [edge-runtime/cookies#533](https://github.com/vercel/edge-runtime/pull/533)
- Upgraded edge-runtime/cookies to 3.3.0 #54117 
- Added a test case


Fixes #54005 #54111
2023-08-17 01:06:07 +00:00
Balázs Orbán
af97755e3c
fix(edge): override init when cloning with NextRequest (#54108)
### 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
2023-08-16 18:54:35 +00:00
Zack Tanner
0b3e366f32
fix routing bug when bfcache is hit following an mpa navigation (#54081)
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
2023-08-16 17:55:06 +00:00
Jiachi Liu
594f3d1fc0
Fix root not-found page tree loader structure (#54080)
### 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
2023-08-16 15:10:08 +00:00
Damien Simonin Feugas
77acd164d3
fix(47299): allow testing pages with metadata in jsdom test environment (#53578)
### 🧐 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>
2023-08-16 07:14:27 +00:00
stefanprobst
42227559c6
fix: don't add forceConsistentCasingInFileNames to tsconfig when ts version >= 5.0 (#51564)
Currently, Next.js enforces that `forceConsistentCasingInFileNames: true` is added to a user's `tsconfig.json`.

This PR removes that behavior for CNA templates, and when the typescript version is >= 5.0.0, because since ts 5.0 `forceConsistentCasingInFileNames` is `true` by default. See https://devblogs.microsoft.com/typescript/announcing-typescript-5-0/

related: https://github.com/vercel/next.js/issues/45617
2023-08-15 19:12:40 +00:00
Zack Tanner
cb432eb42d
Fix scroll bailout logic when targeting fixed/sticky elements (#53873)
### 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
2023-08-15 13:31:39 +00:00
Jiachi Liu
ec6d2c7825
Do not output pages 404 in tree view if app not-found is used (#54051)
### 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.
2023-08-15 09:59:43 +00:00
Zack Tanner
e02397d264
fix: pages not visible in dev when named children (#54007)
`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
2023-08-15 03:50:37 +00:00
Matt Cowley
c1fa78bf6c
fix(next/image): empty blur image when animated (#54028)
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.
2023-08-15 02:17:40 +00:00
Zack Tanner
c4f9c6d492
add standalone testcase for ipv6 hostnames (#53999)
This adds a test case for ipv6 hostnames in standalone mode

- Follow up to https://github.com/vercel/next.js/pull/53131
2023-08-14 17:14:07 +00:00
Ngô Đức Anh
a4b430e6f1
Better IPv6 support for next-server (#53131)
### What?
This PR makes it easier to use Next.js with IPv6 hostnames such as `::1` and `::`.

### How?
It does so by removing rewrites from `localhost` to `127.0.0.1` introduced in #52492. It also fixes the issue where Next.js tries to fetch something like `http://::1:3000` when `--hostname` is `::1` as it is not a valid URL (browsers' `URL` class throws an error when constructed with such hosts). It also fixes `NextURL` so that it doesn't accept `http://::1:3000` but refuse `http://[::1]:3000`. It also changes `next/src/server/lib/setup-server-worker.ts` so that it uses the server's `address` method to retrieve the host instead of our provided `opts.hostname`, ensuring that no matter what `opts.hostname` is we will always get the correct one.

### Note
I've verified that `next dev`, `next start` and `node .next/standalone/server.js` work with IPv6 hostnames (such as `::` and `::1`), IPv4 hostnames (such as `127.0.0.1`, `0.0.0.0`) and `localhost` - and with any of these hostnames fetching to `localhost` also works. Server Actions and middleware have no problems as well.

This also removes `.next/standalone/server.js`'s logging as we now use `start-server`'s logging to avoid duplicates. `start-server`'s logging has also been updated to report the actual hostname.
![image](https://github.com/vercel/next.js/assets/75556609/cefa5f23-ff09-4cef-a055-13eea7c11d89)
![image](https://github.com/vercel/next.js/assets/75556609/619e82ce-45d9-47b7-8644-f4ad083429db)
The above pictures also demonstrate using Server Actions with Next.js after this PR.
![image](https://github.com/vercel/next.js/assets/75556609/3d4166e9-f950-4390-bde9-af2547658148)

Fixes #53171
Fixes #49578
Closes NEXT-1510

Co-authored-by: Tim Neutkens <6324199+timneutkens@users.noreply.github.com>
Co-authored-by: Zack Tanner <1939140+ztanner@users.noreply.github.com>
2023-08-14 07:23:24 +00:00
Zack Tanner
23f623546e
add "expect" to list of forbidden IPC headers (#53947)
`expect` is an unsupported header for undici: c83b084879/lib/core/request.js (L354) -- this filters it out so that the API routes don't throw an internal server error if that header is included. 

Also added a test case for the previously submitted PR that was added for `content-length: 0`

- x-ref: #53843

Fixes #53822 (erroneously closed by a content-length issue being fixed)
2023-08-12 19:38:38 +00:00
Jiachi Liu
4056994304
Recover not found errors from flight data to render with proper boundary (#53703)
### What?

We change the not-found rendering strategy to the origin one which recovers the not found error from the flight data, and hit the error boundary to display the closet not found component.

For parallel `@slot` we shouldn't pass down the not-found boundary, the boundary is only for `@children`.

### Why?

We're having a lot of not-found matching issues that manually searching for not found and layout won't be accurate as we have various scenarios like `(group)` routes, dynamic routes, etc.

### How?

Only render html with empty body so that the error can recover from flight and render the proper not-found component during hydration.

One change for metadata is that we need to get the "not-found" metadata in the initial render, so we'll catch the not-found error once there first and start render the "not-found" metadata and put it in the flight data. Then when it recovers it's still preserved.

Fixes #53694
2023-08-12 08:41:47 +00:00
Artur Bień
e0ca2ba544
feat(image): DataURL placeholder support for <Image /> (#53442)
Adds support for base64-encoded `placeholder`. Enables using placeholders without the "blur" effect.

Fixes #47639
- [x] Add support for DataURL placeholder
- [x] Add tests
- [x] Update docs

Co-authored-by: Steven <229881+styfle@users.noreply.github.com>
2023-08-11 23:45:20 +00:00
Dima Voytenko
4c14482553
[chore] Upgrade playwright to 1.35.1 (#53875) 2023-08-11 23:25:01 +00:00
JJ Kasper
2312852e57
Update runner labels (#53925)
Adds a new label for distinguishing between runners, also fixes a couple flakey fixtures noticed while benchmarking.
2023-08-11 21:05:11 +00:00
Jiachi Liu
50ff54ee29
Use summary_large_image as twitter card if images present by default (#53919)
This is an improvement for twitter card, if there's image present we could use `summary_large_image` to make the twitter card look better instead of using `summary` by default, so that users could benefit from the large image card display on twitter
2023-08-11 17:52:45 +00:00
Jan Nicklas
9e1e9bf311
Fix/match resource (#53796)
### Bug Fix
fixes #53366



### Change

Add `query` and [`matchResource`](https://webpack.js.org/api/loaders/#inline-matchresource) to the module mapping. 



### Why

`mod.resource` and all other paths inside `packages/next/src/build/webpack/plugins/flight-client-entry-plugin.ts` are already using the query:

e127c51327/packages/next/src/build/webpack/plugins/flight-client-entry-plugin.ts (L506-L507)

e127c51327/packages/next/src/build/webpack/plugins/flight-client-entry-plugin.ts (L584-L585)



### Motivation

We are using a static extraction css-in-js solution which uses the [inline match resource feature](https://webpack.js.org/api/loaders/#inline-matchresource) (see more in #53366)

As a css-in-js file contains the TSX and the CSS code we have to split the file into two modules which share the same `resource.path`.  

This works well however there is a problem in the mapping inside `.next/server/app/page_client-reference-manifest.js`.
The `ssrModuleMapping` from `addSSRIDMapping` in 
e127c51327/packages/next/src/build/webpack/plugins/flight-manifest-plugin.ts (L270) links to the latest module (the css part) and not the the initial one (the js part).

Therefore the css module is rendered [react-server-dom-webpack](https://www.npmjs.com/package/react-server-dom-webpack/v/0.0.1?activeTab=versions) and breaks.

The SSR/SSG fails with the error `Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.`

Co-authored-by: Shu Ding <3676859+shuding@users.noreply.github.com>
2023-08-11 17:36:58 +00:00
Tobias Koppers
45576ae752
Turbopack: more tests and bugfixes for next.rs api (#53809)
### What?

* adds more HMR test cases
* fixes bugs found

### Why?

### Turbopack changes

* https://github.com/vercel/turbo/pull/5668 <!-- OJ Kwon - ci(test):
temporarily increase test timeout -->
* https://github.com/vercel/turbo/pull/5696 <!-- Tobias Koppers -
Cleanup minify -->
2023-08-11 10:29:36 +02:00
Luud Janssen
5fe332186e
Add changeFrequency and priority attributes to sitemaps (#48484)
Closes #48479. 

Couldn't find the source for the Next.js beta docs, so I didn't add documentation.

Co-authored-by: Jiachi Liu <4800338+huozhi@users.noreply.github.com>
2023-08-09 20:36:22 +00:00
Zack Tanner
712669f605
improve error message for conflicting parallel segments (#53803)
This is a follow-up to log both conflicting paths & a link to route group docs, which I believe is the only scenario someone could trigger this

- https://github.com/vercel/next.js/pull/53752
2023-08-09 17:21:24 +00:00
OJ Kwon
e127c51327
test(turbo): allow to run test with --experimental-turbo (#53396)
### What?

Allows to configure test runs with --experimental turbo.
2023-08-09 05:48:54 +00:00
JJ Kasper
6b492974b7
Move next-rs API tests from unit to e2e (#53771)
These tests aren't unit per-se as they rely on e2e-utils so this moves
them to the `development` test folder.

x-ref: [slack
thread](https://vercel.slack.com/archives/C04DUD7EB1B/p1691520079363229)
2023-08-08 21:50:04 -07:00
JJ Kasper
4b4533787b
Add warnings for static generation bail outs (#53761)
Currently using server actions on a page or using edge runtime causes
that page to bail out of ISR or static generation so this adds warnings
to make users aware of this.

x-ref: [slack
thread](https://vercel.slack.com/archives/C03KAR5DCKC/p1690816539472449)

---------

Co-authored-by: Zack Tanner <zacktanner@gmail.com>
2023-08-08 20:09:34 -07:00
Eric Fennis
5e716ec918
fix: Update outdated transform imports lucide-react (#53697)
### What?

Fixing outdated import mapping with the latest `lucide-react` changes. See [lucide-icons/lucide@v0.264.0](https://github.com/lucide-icons/lucide/releases/tag/v0.264.0)

Closes: lucide-icons/lucide#1482

### Why?

Import mapping was outdated

### How?

By updating the default config and the tests.

## Notes

Maintainer here from @lucide-icons.
To this day I didn't know the Nextjs default config file has predefined hardcoded modularize imports. 
I was a bit surprised that there is a default mapping for libraries that could change in the future like Lucide. 

I'm not in favor of this hardcoded "modularize imports", because this creates a hard dependency on libraries. With Lucide, we still have not reached 1.0 and will sometimes rename icons and add aliases for them. So issues will occur in the future, and constantly updating this config doesn't feel right. 

Is there, not a better way? Like for example, a package exposing a config file containing the import mapping?
This way import map will automatically be in sync with changes in a package. 

Let me know what you think of this.
2023-08-09 00:48:48 +00:00