Commit graph

151 commits

Author SHA1 Message Date
Tim Neutkens
14c9376899
BREAKING CHANGE: Remove React 17 (#41629)
Next.js 13 will require React 18.

In this PR I've only updated the peerDependency and removed the test runs in GH actions. Further cleanup will follow later, this allows us to remove the code supporting it later.



## 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)


Co-authored-by: Jiachi Liu <4800338+huozhi@users.noreply.github.com>
2022-10-21 22:20:36 +00:00
Steven
cff9fc9d74
BREAKING CHANGE: Remove browsersListForSwc and change default to legacyBrowsers: false (#41529)
Remove `browsersListForSwc` since it is enabled by default now, and disable `legacyBrowsers` by default.

This PR also bumps the default browserslist to the following:

- Chrome 64+
- Edge 79+
- Firefox 67+
- Opera 51+
- Safari 12+

See related RFC:
- Closes #33227 

Co-authored-by: JJ Kasper <22380829+ijjk@users.noreply.github.com>
2022-10-19 01:38:39 +00:00
Steven
9c5bb5bfe9
BREAKING CHANGE: Remove target: serverless (#41495)
The `target: serverless` config was deprecated a year ago starting in
[Next.js 12](https://nextjs.org/blog/next-12).

Tests were disabled in #41252 so we can now remove `target: serverless`
and all usage of `target` in `next.config.js`.

Co-authored-by: Balázs Orbán <info@balazsorban.com>
Co-authored-by: JJ Kasper <jj@jjsweb.site>
2022-10-18 09:47:13 -07:00
Tim Neutkens
f260328900
BREAKING CHANGE: Enable newNextLinkBehavior (#41459)
- Enable newNextLinkBehavior. See #36436 
- Run next/link codemod on test suite

Note that from when this lands on apps trying canary will need to run
the new-link codemod in order to upgrade.
Ideally we have to detect `<a>` while rendering the new link and warn
for it.

Co-authored-by: Steven <steven@ceriously.com>
2022-10-17 21:20:28 -04:00
Felipe Barso
6249307b75
fix(stream): Allows body larger than 16 KiB with middleware (#41270)
Fixes #39262

The solution is to call `stream.push(null)` to trigger the `end` event
which allows `getRawBody` to run completely.

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

## Bug

- [x] 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

- [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/examples/adding-examples.md)

Co-authored-by: JJ Kasper <jj@jjsweb.site>
2022-10-17 15:26:16 -07:00
Steven
241195ddd6
BREAKING CHANGE: Rename next/image to next/legacy/image & rename next/future/image to next/image (#41399)
This PR introduces breaking changes by renaming components.

- Rename `next/image` to `next/legacy/image`
- Rename `next/future/image` to `next/image`

The diff is very confusing because both components are very similar so git got confused.
2022-10-14 01:59:22 +00:00
Balázs Orbán
701e8d2c0f
fix(standalone): support type: "module" (#41268)
Fixes #41258

When we detect `type: "module"` in `package.json`:

~1. generate `server.mjs`~ Not necessary when `type: "module"` is set.
2. use `import` instead of `require`
3. replace `__dirname` with [ESM compatible
alternative](https://blog.logrocket.com/alternatives-dirname-node-js-es-modules/)

In this PR, I also moved some tests (those using `output: "standalone"`)
to a new `test/production/standalone-mode` directory for easier
discoverability in the future.

Run the related test with `pnpm test
test/production/standalone-mode/type-module/index.test.ts`

## 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-10-11 17:04:37 +02:00
Tim Neutkens
eb629c15ca
Skip serverless/serverless-trace target tests (#41252) 2022-10-07 18:57:22 +02:00
JJ Kasper
eb424042f8
Ensure skipClientCache is honored for router.push (#40932)
Fixes: https://github.com/vercel/next.js/issues/40927

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have a helpful link attached, see `contributing.md`
2022-09-26 23:30:49 -07:00
Tomer Aberbach
4970d7a0e8
Set __NEXT_NEW_LINK_BEHAVIOR in Jest tests when newNextLinkBehavior is true (#40702)
Fixes #40463

Could use some help figuring out where to add a test! I looked around
and found
[`jest-next-swc.test.ts`](https://github.com/vercel/next.js/blob/canary/test/unit/jest-next-swc.test.ts),
but I don't think I can use that to test this fix. Anyways, from my
local testing this PR seems to fix the issue.

Co-authored-by: JJ Kasper <jj@jjsweb.site>
2022-09-21 22:36:59 -07: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
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
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
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
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
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
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
JJ Kasper
68fb39a034
Fix handling with custom _error and pages/500 (#40110)
This ensures we are properly calling `getInitialProps` in `_error` before serving `pages/500` as this has been the expected behavior since we introduced the process exiting behavior when deployed. This also ensures we don't attempt serving the `pages/500` before logging the error and exiting as this file isn't always expected to be present when statically optimized. 

Test deployments from provided reproduction can be seen here: 
- https://next-500-issue-ijdlh0e9y-ijjk-testing.vercel.app/
- https://next-500-issue-acn2vi68j-ijjk-testing.vercel.app/

## 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/40065
Fixes: https://github.com/vercel/next.js/issues/39952
2022-08-30 18:14:12 -05:00
Jiachi Liu
8668020a54
Upgrade typescript to 4.8.2 (#39979)
Typescript published 4.8.2 today and it fails CI, bump our typescript version to 4.8.2 and tweak some typings to make existing e2e typescript tests work properly

* Bump web-vitals from 3.0.0-beta to 3.0.0 stable for typing fix (there's an undefined type but it wasn't caught by ts 4.7), also force compiled it as CJS for pre-compiled
* Bump ncc to 3.34.0 for ts-loader compatibility for new typescript version, ncc 3.33.x cannot work with ts 4.8
* Update pre-compiled
2022-08-29 16:56:02 +00:00
Balázs Orbán
6da621df63
feat: add experimental.fallbackNodePolyfills flag (#39248)
For historical reasons, Next.js has been falling back to polyfill certain Node.js APIs in the browser. `webpack` itself stopped doing it, and so should Next.js. This might unexpectedly break some packages in the ecosystem though, so it is being introduced as an experimental flag. These imports will now throw a `Module not found` error and the package maintainer should make sure that the library isn't relying on these Node.js APIs when the package is meant for browser usage. 

Let's take a look at a common example, the `crypto` API, which can be imported as `import crypto from "crypto"` but [should already be available in browsers](https://caniuse.com/cryptography). Until now, Next.js has fallen back to use a polyfilled version for the import, which resulted in a bundle-size increase.


```js
import crypto from 'crypto'
import { useEffect } from 'react'
export default function Page() {
  useEffect(() => {
    console.log(crypto)
  }, [])
}
```

it imports `crypto`, which currently resolves to [`crypto-browserify`](https://www.npmjs.com/package/crypto-browserify).

So the bundle will include `crypto-browserify` as well:
```sh
Page                                       Size     First Load JS
┌ ○ /                                      131 kB          213 kB # <--
└ ○ /404                                   194 B          82.2 kB
+ First Load JS shared by all              82 kB
  ├ chunks/framework-bcc2dc0ea27ab0c6.js   45.1 kB
  ├ chunks/main-dc2421aef72299b4.js        35.4 kB
  ├ chunks/pages/_app-a85935458980c5c2.js  708 B
  └ chunks/webpack-9b312e20a4e32339.js     836 B
```

Here, we can just remove the import, as we are [safely accessing](https://nextjs.org/docs/migrating/from-create-react-app#safely-accessing-web-apis) the [Crypto Web API](https://caniuse.com/cryptography):

```diff
- import crypto from 'crypto'
import { useEffect } from 'react'
export default function Page() {
  useEffect(() => {
    console.log(crypto)
  }, [])
}
```

Which will reduce the bundle size:

```sh
Page                                       Size     First Load JS
┌ ○ /                                      269 B          82.2 kB # <--
└ ○ /404                                   194 B          82.1 kB
+ First Load JS shared by all              81.9 kB
  ├ chunks/framework-bcc2dc0ea27ab0c6.js   45.1 kB
  ├ chunks/main-dc2421aef72299b4.js        35.4 kB
  ├ chunks/pages/_app-a85935458980c5c2.js  708 B
  └ chunks/webpack-fd82975a6094609f.js     727 B
```


This is harder to detect if the `crypto` import is in a third-party package though. By setting `experimental: { fallbackNodePolyfills: false }`, Next.js will now fail at build-time and should show where the unnecessary import comes from, so the developer can reach out to the package maintainer to fix this issue.

Note: There might be differences between the living standard and some of these older polyfills, so you have to make sure your code works well without the polyfilled version.

Related feedback: https://twitter.com/lfredolo/status/1539608666026000384
2022-08-26 23:11:57 +00:00
Jiachi Liu
7397be7792
test: pin typescript version to 4.7 (#39978)
Typescript published 4.8 and the ts tests are filling. Fix it by pining it to 4.7 temproraily 

x-ref: https://github.com/vercel/next.js/runs/8037717851?check_suite_focus=true#step:9:211
2022-08-26 16:59:33 +02:00
Jiachi Liu
e2a5b095ae
test: merge edge ssr tests (#39924)
- Group edge ssr tests, merge `edge-vs.-non-edge-api-route-priority` and `react-18-streaming-ssr` into 1 e2e test suite
- Add rewrite case to edge ssr in switchable runtime
2022-08-24 23:56:59 +01:00
JJ Kasper
1d9706f443
Remove un-necessary internal jest-worker error during ts/lint error (#39886)
This ensures we strip the un-necessary `jest-worker` error shown from an error with verifying TypeScript during build as this error just clutters the output and doesn't provide any additional helpful context. 

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

## Bug

- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`
2022-08-24 09:29:27 -05:00
JJ Kasper
08dd08ec72
Skip auto-install for missing deps in CI (#39882)
Follow-up to https://github.com/vercel/next.js/pull/39838 this skips auto-installing missing TypeScript dependencies in CI environments as this creates a side-effect which we want to avoid. 

x-ref: [slack thread](https://vercel.slack.com/archives/C03KAR5DCKC/p1661301586792559?thread_ts=1661299706.559769&cid=C03KAR5DCKC)

## Bug

- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`
2022-08-23 22:53:05 -05:00
JJ Kasper
88916fbaf0
Fix runLintCheck during build (#39883)
Follow-up to https://github.com/vercel/next.js/pull/39872 this fixes a check in `runLintCheck` causing setup to start during build and adds a regression test. 

## Bug

- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`
2022-08-23 22:36:52 -05:00
JJ Kasper
ec25b4742b
Add handling for auto installing TypeScript deps and HMRing tsconfig (#39838)
This adds handling for auto-detecting TypeScript being added to a project and installing the necessary dependencies instead of printing the command and requiring the user run the command. We have been testing the auto install handling for a while now with the `next lint` command and it has worked out pretty well. 

This also adds HMR handling for `jsconfig.json`/`tsconfig.json` in development so if the `baseURL` or `paths` configs are modified it doesn't require a dev server restart for the updates to be picked up. 

This also corrects our required dependencies detection as previously an incorrect `paths: []` value was being passed to `require.resolve` causing it to fail in specific situations.

Closes: https://github.com/vercel/next.js/issues/36201

### `next build` before

https://user-images.githubusercontent.com/22380829/186039578-75f8c128-a13d-4e07-b5da-13bf186ee011.mp4

### `next build` after


https://user-images.githubusercontent.com/22380829/186039662-57af22a4-da5c-4ede-94ea-96541a032cca.mp4

### `next dev` automatic setup and HMR handling

https://user-images.githubusercontent.com/22380829/186039678-d78469ef-d00b-4ee6-8163-a4706394a7b4.mp4


## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [x] Errors have helpful link attached, see `contributing.md`
2022-08-23 13:16:47 -05:00
JJ Kasper
c9aa2ea2cf
Tweak styled-jsx type declarations (#39474)
* Tweak styled-jsx type declarations

* fix lint
2022-08-10 15:26:54 -05:00
JJ Kasper
d64a1507a9
Ensure default _app is used when falling back to default _error (#39467)
* Ensure default _app is used when falling back to default _error

* make render check less specific due to arbitrary wait
2022-08-10 11:36:22 -05:00
JJ Kasper
997e3c0cf9
Ensure locale redirects are not applied in minimal mode (#39436) 2022-08-09 15:06:00 -05:00
Yamagishi Kazutoshi
0796b6faa9
Add runtime to PageConfig type (#37453)
* Add runtime to PageConfig type

* Add test case for runtime type

* Apply suggestions from code review

* dedupe type

* fix import

* fix lint

Co-authored-by: JJ Kasper <jj@jjsweb.site>
2022-08-07 14:16:10 -05:00
JJ Kasper
442378d21d
Fix failing escheck test (#39365) 2022-08-05 12:30:42 -05:00
Balázs Orbán
0571885ec4
test: ensure default output is correct (#39358)
So we don't regress on issues like #39090, #35913, #34629, #33314, etc.

Closes #35912

## 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-08-05 13:07:50 +00:00
Gal Schlezinger
e3181c2d77
Export URLPattern from next/server (#39219)
This commit allows the users to import URLPattern from `next/server`,
by defining a key that uses `global.URLPattern`.

Why is this any good? or: why don't we add URLPattern to the global namespace?

URLPattern is exposed as global on Edge Runtime _only_. This means that if we define a
constructor in global namespace in our TypeScript definitions, people might
have runtime errors in their Node.js functions.

Importing from `next/server` enables users to get the constructor without
risking in runtime errors and wrong type definitions.

Keep in mind, that with the current implementation, we do not check if the
constructor actually exists, but `next/server` shouldn't be imported in
Node.js functions, AFAIK.

## Related

- Fixes #38131

## Bug

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


Co-authored-by: JJ Kasper <22380829+ijjk@users.noreply.github.com>
2022-08-02 02:04:08 +00:00
Shu Ding
600bdb1eb5
Remove RSC rendering from render (#39045)
(For context, the logic and tests have been moved to `app-render`.)

## 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-07-27 22:11:02 +00:00
JJ Kasper
fd7bd12421
Fix tracing edge-runtime dependencies (#39009)
* Fix tracing edge-runtime dependencies

* update compiled

* remove old console log
2022-07-26 10:47:34 -05:00
JJ Kasper
7fa7204854
Add config for opting out of optimistic client cache behavior (#38774)
* Add config for opting out of optimistic client cache behavior

* update test
2022-07-26 10:27:39 -05:00
JJ Kasper
135a4cfc66
Add handling for prefetching onTouchStart and initial mobile testing (#38805)
This adds handling for prefetching `onTouchStart` as this gives a little more time to start parsing required scripts for a page transition if not already done that can help make the transition faster. This is based on research showing the touch start event firing on average `90ms` before click (x-ref: [source](https://instant.page/#:~:text=in%20the%20world.-,On%20mobile,-A%20user%20starts))

This also adds testing safari with playwright so we can run these in PRs instead of only after merge and adds initial mobile testing as well. 

x-ref: [slack thread](https://vercel.slack.com/archives/C7PDM7X2M/p1658250170774989?thread_ts=1658249275.178349&cid=C7PDM7X2M)

## 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-07-25 19:04:03 +00:00
Sukka
25d34057d6
feat: enhance warning messages about unanalyzable config field (#38907)
x-ref: #38750
x-ref: https://github.com/vercel/next.js/pull/38750#discussion_r926203439

cc @ijjk 

The PR implements the details about un-extractable fields in the `UnsupportedValueError`.

The PR also enhances the warning message about the unrecognizable `config` field. Now the warning message will look like this:

```
warn  - Next.js can't recognize the exported `config` field in route "/unsupported-value-type":
Unsupported node type "CallExpression" at "config.runtime".
The default config will be used instead.
Read More - https://nextjs.org/docs/messages/invalid-page-config
```

The corresponding production test case has also been updated.
2022-07-22 19:31:47 +00:00
Sukka
02c78a5c15
fix(#38743): config.runtime support template literal (#38750)
## Bug

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

Fixes #38743.
Fixes: https://github.com/vercel/next.js/pull/38750

The PR adds basic `TemplateLiteral` support for static analysis.

The corresponding re-production of #38743 has also been implemented in e2e tests.
2022-07-21 19:56:52 +00:00
Damien Simonin Feugas
90bbac44db
fix(edge): error handling for edge route and middleware is inconsistent (#38401)
## What’s in there?

This PR brings more consistency in how errors and warnings are reported when running code in the Edge Runtime:

- Dynamic code evaluation (`eval()`, `new Function()`, `WebAssembly.instantiate()`, `WebAssembly.compile()`…)
- Usage of Node.js global APIs (`BroadcastChannel`, `Buffer`, `TextDecoderStream`, `setImmediate()`...)
- Usage of Node.js modules (`fs`, `path`, `child_process`…)

The new error messages should mention *Edge Runtime* instead of *Middleware*, so they are valid in both cases.

It also fixes a bug where the process polyfill would issue a warning for  `process.cwd` (which is `undefined` but legit). Now, one has to invoke the function `process.cwd()` to trigger the error.

It finally fixes the react-dev-overlay, where links from middleware and Edge API route files could not be opened because of the `(middleware)/` prefix in their name.

About the later, please note that we can’t easily remove the prefix or change it for Edge API routes. It comes from the Webpack layer, which is the same for both. We may consider renaming it to *edge* instead in the future.

## How to test?

These changes are almost fully covered with tests:

```bash
pnpm testheadless --testPathPattern runtime-dynamic
pnpm testheadless --testPathPattern runtime-with-node
pnpm testheadless --testPathPattern runtime-module
pnpm testheadless --testPathPattern middleware-dev-errors
```

To try them out manually, you can write a middleware and Edge route files like these:

```jsx
// middleware.js
import { NextResponse } from 'next/server'
import { basename } from 'path'

export default async function middleware() {
  eval('2+2')
  setImmediate(() => {})
  basename()
  return NextResponse.next()
}

export const config = { matcher: '/' }
```

```jsx
// pages/api/route.js
import { basename } from 'path'

export default async function handle() {
  eval('2+2')
  setImmediate(() => {})
  basename()
  return Response.json({ ok: true })
}

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

The expected behaviours are:

- [x] dev, middleware/edge route is using a node.js module: error at runtime (logs + read-dev-overlay):

```bash
error - (middleware)/pages/api/route.js (1:0) @ Object.handle [as handler]
error - The edge runtime does not support Node.js 'path' module.
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime
> 1 | import { basename } from "path";
  2 | export default async function handle() {
```

- [x] build, middleware/edge route is using a node.js module: warning but succeeds

```bash
warn  - Compiled with warnings

./middleware.js
A Node.js module is loaded ('path' at line 4) which is not supported in the Edge Runtime.
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime

./pages/api/route.js
A Node.js module is loaded ('path' at line 1) which is not supported in the Edge Runtime.
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime
```

- [x] production, middleware/edge route is using a node.js module: error at runtime (logs + 500 error)

```bash
Error: The edge runtime does not support Node.js 'path' module.
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime
    at <unknown> (file:///Users/damien/dev/next.js/packages/next/server/web/sandbox/context.ts:149)
```

- [x] dev, middleware/edge route is using a node.js global API: error at runtime (logs + read-dev-overlay):

```bash
error - (middleware)/pages/api/route.js (4:2) @ Object.handle [as handler]
error - A Node.js API is used (setImmediate) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime
  2 |
  3 | export default async function handle() {
> 4 |   setImmediate(() => {})
    |  ^
```

- [x] build, middleware/edge route is using a node.js global API: warning but succeeds

```bash
warn  - Compiled with warnings

./middleware.js
A Node.js API is used (setImmediate at line: 6) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime

./pages/api/route.js
A Node.js API is used (setImmediate at line: 3) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime
```

- [x] production, middleware/edge route is using a node.js module: error at runtime (logs + 500 error)

```bash
Error: A Node.js API is used (setImmediate) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime
    at <unknown> (file:///Users/damien/dev/next.js/packages/next/server/web/sandbox/context.ts:330)
```

- [x] dev, middleware/edge route is loading dynamic code: warning at runtime (logs + read-dev-overlay) and request succeeds (we allow dynamic code in dev only):

```bash
warn  - (middleware)/middleware.js (7:2) @ Object.middleware [as handler]
warn  - Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime
   5 |
   6 | export default async function middleware() {
>  7 |   eval('2+2')
```

- [x] build, middleware/edge route is loading dynamic code: build fails with error:

```bash
Failed to compile.

./middleware.js
Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime
Used by default

./pages/api/route.js
Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime
Used by default
```

## Notes to reviewers

Edge-related errors are either issued from `next/server/web/sandbox/context.ts` file (runtime errors) or from `next/build/webpack/plugins/middleware-plugin.ts` (webpack compilation).

The previous implementation (I’m pleading guilty here) was way too verbose: some errors (Node.js global APIs like using `process.cwd()`) could be reported several times, and the previous mechanism to dedupe them (in middleware-plugin) wasn’t really effective.

Changes in tests are due to renaming existing tests such as `test/integration/middleware-with-node.js-apis` into `test/integration/edge-runtime-with-node.js-apis`. I extended them to cover Edge API route.

@hanneslund I’ve pushed the improvement you did in https://github.com/vercel/next.js/pull/38289/ one step further to avoid duplication.
2022-07-21 14:53:23 +00:00
Steven
3102899f69
Fix squoosh image optimization for Node.js 18 (#38833)
Starting in Node.js 18, the `fetch` global was made available and that caused the squoosh implementation to assume it was on a web browser and try to fetch the wasm file instead of reading it from the filesystem. This PR deletes the code trying to fetch since we know that squoosh only runs in the Image Optimization API, not the browser.

- Fixes #38020 
- Enables a test that was disabled in #38460
2022-07-20 12:24:50 -04:00
Gal Schlezinger
62eb16b603
Upgrade edge-runtime + make EdgeRuntime value overridable with an env var on compilation (#38331)
This PR introduces an environment variable that allows to modify the `EdgeRuntime` value on compilation time.
This is done to allow cloud providers like Vercel to have a different value, and enable user code and 3rd party libraries to have different code paths depending on the Edge Functions provider.

## Related

- Related to #30739

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`
2022-07-12 15:18:59 +00:00
stefanprobst
dc3bd761b4
fix: fix bundle-analyzer plugin types (#38255)
* chore: fix bundle-analyzer types

* Add test for bundle analyzer type

* fix lint

Co-authored-by: JJ Kasper <jj@jjsweb.site>
2022-07-10 14:13:24 -05:00
Gal Schlezinger
708688dd26
[edge] enable edge compiler source maps by default (#38365)
since we no longer have a single compiler for browser & edge, we can enable
source map generation by default for all edge functions. This would make it
much easier to debug and understand what's happening when deploying to prod
as the log statements will show us the actual code location instead of post
bundling and minified location.

This also removes the experimental flag as it's not needed anymore.
2022-07-06 18:17:57 +00:00
Gal Schlezinger
56e760a203
[build] validate the exported config values (#38370)
Right now if people will accidentally export a typo like `runtime: 'experimental-egde'` we will fail silently.
This commit ensures we will throw and fail loudly when such typos occur.

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`
2022-07-06 11:06:57 +00:00
Gal Schlezinger
672736c408
[edge] Make runtime addressable in compile time (#38288)
this commit allows to use EdgeRuntime as a dead code eliminator identifier:

```ts
if (typeof EdgeRuntime !== "undefined") {
  console.log("will be stripped away");
} else {
  console.log("will be kept in the bundle");
}
```

which means we're replacing `EdgeRuntime` with a literal

## Related

- Fixes #30739

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [x] 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-07-04 12:54:07 +00:00
JJ Kasper
58033c4a3c
Fix resolving dynamic routes when on returns a redirect (#38079)
* Fix resolving dynamic routes when on returns a redirect

* Update fix and add test case
2022-06-27 18:47:32 -05:00
JJ Kasper
e3fb62b6bf
Add invariant with debug information when failing to load static file (#38075) 2022-06-27 14:15:09 -05:00
Jiachi Liu
a5f8382ee3
Rename page runtime edge to experimental-edge (#38041)
* Rename page runtime edge to experimental-edge

* fix ut

* fix lint

* PageRuntime -> ServerRuntime

* rename constant
2022-06-26 20:02:24 -05:00