Commit graph

393 commits

Author SHA1 Message Date
Shu Ding
b72dc5b69f
Improve the error message when custom export fields are used in an entry (#42221) 2022-11-01 11:17:06 -07:00
Duncan Ogle
848bb3af73
Escape HTML on "<Link> with <a> child" page (#42114)
Non-escaped characters is leading this page to attempt to render the title as HTML tags. This change escapes those values so they may present correctly

https://nextjs.org/docs/messages/invalid-new-link-with-extra-anchor

<img width="524" alt="Screenshot 2022-10-29 at 06 57 16" src="https://user-images.githubusercontent.com/5629994/198817257-47b45ce9-2841-4db1-82f2-91e2c9b22808.png">



## Documentation / Examples

- [x] Make sure the linting passes by running `pnpm build && 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)
2022-10-31 16:16:42 +00:00
Steven
191710ddfe
Show error message when using legacy props on new next/image (#41930)
This PR shows a better error message when using legacy props on new
`next/image` (introduced in Next.js 13) and makes the codemod more
discoverable.
2022-10-27 12:17:28 -04:00
Balázs Orbán
4d20beb7c5
BREAKING CHANGE: feat(edge): split NextCookies to RequestCookies and ResponseCookies (#41526)
Ref: [Slack
thread](https://vercel.slack.com/archives/C035J346QQL/p1666056382299069?thread_ts=1666041444.633059&cid=C035J346QQL),
[docs update](https://github.com/vercel/front/pull/17090)

Spec: https://wicg.github.io/cookie-store/

BREAKING CHANGE:

Ref: https://github.com/vercel/edge-runtime/pull/177,
https://github.com/vercel/edge-runtime/pull/181

## 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-27 00:20:39 -07:00
Hannes Bornö
e64bf98511
Update font links and add missing error (#41910)
Adds an error that was missing. Link to beta until the changes are live.

closes #41900

## 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-26 23:00:40 -07:00
Lee Robinson
a05a0c7784
Update the documentation. (#41758)
Co-authored-by: JJ Kasper <jj@jjsweb.site>
Co-authored-by: Matt Kane <m@mk.gg>
Co-authored-by: Ismael <ismael.rumzan@gmail.com>
Co-authored-by: Balázs Orbán <info@balazsorban.com>
2022-10-26 14:04:45 -07:00
Steven
e107bc4561
Throw error <a> child in <Link> (#41756)
This PR improves the error message when `<a>` is a child of `<Link>`
2022-10-24 22:39:22 -07:00
Steven
7102050ec7
Add support for images.loaderFile config (#41585)
This PR adds a new configure property, `images.loaderFile` that allow
you to define a path to a file with an exported image loader function.

This is useful when migrating from `next/legacy/image` to `next/image`
because it lets you configure the loader for every instance of
`next/image` once, similar to the legacy "built-in loaders".
2022-10-21 12:31:53 -07: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
Lee Robinson
6101bf69ad
Add remotePatterns link to next-image-unconfigured-host (#41504)
Didn't realize the `remotePatterns` usage was already in here (not live
yet, but merged into `canary`) - so just also added on this link for the
end 👍
2022-10-17 22:06:50 -07:00
Damien Simonin Feugas
d8395e4eeb
docs: more detailed error message when failing to parse a middleware matcher (#41390)
## 📖 What's in there?

This is a follow-up for https://github.com/vercel/next.js/pull/40180
Someone made the good point that users may get directed to this error page while setting up middleware matchers. And that page has no information (yet) about it.

## Documentation / Examples

- [ ] 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: Balázs Orbán <18369201+balazsorban44@users.noreply.github.com>
2022-10-13 18:03:10 +00:00
Lee Robinson
a315c748c7
Update node-module-in-edge-runtime.md (#41375)
To be a bit more clear.

Co-authored-by: JJ Kasper <22380829+ijjk@users.noreply.github.com>
2022-10-13 04:22:04 +00:00
Damien Simonin Feugas
bef709bc74
fix(middleware): 'instanceof Function' is dynamic code false-positive (#41249)
## 🐛 What's in there?

`foo instanceof Function` is wrongly considered as Dynamic code evaluation by our static analyzer.
This PR fixes it.

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

## 🧪 How to reproduce?

1. Create a simple repro in `examples` folder:
   ```js
   // examples/instance-of-function/pages/index.js
   export default function Home() {
     return <h1>home</h1>
   }
   
   // examples/instance-of-function/middleware.js
   import { NextResponse } from 'next/server'
   
   export default async function handler() {
     console.log('is arrow a function?', (() => {}) instanceof Function)
     return NextResponse.next()
   }
   ```
1. build with next `pnpm next build examples/instance-of-function`
   > the build fails
1. rebuild next to include PR's fix `pnpm build`
1. build with new next `pnpm next build examples/instance-of-function`
   > the build works

## 📔 Notes to reviewers

`hooks.expression.for(`${prefix}Function`).tap(NAME, handleExpression)` is actually legacy code from the original implementation. It's used when finding `Function` regardless of how it is used. We only want to find `new Function()` or `Function()`, which `hooks.calls` and `hooks.new` are covering.

`eval instanceof Function` is perfectly legit code on the edge, despite its uselessness :lol-think: 

Because we got multiple people asking "how do I relax this error when my code contains unreachable dynamic code evaluation", I've copy-pasted details about `config.unstable_allowDynamic` into the error page. Because users do not always click links :blob_shrug:
2022-10-07 14:14:11 +00:00
Steven
5e6b008b56
Fix docs for next/image unconfigured hosts (#41223)
Fix docs for next/image unconfigured hosts to mention `remotePatterns`.
2022-10-06 16:51:41 +00:00
Hannes Bornö
e5be49eec1
Font loader with babel error (#41151)
Adds build error when using font loaders with babel. Otherwise you'll
get other unrelated errors.

## 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: JJ Kasper <jj@jjsweb.site>
2022-10-05 22:14:31 -07:00
Balázs Orbán
cbda3b52dc
docs(image): improve error message when sharp is missing in standalone mode (#41133)
Partially addresses #41111

## 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: JJ Kasper <22380829+ijjk@users.noreply.github.com>
2022-10-05 17:28:29 +00:00
Eliaz Bobadilla
1d026ec074
class component -> functional component (#41089)
easier to read

## 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: Balázs Orbán <18369201+balazsorban44@users.noreply.github.com>
2022-10-01 20:18:49 +00:00
Artur Sedlukha
377a39a88d
Typo in middleware upgrade guide (#40963)
<!--
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

- [ ] 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: JJ Kasper <jj@jjsweb.site>
2022-09-27 12:40:50 -07:00
Abdallah NourAldin
194b6ad1c1
update url for React Hydration Documentation (#40883)
Docs point to old
__[hydrate()](https://reactjs.org/docs/react-dom.html#hydrate)__, which
had been replaced with
__[hydrateRoot()](https://reactjs.org/docs/react-dom-client.html#hydrateroot)__
as React 18 came:

> Note:
hydrate has been replaced with hydrateRoot in React 18. See
[hydrateRoot](https://reactjs.org/docs/react-dom-client.html#hydrateroot)
for more info.

From [react 18 docs](https://reactjs.org/docs/react-dom.html#hydrate).
2022-09-26 12:35:12 -07:00
abdennor
1bbd264216
Add additional fix in hydration error document (#40675)
I had the same issue, so the fix that worked for me was pulled from this
thread https://stackoverflow.com/a/71870995

I have been experiencing the same problem lately with NextJS and i am
not sure if my observations are applicable to other libraries. I had
been wrapping my components with an improper tag that is, NextJS is not
comfortable having a p tag wrapping your divs, sections etc so it will
yell "Hydration failed because the initial UI does not match what was
rendered on the server". So I solved this problem by examining how my
elements were wrapping each other. With material UI you would need to be
cautious for example if you use a Typography component as a wrapper, the
default value of the component prop is "p" so you will experience the
error if you don't change the component value to something semantic. So
in my own opinion based on my personal experience the problem is caused
by improper arrangement of html elements and to solve the problem in the
context of NextJS one will have to reevaluate how they are arranging
their html element

<!--
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:
-->


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

Co-authored-by: JJ Kasper <jj@jjsweb.site>
2022-09-22 18:14:18 -07: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
Jan Klimo
c11310b0f1
Fix a typo in docs (#40501)
<!--
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)

Co-authored-by: Balázs Orbán <info@balazsorban.com>
2022-09-13 13:22:25 +02:00
Ryan Parker
0a093c0e82
docs(errors/large-page-data): how to see data being passed to page (#40491)
## Summary

This PR adds a note about how to see the data that this error is complaining about:

```sh
Warning: data for page "/" is xxx which exceeds the threshold of 128 kB, this amount of data can reduce performance.
```

This debug trick was something I came across in a [discussion](https://github.com/vercel/next.js/discussions/39880) and I thought it would be helpful to others like it was for me.

## 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 <22380829+ijjk@users.noreply.github.com>
2022-09-13 00:44:43 +00: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
Yusuke Hayashi
885defd442
Fix typo in error/middleware-upgrade-guide.md (#40176)
No Reponse Body -> No Response Body

<img width="330" alt="スクリーンショット 2022-09-02 16 40 04" src="https://user-images.githubusercontent.com/11132792/188084749-a1dd4ca6-b108-47ef-85d9-5f1602cb8cea.png">
2022-09-02 18:20:22 +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
Jerome Leclanche
a799d25cfa
Mention largePageDataBytes in warning docs (#39941)
Also fix the KB unit to `kB` (https://en.wikipedia.org/wiki/Kilobyte)

## 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-08-25 10:52:32 -05:00
Sukka
5360440413
fix(#39609): warns about suspense and ssr (#39676)
Currently, `next/dynamic` will opt-in to `React.lazy` if `{ suspense: true }` is used. And React 18 will always resolve the `Suspense` boundary on the server-side, effectively ignoring the `ssr` option.

The PR fixes #39609 by showing a warning message when `{ suspense: true, ssr: false }` is detected. The error documentation and the corresponding test case has also been updated.

In the future, Next.js could implement a custom version of `React.lazy` that could suspense without executing the lazy-loaded component on the server-side.

cc @huozhi 

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [x] Errors have helpful link attached, see `contributing.md`
2022-08-18 13:53:23 +00:00
M. Zakiyuddin Munziri
5f033ecb54
Fix docs path "Invalid getServerSideProps Return Value" (#39443)
# Description

The link to https://nextjs.org/docs/messages/invalid-getserversideprops-value does not exist, the correct link should be https://nextjs.org/docs/messages/invalid-getserversideprops-return-value

![image](https://user-images.githubusercontent.com/78015359/183795431-53210024-4938-4f50-9f0a-cb412383780e.png)

![image](https://user-images.githubusercontent.com/78015359/183795482-f17f31c2-cbaf-4652-ad77-5294fa8f104a.png)

# Solution

## From

Referring to the pattern, there is no `return`

![Screenshot from 2022-08-10 10-04-33](https://user-images.githubusercontent.com/78015359/183795393-ba244d6a-84b3-426c-b5ef-4e17d108902a.png)

## To

So I removed the word `return` to match the pattern

![image](https://user-images.githubusercontent.com/78015359/183796280-da6f10d1-c017-4075-942a-01d9ad234c27.png)


## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ x] 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: JJ Kasper <22380829+ijjk@users.noreply.github.com>
2022-08-10 02:34:43 +00:00
Lee Robinson
5d93753bc3
API Routes Request Helpers docs. (#39407)
Renames Middleware to Request Helpers to be both more accurate and also less confusing since Middleware is a separate feature of Next.js now.
2022-08-09 02:02:14 +00:00
Balázs Orbán
b292bdc293
fix(ts): Middleware type tweaks (#38625)
* fix internal type

* allow `void` to be returned from Middleware

* mark deprecated APIs in JSDoc

* fix typo

* add missing error page

* remove unused import
2022-08-08 09:40:44 -05:00
Josh Goldberg
963585a4fc
fix: improve logging for _devPagesManifest.json loading failures (#38046)
## Bug

- [x] Fixes #38047
- ~[ ] Integration tests added: do you want them added for such an unusual edge case?~ [Comment below: skipping](https://github.com/vercel/next.js/pull/38046#issuecomment-1207444526)
- [x] Errors have helpful link attached, see `contributing.md`: ~I'll wait until this approach & error message are confirmed before thinking more deeply on how to explain the error~

Sending a draft PR as reference ahead of time. 🙂 

Doesn't resolve the root issue of why `_devPagesManifest.json` might fail to load. But does improve the log for when it happens. I'd suggest applying this same fix to `_devMiddlewareManifest.json` too.

<table>
<thead>
<tr>
<th></th>
<th>Before</th>
<th>After</th>
</tr>
</thead>
<tbody>
<tr>
<th>Console</th>
<td>
<pre>
<code>
Failed to fetch devPagesManifest TypeError: Failed to fetch
    at PageLoader.getPageList (page-loader.js?e87a:30:53)
    at _callee$ (router.js?8684:955:45)
    at ...
</code>
</pre>
<pre>
<code>
router.js?8684:1319 Uncaught (in promise) TypeError: Cannot \
read properties of undefined (reading 'includes')
    at resolveDynamicRoute (router.js?8684:1319:16)
    at _callee$
    at ...
</code>
</pre>
</td>
<td>
<pre>
<code>
Failed to fetch devPagesManifest: TypeError: Failed to fetch
    at PageLoader.getPageList (page-loader.js?e87a:30:53)
    at _callee$ (router.js?8684:955:45)
    at ...
</code>
</pre>
</td>
</tr>
<tr>
<th>Visual</th>
<td><img alt="Screenshot of a Next.js runtime error: TypeError: Cannot read properties of undefined (reading 'includes')" src="https://user-images.githubusercontent.com/3335181/175854728-8d5c2051-1229-4da7-8af1-fc95236befae.png" /></td>
<td><img alt="Screenshot of a Next.js runtime error: Error: Failed to fetch _devPagesManifest.json. Is something blocking that network request?" src="https://user-images.githubusercontent.com/3335181/175854774-07895846-1a1c-4bb8-bf57-fa696b8c6ba4.png" /></td>
</tr>
</tbody>
</table>
2022-08-07 19:36:03 +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
Lee Robinson
5d4ac47f7a
Improve response body in Middleware error page. (#38537)
* Improve respond body in Middleware error page.

* Apply suggestions from code review

Co-authored-by: JJ Kasper <jj@jjsweb.site>
2022-07-18 20:20:23 -05:00
JJ Kasper
62f3f87891
Add next.config.js validation with ajv (#38498)
* Add next.config.js validation with ajv

* update manifest

* update lib type

* remove old tests

* update to pre-build validation code

* ensure validate output is ncced

* Apply suggestions from code review

Co-authored-by: Steven <steven@ceriously.com>

* Add example of typing next.config.js

Co-authored-by: Steven <steven@ceriously.com>
2022-07-13 13:31:55 -05:00
Damien Simonin Feugas
6e2c3821cf
feat: build edge functions with node.js modules and fail at runtime (#38234)
## What's in there?

The Edge runtime [does not support Node.js modules](https://edge-runtime.vercel.app/features/available-apis#unsupported-apis).
When building Next.js application, we currently fail the build when detecting node.js module imported from middleware.

This is an blocker for using code that is conditionally loading node.js modules (based on platform/env detection), as @cramforce reported.

This PR implements a new strategy where:
- we can build such middleware/Edge API route code **with a warning**
- we fail at run time, with graceful errors in dev (console & react-dev-overlay error)
- we fail at run time, with console errors in production

## How to test?

All cases are covered with integration tests.
To try them live, create a simple app with a page, a `middleware.js` file and a `pages/api/route.js`file.
Here are iconic examples:

### node.js modules
```js
// middleware.js
import { NextResponse } from 'next/server'
// static
import { basename } from 'path'

export default async function middleware() {
  // dynamic
  const { basename } = await import('path')
  basename()
  return NextResponse.next()
}

export const config = { matcher: '/' }
```
```js
// pags/api/route.js
// static
import { isAbsolute } from 'path'

export default async function handle() {
  // dynamic
  const { isAbsolute } = await import('path')
  return Response.json({ useNodeModule: isAbsolute('/test') })
}

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

Desired error (+ source code highlight in dev):

> The edge runtime does not support Node.js 'path' module
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime

Desired warning at build time:

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

- [x]  in dev middleware, static, shows desired error on stderr
- [x]  in dev route, static, shows desired error on stderr
- [x]  in dev middleware, dynamic, shows desired error on stderr
- [x]  in dev route, dynamic, shows desired error on stderr
- [x]  in dev middleware, static, shows desired error on react error overlay
- [x]  in dev route, static, shows desired error on react error overlay
- [x]  in dev middleware, dynamic, shows desired error on react error overlay
- [x]  in dev route, dynamic, shows desired error on react error overlay
- [x]  builds middleware successfully, shows build warning, shows desired error on stderr on call
- [x]  builds route successfully, shows build warning, shows desired error on stderr on call

### 3rd party modules not found

```js
// middleware.js
import { NextResponse } from 'next/server'
// static
import Unknown from 'unknown'

export default async function middleware() {
  // dynamic
  const Unknown = await import('unknown')
  new Unknown()
  return NextResponse.next()
}
```
export const config = { matcher: '/' }
```
```js
// pags/api/route.js
// static
import Unknown from 'unknown'

export default async function handle() {
  // dynamic
  const Unknown = await import('unknown')
  return Response.json({ use3rdPartyModule: Unknown() })
}

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

Desired error (+ source code highlight in dev):

> Module not found: Can't resolve 'does-not-exist'
Learn More: https://nextjs.org/docs/messages/module-not-found

- [x]  in dev middleware, static, shows desired error on stderr
- [x]  in dev route, static, shows desired error on stderr
- [x]  in dev middleware, dynamic, shows desired error on stderr
- [x]  in dev route, dynamic, shows desired error on stderr
- [x]  in dev middleware, static, shows desired error on react error overlay
- [x]  in dev route, static, shows desired error on react error overlay
- [x]  in dev middleware, dynamic, shows desired error on react error overlay
- [x]  in dev route, dynamic, shows desired error on react error overlay
- [x]  fails to build middleware, with desired error on stderr
- [x]  fails to build route, with desired error on stderr

### unused node.js modules
```js
// middleware.js
import { NextResponse } from 'next/server'

export default async function middleware() {
  if (process.exit) {
    const { basename } = await import('path')
    basename()
  }
  return NextResponse.next()
}
```
```js
// pags/api/route.js
export default async function handle() {
  if (process.exit) {
    const { basename } = await import('path')
    basename()
  }
  return Response.json({ useNodeModule: false })
}

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

Desired warning at build time:

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

- [x]  invoke middleware in dev with no error
- [x]  invoke route in dev with no error
- [x]  builds successfully, shows build warning, invoke middleware with no error
- [x]  builds successfully, shows build warning, invoke api-route with no error

## Notes to reviewers

The strategy to implement this feature is to leverages webpack [externals](https://webpack.js.org/configuration/externals/#externals) and run a global `__unsupported_module()` function when using a node.js module from edge function's code.
For the record, I tried using [webpack resolve.fallback](https://webpack.js.org/configuration/resolve/#resolvefallback) and [Webpack.IgnorePlugin](https://webpack.js.org/plugins/ignore-plugin/) but they do not allow throwing proper errors at runtime that would contain the loaded module name for reporting.

`__unsupported_module()` is defined in `EdgeRuntime`, and returns a proxy that's throw on use (whether it's property access, function call, new operator... synchronous & promise-based styles).

However there's an issue with error reporting: webpack does not includes the import lines in the generated sourcemaps, preventing from displaying useful errors.
I extended our middleware-plugin to supplement the sourcemaps (when analyzing edge function code, it saves which module is imported from which file, together with line/column/source)

The react-dev-overlay was adapted to look for this additional information when the caught error relates to modules, instead of looking at sourcemaps.

I removed the previous mechanism (built by @nkzawa ) which caught webpack errors at built time to change the displayed error message (files `next/build/index.js`, `next/build/utils.ts` and `wellknown-errors-plugin`)
2022-07-06 20:54:44 +00:00
Emerson Laurentino
6b8e499c7b
fix: middleware-upgrade-guide.md (#38246)
* Update middleware-upgrade-guide.md

* Update middleware-upgrade-guide.md
2022-07-01 22:24:34 -05:00
Michael Novotny
c83f94cf8b
Readds missing @next/next/no-assign-module-variable ESLint rule. (#38134)
Readds `@next/next/no-assign-module-variable` ESLint rule that was inadvertently removed in #34335 during the resolution of many merge conflicts.

This PR will get us back to a good / working state. I'll see if I can add a test to ensure all rule are accounted for in a separate PR.

Fixes #34335.

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [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)
2022-06-29 02:54:47 +00:00
Edward Thomson
dd1492d3a0
Update middleware upgrade guide w/ more rationale (#38074)
* Update middleware upgrade guide w/ more rationale

The API changes for GA are general improvements.

Our middleware upgrade guide is very helpful about describing the changes
that were made and how to react to them; include some additional "why" to
rationalize these changes.

* Update middleware-upgrade-guide.md

Avoid words like "simple" and "easy"

* Update middleware-upgrade-guide.md

Clarify the issues around "security" with responses - the previous verbiage made it sound like there was a security vulnerability; there was not.

* Apply suggestions from code review

Co-authored-by: Lee Robinson <me@leerob.io>

* Apply suggestions from code review

* Update errors/middleware-upgrade-guide.md

* Update errors/middleware-upgrade-guide.md

Co-authored-by: Balázs Orbán <info@balazsorban.com>

* Apply suggestions from code review

* Update canary -> latest

* Apply suggestions from code review

Co-authored-by: Lee Robinson <me@leerob.io>
Co-authored-by: Balázs Orbán <info@balazsorban.com>
Co-authored-by: JJ Kasper <jj@jjsweb.site>
2022-06-28 10:31:47 -05:00
JJ Kasper
8e161e1855
Middleware docs update (#38111)
* Initial outline added for middleware docs

* Feedback changes - not included new user agent yet

* edge api routes docs

* middleware page some cleanup

* moved api stuff to next server, added useragent

* waitUntil example added

* Updated env vars section

* Added cookies on the request object example

* fixed naming

* fixed import typo

* Amy feedback

* Update docs/advanced-features/middleware.md

Co-authored-by: Amy Burns <amy.burns@vercel.com>

* first commit

* more fixes

* re-structuring based on feedback

* changes to middleware.md

* updates to edge-api-routes

* code typo

* Update docs/advanced-features/middleware.md

Co-authored-by: JJ Kasper <jj@jjsweb.site>

* Update edge-api-routes.md

* Update Edge Runtime API docs

* Clarify API docs

* Update

* Update docs/advanced-features/middleware.md

* Update switchable runtime docs

* Update response

* experimental-edge

* Update docs/advanced-features/middleware.md

* Add example of forwarding headers and address comments

* Add proxying headers to middleware upgrade guide

* Apply suggestions from code review

Co-authored-by: Jeff Escalante <jescalan@users.noreply.github.com>

* fix middleware directory spec

* localization explanation

* update detecting runtime

* Update docs/advanced-features/react-18/switchable-runtime.md

Co-authored-by: Balázs Orbán <info@balazsorban.com>

* fix prettier issues

* table fix

* Update docs/advanced-features/react-18/switchable-runtime.md

Co-authored-by: Jeff Escalante <jescalan@users.noreply.github.com>

* Update docs/api-routes/edge-api-routes.md

Co-authored-by: Jeff Escalante <jescalan@users.noreply.github.com>

* lint-fix

Co-authored-by: molebox <hello@richardhaines.dev>
Co-authored-by: Amy Burns <amy.burns@vercel.com>
Co-authored-by: Ismael Rumzan <ismael.rumzan@gmail.com>
Co-authored-by: Lee Robinson <me@leerob.io>
Co-authored-by: Balázs Orbán <info@balazsorban.com>
Co-authored-by: Jeff Escalante <jescalan@users.noreply.github.com>
Co-authored-by: Ismael <ismael@vercel.com>
2022-06-28 10:22:48 -05:00
Dom Sip
a90349d519
Update middleware-upgrade-guide to be consistent (#38102)
Update middleware-upgrade-guide.md

Ensure that before and after examples are consistent
2022-06-28 14:48:57 +02:00
Javi Velasco
0f33c0cbf5
Rephrase middleware location (#38073)
It is possible that users that are defining `src/pages` in their project confuse the "project root" to locate middleware with the actual project root instead of `src/middleware` so this PR rephrases the migration guide to make explicit that the it should be located **next** to the `pages` folder.
2022-06-27 17:13:19 +00:00
Steven Tey
8019cf002a
Added ESLint upgrade instructions to middleware upgrade guide (#38008)
## 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: JJ Kasper <22380829+ijjk@users.noreply.github.com>
2022-06-27 00:20:36 +00:00
M. Zakiyuddin Munziri
2833904b6f
Fix typo for rewrites/redirects to rewrite/redirect (#38016)
Co-authored-by: JJ Kasper <jj@jjsweb.site>
2022-06-26 16:17:34 -05:00
Lee Robinson
5646e43f83
Fix typo for rewrites to rewrite. (#38000) 2022-06-24 15:45:02 -05:00
Balázs Orbán
a590c4e7f3
docs: return response in code example (#37985)
* Update middleware-upgrade-guide.md

* lint-fix

Co-authored-by: JJ Kasper <jj@jjsweb.site>
2022-06-24 11:13:40 -05:00
Steven
e28d03c5a4
Add experimental next/future/image component (#37927)
This PR introduces a new experimental component, `next/future/image`, which is inspired by the existing experimental `layout="raw"`.

The difference is that much of the code has been deleted in order to reduce client-side code as well as reduce complexity:

- No `layout` prop
- No `loader` config (although `loader` prop works)
- No `IntersectionObserver`, use native `loading="lazy"` 
  - No `lazyBoundary`
  - No `lazyRoot`
- No `fill` (yet) so width & height are required
- No `objectFit` (use `style` instead)
- No `objectPosition` (use `style` instead)

This improves performance because native `loading="lazy"` doesn't need to wait for React Hydration and client-side JS.

In a future PR, we will modify `next/image` to remove `layout="raw"` since this new component supersedes it.

## Feature

- [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-06-24 14:56:05 +00:00
Lee Robinson
b0533635ab
Update Middleware beta message. (#37934)
To help folks find the upgrade guide.
2022-06-23 01:11:31 +00:00
Lee Robinson
f3c1bcfc2f
Change Middleware error guide from .js to .ts. (#37858)
Feedback:

> Hello :D may it be that the types should be imported in a TS file, so I think the extension of the file should be updated here :) /middleware.js -> /middleware.ts (or no types)
2022-06-20 21:56:19 +00:00