Commit graph

3018 commits

Author SHA1 Message Date
Shu Ding
c742c038b0
Port page and layout level API assertions to SWC transform (#40653)
We used to do an extra pass of SWR `parse` and loop over the AST inside
JavaScript to check if `getServerSideProps` or `getStaticProps` is used
in a client page or layout. Instead this can be done in the same
`react_server_components` SWC transform now.

## Bug

- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have a helpful link attached, see `contributing.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
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
2022-09-19 14:30:32 +02:00
Hannes Bornö
356b6cec43
Send web vitals to Vercel analytics in app (#40669)
Sends web vitals to Vercel analytics.

My plan for the test was to assert the data sent by the client but there's a bug where it's always null when sending a blob https://github.com/microsoft/playwright/issues/6479.

When adding support for a custom web vitals reporter it will be easier to assert the values sent by the reporter.
2022-09-19 08:16:53 +00:00
Tim Neutkens
d41ca43d23
Change Flight response content type to application/octet-stream (#40665)
Ensures Flight responses are not loaded as HTML.


## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see `contributing.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
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
2022-09-18 20:49:05 +00:00
Jiachi Liu
3f8f72bf9b
Remove internal client next api detection (#40646)
Follow up for https://github.com/vercel/next.js/pull/40415

Remove internal next client api determination, fully relying on `'client'` directive.
Change `.client.js` extension to `.js ` in tests, remove legacy / unused test files
2022-09-18 09:36:10 +00:00
Jiachi Liu
295f9da393
Client directive (#40415)
## Feature
Change server components convention from using `.server.js` / `.client.js` file extension to determine it's a server or client component to using `'client'` js literal as a directive for determine client components boundary.
React RFC: https://github.com/reactjs/rfcs/pull/189
New behavior doesn't consume `.server.js` as server components any more, if you're enabling `serverComponents` flag, every `page.js` in app dir will become server components by default. If you adding a `'client'` directive to the page, then that page will become a client component. This rule also applies to the normal js components, client components will require a `'client'` directive to indicate its identity, instead of having a `.client.js` extension.
- [x] 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`
- [x] Integration tests added
- [ ] 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: Shu Ding <3676859+shuding@users.noreply.github.com>
2022-09-18 00:00:16 +00:00
Shu Ding
d5fa555841
Implement SWC transformer for server and client graphs (#40603)
This is an initial implementation of the Server Components SWC
transformer. For the server graph, it detects client entries via the
`"client"` directive and transpile them into module reference code; for
the client graph, it removes the directives. And for both graphs, it
checks if there is any invalid imports for the given environment and
shows proper errors.

With that added, we can switch from `next-flight-client-loader` to
directly use the SWC loader in one pass. Next step is to get rid of the
`.client.` extension in other plugins.

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [x] 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`
- [x] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
2022-09-17 00:12:59 +02:00
Balázs Orbán
3ff21ed178
refactor: split up CONTRIBUTING.md (#40515)
Continues #39778

Closes #40499

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.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
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)

Co-authored-by: Tim Neutkens <tim@timneutkens.nl>
Co-authored-by: JJ Kasper <jj@jjsweb.site>
2022-09-16 14:54:58 -07:00
Balázs Orbán
cade8c84c4
fix: handle notFound: true in / with next export (#40592)
Closes #40571

An earlier fix in #24481 did not consider the `/` case. The page path normalization method `normalizePagePath` turned `/` into `/index` and the route matching was skipped for the index route's non-existent HTML file.

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.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
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
2022-09-16 21:39:48 +00:00
Janicklas Ralph
7fba48ef70
Adding experimentalAdjustFallback feature to font optimization (#40185)
<!--


## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [x] 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`
- [x] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [x] Make sure the linting passes by running `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
- [ ] -->
## Feature

- [x] Implements https://github.com/vercel/next.js/discussions/40112
- [x] Integration tests added

Adds a new option to the current font optimization to enable
experimental font size adjust

The new `optimizeFonts` config will be 
```
optimizeFonts: {
    inlineFonts: true,
    experimentalAdjustFallbacks: false,
  },
```

To enable the feature, set `experimentalAdjustFallbacks: true`

`optimizeFonts: false` will disable the entire feature (including
inlining google font definition)

Co-authored-by: JJ Kasper <jj@jjsweb.site>
2022-09-16 14:13:21 -07:00
Balázs Orbán
8bf082a913
fix: loosen webpack compilation with fallbackNodePolyfills: false (#40612)
If in `resolve.fallback` we set previously polyfilled modules to `false`
instead of an empty object, webpack will pass the compilation _and_ not
include any polyfills.

Fixes #40522, fixes #40364

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.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
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
2022-09-16 13:23:56 -07:00
Alex
1ea65cf931
fix(image): handle image imports with high aspect ratio (#40563)
## Bug

- [x] Related issues linked using `fixes #40562`
fixes #40562
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`


Co-authored-by: Steven <229881+styfle@users.noreply.github.com>
2022-09-16 20:17:19 +00:00
유경화
7556611449
fix(next/router): Prevent query delete in routing when next.config basePath option is truthy (#40566)
## Bug

- [x] Related issues linked using `fixes #number`
    - fixes 
        - #38528 
        - #40432
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

Hi, it is my first pull request in this project.
So... if you need anything more tasks, please tell me.

Co-authored-by: JJ Kasper <22380829+ijjk@users.noreply.github.com>
2022-09-15 22:56:53 +00:00
Wyatt Johnson
33a6dca747
Mask Flight Parameters from Middleware (#39939)
This masks flight parameters from middleware so it doesn't interfere with RSC or routing.

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.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
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)


Co-authored-by: Tim Neutkens <6324199+timneutkens@users.noreply.github.com>
2022-09-15 14:53:51 +00:00
Donny/강동윤
57be012e06
chore: Update swc (#40520)
This updates SWC crates to
69bf533571

---

 - Closes https://github.com/vercel/next.js/issues/40535

Co-authored-by: JJ Kasper <jj@jjsweb.site>
2022-09-15 14:22:11 +02:00
Sukka
01b1e6b52b
fix(#40025): run next/script beforeInteractive test in both dev & prod (#40541)
Ref: #40002 #40026 #40191
Fixes #40025

This is the final step of fixing #40025. The PR migrates the rest of the
`next/script` test cases to run in both dev (strict mode) and
production, confirming that the `next/script` component is now
completely concurrent rendering resilient and is ready for the upcoming
React 18 `<OffScreen />`.

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`
2022-09-14 10:00:40 -07:00
Tim Neutkens
385e3f0380
Wrap parallel routes tests in describe (#40546)
Small changes:
- Group parallel routes tests
- Upgrade tests to latest react experimental
2022-09-14 09:09:01 +00:00
Sukka
ed3cb83c8a
next/script: make onLoad concurrent rendering resilient (#40191)
Another step toward fixing #40025.

Multiple `next/script` components with the same `src` may exist in the
Next.js app. So the `loadScript` function will always attach the
`onLoad` handler to the `loadingPromise` every time it executes.

However, with strict mode (or wrapped inside the `<OffScreen />`
component), the `useEffect` could execute more than once for the same
`next/script` component, thus the `loadScript` for each `next/script`
component could execute more than once (and `onLoad` to be attached more
than once), results in `onLoad` fires more than once.

The PR makes sure that for every `next/script` component mounted, the
`loadScript` will always be executed only once for each of them.

The corresponding `onload fires correctly` integration test case is also
updated to run in dev mode.

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`
2022-09-13 17:48:06 -07:00
Tim Neutkens
eadaca780b
Add additional tests for prefetch and trailingSlash (#40517)
Adds some of the tests we didn't have yet for app.
<!--
Thanks for opening a PR! Your contribution is much appreciated.
In order to make sure your PR is handled as smoothly as possible we
request that you follow the checklist sections below.
Choose the right checklist for the change that you're making:
-->

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.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
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
2022-09-13 16:01:43 -07:00
Malte Ubl
421029cf61
Don't execute prefetches for bot user agents (#40435)
Such bots typically navigate websites using hard navigations (as they
crawl one URL at a time). Respectively, they do not benefit from
prefetches at all, while increasing the cost of both the crawl and
operating the site.

<!--
Thanks for opening a PR! Your contribution is much appreciated.
In order to make sure your PR is handled as smoothly as possible we
request that you follow the checklist sections below.
Choose the right checklist for the change that you're making:
-->

## Bug

- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`
2022-09-12 17:27:43 -07:00
JJ Kasper
8bf6a87303
Rename allowDynamic to unstable_allowDynamic (#40496)
Follow-up to https://github.com/vercel/next.js/pull/39539 as discussed
this renames to `unstable_` prefix initially while we test this out
further.

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.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
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
2022-09-12 15:32:18 -07:00
Damien Simonin Feugas
97ac344468
feat(edge): allows configuring Dynamic code execution guard (#39539)
### 📖  What's in there?

Dynamic code evaluation (`eval()`, `new Function()`, ...) is not
supported on the edge runtime, hence why we fail the build when
detecting such statement in the middleware or `experimental-edge` routes
at build time.

However, there could be false positives, which static analysis and
tree-shaking can not exclude:
- `qs` through these dependencies (get-intrinsic:
[source](https://github.com/ljharb/get-intrinsic/blob/main/index.js#L12))
- `function-bind`
([source](https://github.com/Raynos/function-bind/blob/master/implementation.js#L42))
- `has`
([source](https://github.com/tarruda/has/blob/master/src/index.js#L5))

This PR leverages the existing `config` export to let user allow some of
their files.
it’s meant for allowing users to import 3rd party modules who embed
dynamic code evaluation, but do not use it (because or code paths), and
can't be tree-shaked.

By default, it’s keeping the existing behavior: warn in dev, fails to
build.
If users allow dynamic code, and that code is reached at runtime, their
app stills breaks.

### 🧪 How to test?

- (existing) integration tests for disallowing dynamic code evaluation:
`pnpm testheadless --testPathPattern=runtime-dynamic`
- (new) integration tests for allowing dynamic code evaluation: `pnpm
testheadless --testPathPattern=runtime-configurable`
- (amended) production tests for validating the new configuration keys:
`pnpm testheadless --testPathPattern=config-validations`

To try it live, you could have an application such as:
```js
// lib/index.js
/* eslint-disable no-eval */
export function hasUnusedDynamic() {
  if ((() => false)()) {
    eval('100')
  }
}

export function hasDynamic() {
  eval('100')
}

// pages/index.jsx
export default function Page({ edgeRoute }) {
  return <p>{edgeRoute}</p>
}

export const getServerSideProps = async (req) => {
  const res = await fetch(`http://localhost:3000/api/route`)
  const data = await res.json()
  return { props: { edgeRoute: data.ok ? `Hi from the edge route` : '' } }
}

// pages/api/route.js
import { hasDynamic } from '../../lib'

export default async function handle() {
  hasDynamic()
  return Response.json({ ok: true })
}

export const config = { 
  runtime: 'experimental-edge' ,
  allowDynamic: '/lib/**'
}
```

Playing with `config.allowDynamic`, you should be able to:
- build the app even if it uses `eval()` (it will obviously fail at
runtime)
- build the app that _imports but does not use_ `eval()`
- run the app in dev, even if it uses `eval()` with no warning

### 🆙 Notes to reviewers

Before adding documentation and telemetry, I'd like to collect comments
on a couple of points:
- the overall design for this feature: is a list of globs useful and
easy enough?
- should the globs be relative to the application root (current
implementation) to to the edge route/middleware file?
- (especially to @sokra) is the implementation idiomatic enough? I've
leverage loaders to read the _entry point_ configuration once, then the
ModuleGraph to get it back during the parsing phase. I couldn't re-use
the existing `getExtractMetadata()` facility since it's happening late
after the parsing.
- there's a glitch with `import { ServerRuntime } from '../../types'` in
`get-page-static-info.ts`
([here](https://github.com/vercel/next.js/pull/39539/files#diff-cb7ac6392c3dd707c5edab159c3144ec114eafea92dad5d98f4eedfc612174d2L12)).
I had to use `next/types` because it was failing during lint. Any clue
why?

### ☑️ Checklist

- [ ] 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`
- [x] Integration tests added
- [x] Documentation added
- [x] Telemetry added. In case of a feature if it's used or not.
- [x] Errors have helpful link attached, see `contributing.md`
2022-09-12 15:01:00 -07:00
Đorđe Spasić
804dc6bd10
fix: eslint no-script-component-in-head error url (#40422)
## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [x] Make sure the linting passes by running `pnpm lint`
- [x] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)


Co-authored-by: JJ Kasper <22380829+ijjk@users.noreply.github.com>
2022-09-12 16:15:33 +00:00
Tim Neutkens
f92a4cee8a
Add failing case for location throw (#40445)
Found that the cause was that `React.useId()` returns the same value across requests whereas it was being used to create a unique key. On further inspection that code could be removed altogether as `id` was not used client-side and the `rscCache` map is no longer needed as the flight instance is already being created per request so it can live in the context of the request execution.


## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.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
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
2022-09-12 12:45:37 +00:00
Balázs Orbán
8bc587aa30
feat(ts): expose AppType (#40391)
An alternative solution to #40371

Ref: #38867, https://github.com/t3-oss/create-t3-app/issues/412,
https://github.com/t3-oss/create-t3-app/pull/414

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.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
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
2022-09-09 13:32:58 -07:00
Hannes Bornö
6fb1121e8c
Add missing trace for full reload event (#40393)
Added missing trace for `client-full-reload` event in hot reloader. Full
reload tests moved to hmr, think they make more sense there than on
their own.
2022-09-09 13:09:15 -07:00
Sukka
3d23c3d9ee
fix(#40388): next/dynamic should only add default loading without suspense (#40397)
The PR fixes #40388.

Currently, `next/dynamic` will try to provide a default `loading` to the
`loadableOptions` even when `suspense` is enabled, thus triggering the
incorrect warning. The PR fixes that. The corresponding integration test
case is also updated.

cc @huozhi 

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

Co-authored-by: huozhi <inbox@huozhi.im>
2022-09-09 12:46:23 -07:00
Jiachi Liu
d64fc54507
Temporarily disable unstable app test (#40408)
Disable this test and investigate it later

x-ref:
https://github.com/vercel/next.js/runs/8270347830?check_suite_focus=true
x-ref:
https://github.com/vercel/next.js/runs/8270348185?check_suite_focus=true
2022-09-09 11:50:18 -07:00
Tim Neutkens
a3a20dcbc1
Add template and error file types (#39808)
Co-authored-by: Jiachi Liu <inbox@huozhi.im>
2022-09-09 14:44:12 +02:00
Wyatt Johnson
c6ef857d57
Subresource Integrity for App Directory (#39729)
<!--
Thanks for opening a PR! Your contribution is much appreciated.
In order to make sure your PR is handled as smoothly as possible we
request that you follow the checklist sections below.
Choose the right checklist for the change that you're making:
-->

This serves to add support for [Subresource
Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity)
hashes for scripts added from the new app directory. This also has
support for utilizing nonce values passed from request headers (expected
to be generated per request in middleware) in the bootstrapping scripts
via the `Content-Security-Policy` header as such:

```
Content-Security-Policy: script-src 'nonce-2726c7f26c'
```

Which results in the inline scripts having a new `nonce` attribute hash
added. These features combined support for setting an aggressive Content
Security Policy on scripts loaded.

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.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
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [x] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [x] Make sure the linting passes by running `pnpm lint`
- [x] The examples guidelines are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)

Co-authored-by: Steven <steven@ceriously.com>
2022-09-08 15:17:15 -07:00
Jiachi Liu
1858fa966c
Fix page url for edge routes in app dir (#40361)
For edge routes in app dir, we passed the page name as url so that the
url will be incorrect:

* a non-dynamic route `/dashboard` will become `/dashboard/page`
* a dynamic route `/dynamic/[id]` with url `/dyanmic/123` will still hit
`/dynamic/page/[id]/page`

This PR uses normalized `params.page` with interoplated as correct
pathname for the page.
2022-09-08 14:57:56 -07:00
Carl von Buelow
75e5616ce4
Update onLoadingComplete for next/future/image to receive reference to <img> (#40326)
* fixes #18398
* fixes #38864

Co-authored-by: Steven <steven@ceriously.com>
2022-09-08 08:37:41 -07:00
Gal Schlezinger
220e144a6a
[edge] fix URLSearchParams lacking data from rewrite (#40260)
Given the change in #40076, when a middleware rewrites into an Edge
API route and changes the querystring, the changed querystring does
not appear in the incoming NextRequest object in the Edge API route

```ts
// middleware.ts
export function middleware(req: NextRequest) {
  const url = req.nextUrl;
  url.pathname = "/api/hello";
  url.searchParams.set("foo", "bar");
  return NextResponse.rewrite(url);
}

// pages/api/hello.ts
import { NextRequest } from "next/server";

export default function handler(req: NextRequest) {
  return NextResponse.json(req.nextUrl.searchParams.get("foo"));
}

export const config = { runtime: "experimental-edge" };
```

Our expectation when requesting `/api/hello` is to see `"bar"`,
but instead we are getting `null` back.

This commit fixes this issue by reading the given `query` instead of using
the initial querystring provided with the user request (prior to rewriting)

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`
2022-09-08 11:19:18 +00:00
JJ Kasper
62c7eff354
Revert "Revert "Refactor Server Router" (#40328)" (#40333)
This unreverts https://github.com/vercel/next.js/pull/40328 as it wasn't
the cause for https://github.com/vercel/next.js/issues/40241 like
initially suspected and the actual fix has been included here as well
with regression test.

Fixes: https://github.com/vercel/next.js/issues/40241

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`
2022-09-07 16:38:10 -07:00
Hannes Bornö
a9b9e00703
fix(switchable-runtime): Make it possible to switch between edge and server runtime in dev (#39327)
Makes it possible to switch between edge/server runtime in dev without
breaking the server.

Fixes slack:
[1](https://vercel.slack.com/archives/CGU8HUTUH/p1659082535540549)
[2](https://vercel.slack.com/archives/C02CDC2ALJH/p1658978287244359)
[3](https://vercel.slack.com/archives/C03KAR5DCKC/p1656869427468779)

#### middleware-plugin.ts
`middlewareManifest` moved from module scope to local scope. Stale state
from earlier builds ended up in `middleware-manifest.json`. Functions
that changed from edge to server runtime stayed in the manifest as edge
functions.

#### on-demand-entry-handler.ts
When a server or edge entry is added we check if it has switched
runtime. If that's the case the old entry is removed.

#### Reproduce
Create edge API route and visit `/api/hello`
```js
// pages/api/hello.js
export const config = {
  runtime: 'experimental-edge',
}

export default () => new Response('Hello')
```

Change it to a server api route and visit `/api/hello`, it will explode.
```js
// pages/api/hello.js
export default function (req, res) {
  res.send('Hello')
}
```

#### Bug not fixed
One EDGE case is not fixed. It occurs if you switch between edge and
server runtime several times without changing the content of the file:

Edge runtime
```js
export const config = {
  runtime: 'experimental-edge',
}

export default () => new Response('Hello')
```

Change it to a server runtime
```js
export default function (req, res) {
  res.send('Hello')
}
```

Change back to edge runtime, the content of the file is the same as the
first time we compiled the edge runtime version.
```js
export const config = {
  runtime: 'experimental-edge',
}

export default () => new Response('Hello')
```

The reason is that both the edge and server compiler emits to the same
file (/.next/server/pages/api/hello.js) which makes this check fail in
webpack:
https://github.com/webpack/webpack/blob/main/lib/Compiler.js#L849-L861
Possible solution is to use different output folders for edge and server
https://vercel.slack.com/archives/CGU8HUTUH/p1661163106667559

Co-authored-by: JJ Kasper <jj@jjsweb.site>
2022-09-07 13:42:32 -07:00
Hannes Bornö
35253e1a93
fix(switchable-runtime): make dev server not break when wrong runtime config is exported (#40312)
Currently the DEV server can't recover if you export an invalid runtime
config. It ends up in a state where it stops to work but nothing is
printed to the terminal.

It now prints an error but keeps working. When building it should crash,
there's an existing test for that
https://github.com/vercel/next.js/blob/canary/test/production/exported-runtimes-value-validation/index.test.ts#L5-L17

#### Reproduce
```tsx
export default function Page() {
  return <p>hello world</p>
}

export const config = {
  runtime: 'something-odd',
}

```
2022-09-07 13:12:13 -07:00
Jiachi Liu
084ad964a0
Fix static info parsing when export data fetching method as variable (#40317)
Fix the ssr/ssg detection when you export a nextjs data fetching method
as a variable instead of an async function.

- [x] Add case support in `checkExports`
- [x] Add unit tests for `getPageStaticInfo`
2022-09-07 09:28:15 -07:00
JJ Kasper
e8ff2738b3
Fix test hydration check in Safari 10.1 (#40285)
This removes the optional chaining inside of the `executeAsync` as that
is treated literally when passed to the browser and Safari 10.1 doesn't
support optional chaining.

fixes:
https://github.com/vercel/next.js/runs/8213273664?check_suite_focus=true
fixes:
https://github.com/vercel/next.js/runs/8213237056?check_suite_focus=true
2022-09-06 12:17:54 -07:00
Steven
d53e2f2f37
Update next/future/image to support only width or only height (#40278)
This PR allows you to resize a statically imported image using only `width` or only `height`. For example:

```jsx
import img from './img.jpg'
<Image src={img} width="200" />
```

Previously, you had to specify both or else the image aspect ratio would not be preserved.
2022-09-06 17:50:31 +00:00
Tim Neutkens
71ad0dd0b0
Add prefetch to new router (#39866)
Follow-up to #37551
Implements prefetching for the new router.

There are multiple behaviors related to prefetching so I've split them out for each case. The list below each case is what's prefetched:

Reference:
- Checkmark checked → it's implemented.
- RSC Payload → Rendered server components.
- Router state → Patch for the router history state.
- Preloads for client component entry → This will be handled in a follow-up PR.
- No `loading.js` static case → Will be handled in a follow-up PR.

---

- `prefetch={true}` (default, same as current router, links in viewport are prefetched)
    - [x]  Static all the way down the component tree
        - [x] RSC payload
        - [x] Router state
        - [ ] preloads for the client component entry
    - [x]  Not static all the way down the component tree
        - [x]  With `loading.js`
            - [x] RSC payload up until the loading below the common layout
            - [x] router state
            - [ ] preloads for the client component entry
        - [x]  No `loading.js` (This case can be static files to make sure it’s fast)
            - [x] router state
            - [ ] preloads for the client component entry
- `prefetch={false}`
    - [x]  always do an optimistic navigation. We already have this implemented where it tries to figure out the router state based on the provided url. That result might be wrong but the router will automatically figure out that

---

In the first implementation there is a distinction between `hard` and `soft` navigation. With the addition of prefetching you no longer have to add a `soft` prop to `next/link` in order to leverage the `soft` case. 

A heuristic has been added that automatically prefers `soft` navigation except when navigating between mismatching dynamic parameters.

An example:
- `app/[userOrTeam]/dashboard/page.js` and `app/[userOrTeam]/dashboard/settings/page.js`
  - `/tim/dashboard` → `/tim/dashboard/settings` = Soft navigation 
  - `/tim/dashboard` → `/vercel/dashboard` = Hard navigation
  - `/vercel/dashboard` → `/vercel/dashboard/settings` = Soft navigation
  - `/vercel/dashboard/settings` -> `/tim/dashboard` = Hard navigation

---

While adding these new heuristics some of the tests started failing and I found some state bugs in `router.reload()` which have been fixed. An example being when you push to `/dashboard` while on `/` in the same transition it would navigate to `/`, it also wouldn't push a new history entry. Both of these cases are now fixed:

```
React.startTransition(() => {
  router.push('/dashboard')
  router.reload()
})
```

---

While debugging the various changes I ended up debugging and manually diffing the cache and router state quite often and was looking at a way to automate this. `useReducer` is quite similar to Redux so I was wondering if Redux Devtools could be used in order to debug the various actions as it has diffing built-in. It took a bit of time to figure out the connection mechanism but in the end I figured out how to connect `useReducer`, a new hook `useReducerWithReduxDevtools` has been added, we'll probably want to put this behind a compile-time flag when the new router is marked stable but until then it's useful to have it enabled by default (only when you have Redux Devtools installed ofcourse).

> ⚠️ Redux Devtools is only connected to take incoming actions / state. Time travel and other features are not supported because the state sent to the devtools is normalized to allow diffing the maps, you can't move backward based on that state so applying the state is not connected.

Example of the integration:

<img width="1912" alt="Screen Shot 2022-09-02 at 10 00 40" src="https://user-images.githubusercontent.com/6324199/188637303-ad8d6a81-15e5-4b65-875b-1c4f93df4e44.png">
2022-09-06 17:29:09 +00:00
Shu Ding
5f95b6b050
Improved route resolution in next-app-loader (#40109)
This PR implements the logic to make next-app-loader able to match multiple routes.

The app loader is refactored to construct the tree recursively instead of within a loop, as there could be multiple branches. Similarly, when entering a new layout level or branch, we resolve both the slot name (defaults to `"children"`) and the segment.

In order to make that work, the loader has to know all matched app paths. This is passed in as the `appPaths` loader option, which is gathered when creating the entrypoint.

## Bug

- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.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
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)

Co-authored-by: Tim Neutkens <tim@timneutkens.nl>
Co-authored-by: JJ Kasper <jj@jjsweb.site>
2022-09-06 10:03:21 -07:00
JJ Kasper
6f352357fb
Ensure path can be specified for clearPreviewData (#40238)
As updated in https://github.com/vercel/next.js/pull/38313 this ensures the `path` option can also be passed to `clearPreviewData` to properly clear the preview cookies. 

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

Fixes: https://github.com/vercel/next.js/issues/39853
2022-09-05 13:37:08 -07:00
Jiachi Liu
03eb4b1d61
Bypass empty pages folder for layouts (#40132)
Check `pagesDir` to bypass empty pages folder when appDir is enabled

* Output empty loadable manifest for now if there's no `pagesDir`
* No custom aliases with all page extensions for `/_app`, `_document` if pagesDir is empty, only keep the built-in ones
* Check pagesDir in build/dev-server/eslint
* Type safe: change arguments of some APIs from optional to required, so that we won't mess up with default arguments
2022-09-03 00:13:47 +00:00
Sukka
f9706e0365
next/script: simplify logic and update tests (#40026)
The PR is the first step toward fixing #40025. The PR makes the `script-loader` integration test run on both dev and production modes.

Some existing test cases are skipped in dev mode because corresponding features are not strict mode resilient and thus will fail. They will be included in dev mode tests in the future.

The PR also merges some duplicated logic in `next/script`, and adds a detailed comment about how `onReady` works.

In the next PR, I will try to fix `onLoad` being called more than once under strict mode.

Co-authored-by: Houssein Djirdeh <houssein.djirdeh@gmail.com>
2022-09-02 15:25:44 -07:00
Visnu Pitiyanuvath
abcf991d11
Match data fetch and busting cache key when path URI encodes (#39568)
Fixes #38581
<!--
Thanks for opening a PR! Your contribution is much appreciated.
In order to make sure your PR is handled as smoothly as possible we request that you follow the checklist sections below.
Choose the right checklist for the change that you're making:
-->

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.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
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)

Co-authored-by: JJ Kasper <jj@jjsweb.site>
2022-09-01 21:22:17 -07:00
Balázs Orbán
2de7b43b78
fix: detect ESLint config in package.json (#40158)
Fixes #40133

Fixes a small regression introduced in #39872. We should be able to detect if a non-empty `package.json#eslintConfig` property is present.

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.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
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
2022-09-01 16:23:03 +00:00
Sukka
40767e5ce7
fix(#40066): preserve error status code from serveStatic (#40128)
The PR fixes #40066.

Next.js' `serveStatic` method is powered by the [send](https://github.com/pillarjs/send) module, which could throw errors under specific circumstances.
Currently, Next.js only preserves the 412 Error from send, hence issue #40066 (where 416 Error is not preserved).

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`
2022-08-31 23:08:56 +00:00
Steven
4cc7f11da2
Update to stable: next/future/image, remotePatterns, unoptimized (#40142)
This PR updates a few features from experimental to stable status:

- `next/future/image` component
- `remotePatterns` configuration
- `unoptimized` configuration
2022-08-31 22:44:17 +00:00
Will Binns-Smith
643447ed03
Allow port 0 in next dev and next start (#40118)
This addresses a bug where invoking `next dev` or `next start` with `--port 0` would fall back to the default port of 3000 instead of binding to port 0 (which typically results in the operating system assigning a free port).

I couldn't find a straightforward way of adding a test for next-start. It looks like we could add a similar test as for dev, but would need to generate a built project to serve. 

Manual test plan for `next start`:
```
$ ./packages/next/dist/bin/next start --port 0
ready - started server on 0.0.0.0:53508, url: http://localhost:53508
```

## Bug

- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [x] Make sure the linting passes by running `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)

Co-authored-by: Steven <steven@ceriously.com>
Co-authored-by: JJ Kasper <jj@jjsweb.site>
Co-authored-by: Wyatt Johnson <accounts+github@wyattjoh.ca>
2022-08-31 17:13:39 -05:00
Steven
abddee7413
Change alt to required in next/future/image (#40136)
This `alt` attribute is required by `<img>` according to the HTML spec, so we should also make it required for `next/future/image`. In the cases where it is not needed, it can be set to the empty string.

https://html.spec.whatwg.org/multipage/images.html#alt
2022-08-31 19:10:19 +00:00
Naoyuki Kanezawa
b522b94cce
feat(next): Support has match and locale option on middleware config (#39257)
## Feature

As the title, support `has` match, `local`  that works the same with the `rewrites` and `redirects` of next.config.js on middleware config. With this PR, you can write the config like the following:

```js
export const config = {
  matcher: [
    "/foo",
    { source: "/bar" },
    {
      source: "/baz",
      has: [
        {
          type: 'header',
          key: 'x-my-header',
          value: 'my-value',
        }
      ]
    },
    {
      source: "/en/asdf",
      locale: false,
     },
  ]
}
```

Also, fixes https://github.com/vercel/next.js/issues/39428

related https://github.com/vercel/edge-functions/issues/178, https://github.com/vercel/edge-functions/issues/179

- [x] 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`
- [x] Integration tests added
- [ ] 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: JJ Kasper <jj@jjsweb.site>
2022-08-31 11:23:30 -05:00