The link to the useSearchParams ref within the File Conventions > layout.js page currently links to the useParams ref, which is wrong and may lead to confusion as the useParams and useSearchParams APIs operate differently.
TypeScript 5.2 now supports `Response.json` (https://github.com/microsoft/TypeScript/issues/52841). That means, if we just need to return a JSON `Response`, we no longer need to import `NextResponse`. This PR updates all such instances in the documentation to use `Response.json`.
This will be the recommended way of passing extra arguments to a Server Action. A couple of reasons behind:
- This is better than putting a hidden `<input hidden value={userId}/>` because that will appear in the SSR'd HTML as full text and cannot be encoded. With `.bind`, we can handle that in the future.
- This is better than event callbacks `onSubmit={(e) => { await updateUser(userId, e.target.formData) }}` as this supports progressive enhancement.
- This is better than re-creating a new action `action={async (formData) => { "use server"; return updateUser(userId, formData) }}` as inlined `"use server"` only works in Server Components.
In "app/actions.ts" the function is named like create(), but in "app/add-form.tsx" file "createTodo" function is imported and used. This is related to TypeScript examples, .js files are ok.
### What?
Renamed a function.
### Why?
There are two example files in docs ([Error Handling](https://nextjs.org/docs/app/building-your-application/data-fetching/forms-and-mutations#error-handling) section) and the `app/add-form.tsx` is importing function `create` from `app/actions.ts` by another name (`createTodo`).
### How?
Fixed by renaming function to `createTodo`, to match .js file with the same example.
### Why?
Whenever I run `create-next-app` and reach this question
```
Would you like to customize the default import alias? No / Yes
```
I always have to select "No", because I don't remember what this default import alias here is. [It _is_ documented to be `@/*`](https://nextjs.org/docs/app/api-reference/create-next-app#non-interactive), but the documentation is relatively hidden and not many people know about it – it's also easy to forget.
Even more confusingly, the next question ("What import alias would you like configured?") doesn't have this `@/*` as the default answer, but the user's last choice as the default answer instead (which could be different from `@/*` – making people wonder if Next.js changed their defaults overnight).
I suppose it would be better to just make it clear in the prompt itself, so people with skill issues who happen to forget that default value (like me) can still confidently select "Yes" if they want `@/*`, without having to do "No" and manually type `@/*` again.
### How
```diff
- Would you like to customize the default import alias?
+ Would you like to customize the default import alias (@/*)?
```
as many developers are moving to bun, its a good idea that it also be included as an installation method.
Co-authored-by: Steven <229881+styfle@users.noreply.github.com>
### What?
Fixing a little mistake in the documentation, where the placement of the `extension` option for `createMDX()` was described as being inside the `options` property:
```ts
const withMDX = createMDX({
options: {
extension: /\.mdx?$/,
```
But it's actually a property of its own:
```ts
const withMDX = createMDX({
extension: /\.mdx?$/,
```
I confirmed that the latter is correct because:
- It solves an issue I was having: Unable to import `.md` files
- On the same docs page, there's another place where it mentions this `extension` option and the code example is correct there
- The option is described in a similar issue, such as https://github.com/vercel/next.js/issues/45431#issuecomment-1410363864
Issue: https://github.com/vercel/next.js/issues/53888
Added "not-found.js" information to error.mdx after the `global-error.js`. Please approve.
Co-authored-by: Lee Robinson <9113740+leerob@users.noreply.github.com>
```
Pages and Layouts
The Pages Router has a file-system based router built on the [concept of pages](https://nextjs.org/docs/pages/building-your-application/routing/pages-and-layouts).
```
Change requested:
Here `concept of pages` hyperlinks routes to the current page. This bit confusing for someone trying to learn next.js. removing the hyperlink to the text would make clear.
## Why?
Although the left padding makes the output looks good in the terminal, it causes this weird alignment in almost all bug reports:
```yaml
Operating System:
Platform: win32
Arch: x64
Version: Windows 10 Pro
Binaries:
Node: 18.12.0
npm: N/A
Yarn: N/A
pnpm: N/A
Relevant Packages:
next: 13.5.2-canary.2
eslint-config-next: 13.5.2
react: 18.2.0
react-dom: 18.2.0
typescript: 5.2.2
Next.js Config:
output: N/A
```
If I want it to look nice in the bug report
```yaml
Operating System:
Platform: darwin
Arch: arm64
Version: Darwin Kernel Version 23.0.0: Thu Aug 17 21:23:02 PDT 2023; root:xnu-10002.1.11~3/RELEASE_ARM64_T8112
Binaries:
Node: 20.3.1
npm: 9.6.7
Yarn: 1.22.19
pnpm: 8.6.12
Relevant Packages:
next: 13.5.2
eslint-config-next: N/A
react: 18.2.0
react-dom: 18.2.0
typescript: 5.2.2
Next.js Config:
output: N/A
```
I have to paste this to a text editor and manually remove the first four spaces on every lines.
### How?
This PR removes that four-space padding to make future bug reports look a bit nicer.
- Removes a line from next docs that is no longer accurate:
> Currently, if a route uses a Server Action, it is required to render
dynamically.
According
With the release of Next.js 13.5, Server Actions now work with fully
static routes (including revalidating data with ISR).
<!-- 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(s) that you're making:
## For Contributors
### Improving Documentation
- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide
### Adding or Updating Examples
- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md
### Fixing a bug
- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md
### Adding a feature
- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md
## For Maintainers
- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change
### What?
### Why?
### How?
Closes NEXT-
Fixes #
-->
Co-authored-by: JJ Kasper <jj@jjsweb.site>
While an import may work on initial load, fast refresh fails, and also this can also cause issues when trying to deploy your project to Vercel, resulting in your component not being found.
This could save people time when they run into this issue, and I wish this small nuance, would've been in the docs.
Co-authored-by: Steven <229881+styfle@users.noreply.github.com>
- remove the slash before `pathname` (already included in the value).
- add `search` and `hash` values in redirected url:
- retains these values on redirect
- they already have `?` and `#` respectively
Co-authored-by: Balázs Orbán <18369201+balazsorban44@users.noreply.github.com>
[As of Bun v1.0.0](https://bun.sh/blog/bun-v1.0#changelog-since-v0-8), `bun dev` runs the "dev" script from package.json. Therefore, as with Yarn and pnpm, the "run" command is not necessary.
This PR changes the `create-next-app` README templates to show `bun dev` instead of `bun run dev`.
### What?
Follow-up of #54926.
While that PR's main fix is no longer necessary due to the removal of render workers, I figure that some changes are nice-to-have and have isolated them into this PR. This includes fixing `appUrl` and `networkUrl` in `start-server`, fixing docs and removing some unnecessary template literals in `turbopack-warning`.
### How?
`appUrl` now tries to use `hostname` instead of `actualHostname` (an address like `example.com` seems to be more useful here than an IP like `xxx.xxx.xxx.xxx`), and `networkUrl` is now prefixed with `http://`.
Other simple changes include fixing docs.
Co-authored-by: Zack Tanner <1939140+ztanner@users.noreply.github.com>
This PR clarifies `isrMemoryCacheSize` value units. Units is not obvious
due to `Defaults to 50MB` comment and lack of TSDoc comments
Co-authored-by: Lee Robinson <me@leerob.io>
Co-authored-by: JJ Kasper <jj@jjsweb.site>
The `libsql` package is a fork of `better-sqlite3` that powers the Turso database client. Let's add `libsql` to the list of external packages, like `better-sqlite3`, so that people don't have to add extra configuration for their Next.js applications.
nonce's are limited to characters found in base64 encoding, uuids contain '-' which breaks the spec,
converting to a base64 string after generating simplifies this
---
This was a bit gotcha in our project, there are a few tools that only expect there to be a single `-` and do a split based off it (so when there are >1 they fail)
## Rules for nonce's
- The nonce must be unique for each HTTP response
- The nonce should be generated using a cryptographically secure random generator
- The nonce should have sufficient length, aim for at least 128 bits of entropy (32 hex characters, or about 24 base64 characters).
- Script tags that have a nonce attribute must not have any untrusted / unescaped variables within them.
- The characters that can be used in the nonce string are limited to the characters found in base64 encoding.
Ports content from the Pages and Layouts section about templates and formats to match other API reference pages.
Co-authored-by: Michael Novotny <446260+manovotny@users.noreply.github.com>
> Layouts do not have access to the current route segment(s). To access route segments, you can use useSelectedLayoutSegment or useSelectedLayoutSegments in a Client Component.
The term "current" is confusing.
It should be only the route segments under the layout. For example: `app/layout.tsx` can not access `app/[slug]`.
Missing word in client component page in docs when discussing the effect of "use client" on a client component's children and imported components. Not sure if 'children' is the appropriate word or whether there should be a reference to imported components too.
Update the code snippet for configuring API Routes to include `maxDuration` as an option.
Co-authored-by: Lee Robinson <9113740+leerob@users.noreply.github.com>
There's been some confusion on the correct way to add a `nonce`, so took the opportunity here to:
- Add a new docs page for Content Security Policy
- Explained how to generate a `nonce` with Middleware
- Showed how to consume the `nonce` in a route with `headers`
- Updated the `with-strict-csp` example
- Update the `nonce` error message page
- Backlinked to the new page in a few places in the docs
### What?
Clarify the "Forms and Mutations" docs.
### Why?
This may be opinionated, but I believe this section of the docs starts out assuming that the user knows how the `<form>` HTML works. Coming from the client side React world, most developers are used to using state in forms. Clarifying that this data is accessible via the standard web API [FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData) is essential for both transitioning developers and new developers.
### What?
This adds to the docs a guide for migrating a Vite application to
Next.js. It also contains a section that lists the reasons why one would
want to switch from Vite to Next.js.
### Why?
This guide is helpful for developers that want to switch to Next.js but
don't know how difficult that would be and how to do it. The "Why?" list
is also helpful to developers who haven't yet been convinced to switch
or need help formulating the reasons to switch to decision-makers.
This guide was [first published on the Inngest
blog](https://www.inngest.com/blog/migrating-from-vite-to-nextjs). To
our own surprise, we were able to [migrate from Vite to
Next.js](https://github.com/inngest/inngest/pull/479) our [Dev Server
app](https://github.com/inngest/inngest/tree/main#the-inngest-dev-server)
in less than a day, which motivated us to share our learnings with the
community.
### How?
The guide aims to have the minimum number of steps to get a working
Next.js application so that
the reader can then adopt Next.js features incrementally. This means the
migration of the router isn't part of this guide. However, this would be
something valuable to document at a later time so that the reader can
also learn how to migrate to the App Router and get all the Next.js
benefits.
## What?
- Updated the heading structure in the documentation to maintain a consistent hierarchy.
- All primary points now use `###` for better readability and understanding of content structure.
## Why?
While reviewing the documentation, I noticed that the heading levels were inconsistent between sections 1, 2, and 3-5.
for internal:
https://vercel.slack.com/archives/C03S8ED1DKM/p1691700057242999
### Problem
- The existing [`redirect()`
function](https://nextjs.org/docs/app/api-reference/functions/redirect)
can't control the status code.
- The existing [`redirect()`
function](https://nextjs.org/docs/app/api-reference/functions/redirect)
returns a 307 HTTP redirect response while it returns a 308-equivalent
meta tag `<meta http-equiv="refresh" content="0;url=/foo"/>` in
streaming response (e.g., suspense boundary), making the behavior
inconsistent.
### Solution
Adding a new `permanentRedirect()` function and changing the meta tag
default accordingly.
| func | HTTP status | meta tag |
|---|:---:|---|
| `redirect()` | 307 | `<meta http-equiv="refresh"
content="1;url=/foo"/>` |
| `permanentRedirect()` | 308 | `<meta http-equiv="refresh"
content="0;url=/foo"/>` |
ref.
https://developers.google.com/search/docs/crawling-indexing/301-redirects
---------
Co-authored-by: JJ Kasper <jj@jjsweb.site>
Co-authored-by: Tim Neutkens <tim@timneutkens.nl>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
add if statement, because typescript throws error: revalidatePath require `string`, but `searchParams.get('path')` returns `string|null` type
Co-authored-by: JJ Kasper <22380829+ijjk@users.noreply.github.com>
https://nextjs.org/docs/app/building-your-application/data-fetching/forms-and-mutations
Some of the code blocks where I only specified TS code snippets aren't
working with JS as well (when there are no types). I think I might have
incorrectly assumed you could leave those out. So added the JS snippets
in here (same code, just different file names).
This PR is a larger change to documentation to make the following
updates:
- Deconstructs [Server
Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions)
into "Forms and Mutations" and an API reference
- Removes content in place of future React API documentation pages
- Removes outdated [Building
Forms](https://nextjs.org/docs/pages/building-your-application/data-fetching/building-forms)
docs from the Pages Router and adds conditional content for both routes
in "Forms and Mutations"
- Adds TypeScript code blocks to API Routes page, recommends Route
Handlers for isomorphic signatures.
- Updates `revalidatePath` and `revalidateTag` docs to have a Server
Actions example.
---------
Co-authored-by: Delba de Oliveira <32464864+delbaoliveira@users.noreply.github.com>
Hello!
I recently tried to cache the `.next/cache` directory in a GitHub action following what was said in the documentation and realized that hashing the source files didn't work properly.
This problem also occured in [next-cache](https://github.com/jongwooo/next-cache) and was fixed by [this PR](https://github.com/jongwooo/next-cache/pull/17).
This PR simply changes the example from the documentation to apply the same fix (stop using brackets in the patterns passed to `hashFiles`).
Hope it helps!
### Improving Documentation
- [x] Run `pnpm prettier-fix` to fix formatting issues before opening the PR.
- [x] Read the Docs Contribution Guide to ensure your contribution follows the docs guidelines: https://nextjs.org/docs/community/contribution-guide
This PR adds missing parameters to the `useSelectedLayoutSegment` & `useSelectedLayoutSegments` hooks since they take *optional* `parallelRoutesKey`.
Co-authored-by: Lee Robinson <9113740+leerob@users.noreply.github.com>
We initially wrote the [React
page](https://nextjs.org/docs/getting-started/react-essentials) to
introduce Server Components in the App Router, but over time, some
implementation details have changed, and the information has become
stale. The React team is working on adding new docs, so I'd like to
change the narrative on the Next.js docs from "client vs. server
components" to "writing code for the server and for the client" - and
link back to the React documentation when it becomes available.
As React developers, we're very familiar with writing code for the
client, it's nice and simple. But doing so comes at the expense of not
being familiar with the server. The aim of these docs is to help
developers become proficient in both the client and server environments.
I'd like to take it back to the foundations, and not use abstractions
like SSG and CSR, MPAs or SPAs, as those terms come with their own set
of assumptions that make it harder to understand how RSC works. Instead,
we'll focus on the request lifecycle, show how application code flows
from the server to the client, and discuss the trade-offs of doing
operations in each environment.
- [x] Page: Rendering Fundamentals
- [x] Environments: Client and Server
- [x] Request-response lifecycle
- [x] Network Boundary
- [x] Page: Server Components
- [x] Benefits and use cases of server rendering
- [x] How to use Server Components in Next.js
- [x] How Server Components are rendered
- [x] Static Rendering
- [x] Dynamic Rendering
- [x] Streaming
- [x] Page: Client Components
- [x] Benefits and use cases of client rendering
- [x] How to use Client Components in Next.js
- [x] How Client Components are rendered
- [x] Initial vs. Subsquent navigation
- [x] Page: Composition Patterns
- [x] When to use client and server components
- [x] Server Component Patterns
- [x] Client Component Patterns
- [x] Interleaving Client and Server Components
- [ ] ~Diagrams~ will follow up with new PR.
- [x] Set up redirects: https://github.com/vercel/front/pull/24917
---------
Co-authored-by: Térence Hollander <hollanderterence@gmail.com>
Co-authored-by: shawnthwei <32075290+shawnthwei@users.noreply.github.com>
Co-authored-by: Michael Novotny <manovotny@gmail.com>
Fixed `next/jest.js` import in documentation. without `.js` it show this error
```
Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'F:\React\my-project\node_modules\next\jest' imported from F:\React\my-project\jest.config.mjs
Did you mean to import next/jest.js?
at new NodeError (node:internal/errors:399:5)
at finalizeResolution (node:internal/modules/esm/resolve:326:11)
at moduleResolve (node:internal/modules/esm/resolve:945:10)
at defaultResolve (node:internal/modules/esm/resolve:1153:11)
at nextResolve (node:internal/modules/esm/loader:163:28)
at ESMLoader.resolve (node:internal/modules/esm/loader:838:30)
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:424:18)
at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:77:40)
at link (node:internal/modules/esm/module_job:76:36)
```
### Why?
Many developers are asking how to add internationalized routing in the App Router as it works in the Pages Router. [next-i18n-router](https://www.npmjs.com/package/next-i18n-router) is a very helpful package that fully solves this challenge.
### How?
Unlike the example provided in these Next.js i18n docs, [next-i18n-router](https://www.npmjs.com/package/next-i18n-router) does not require nesting all pages in a `[lang]` dynamic segment. It also allows for the default language to be accessible without a locale prefix in the path (just like in the Pages Router).
It includes locale detection based on the `accept-language` header as recommended in the Next.js docs, as well as support for the `NEXT_LOCALE` cookie to set a user's preferred language (just like in the Pages Router).
Clarify what status code is returned when streaming, and in relation to `redirect` and `not-found`.
Relates to: https://github.com/vercel/next.js/pull/54361
Co-authored-by: Lee Robinson <9113740+leerob@users.noreply.github.com>
Fixes: https://vercel.slack.com/archives/C03S9JCH2Q5/p1692619927373449
- Updates wording on nesting, to say it's not the actual output, but rather how `template.js` nests between `layout.js` and its children.
- Remove mention of animations, needs further clarification.
Hello,
I just make this PR because the `/me.png` example is not in "remote images" section but in "local images", that's why I propose to edit this :)
Thank you!
### Improving Documentation
- [x] Run `pnpm prettier-fix` to fix formatting issues before opening the PR.
- [x] Read the Docs Contribution Guide to ensure your contribution follows the docs guidelines: https://nextjs.org/docs/community/contribution-guide
Partial fix for #54012: do not generate a blur image in the image loader when the image is detected to be animated, rather than returning the *entire* animated image as the blur image.
When implementing `opengraph-image` in my [personal-site-project](https://github.com/kylemcd/personal-site). I was consistently running into issues where custom fonts would either only work locally or only work on vercel. To me it seemed like differences in pathing in `edge` vs `nodejs` runtimes. After digging around I found issue #48081, more specifically [this comment](https://github.com/vercel/next.js/issues/48081#issuecomment-1565842740) where moving the `fetch` for the font into the `Image` function solved the issue.
I'm not sure if this is 100% the correct fix, or if this is an issue that needs to be solved in another way. If that's not the case this PR updates the documentation around `opengraph-image` to have the fetch for custom fonts inside of the `Image` function.
Added a switcher on a code snippet under heading -> `Using Cookies`, just like the other code snippets on this page got one..
(For those who don't know what a switcher is -> It's just a simple functionality for changing `typescript` code to `javascript` and vice-versa, kind of a UI feature for better experience`
Co-authored-by: Balázs Orbán <18369201+balazsorban44@users.noreply.github.com>
Previous of after (before in linked issue)
```
❯ pnpm add --save-dev @next/eslint-plugin-next
Already up to date
Progress: resolved 525, reused 517, downloaded 0, added 0, done
Done in 6.4s
```
Resolves#53937
Adds support for base64-encoded `placeholder`. Enables using placeholders without the "blur" effect.
Fixes#47639
- [x] Add support for DataURL placeholder
- [x] Add tests
- [x] Update docs
Co-authored-by: Steven <229881+styfle@users.noreply.github.com>
## For Contributors
### Improving Documentation
- [x] Run `pnpm prettier-fix` to fix formatting issues before opening the PR.
- [x] Read the Docs Contribution Guide to ensure your contribution follows the docs guidelines: https://nextjs.org/docs/community/contribution-guide
### What?
Add instructions for using `bun/bunx` where relevant. I only added mentions where npm/yarn/pnpm were all already listed.
### Why
Bun can be used as a runtime-agnostic [package manager](https://bun.sh/package-manager) and script runner in any project with a `package.json`.
(Sorry, I probably should have consolidated this with https://github.com/vercel/next.js/pull/53467)
Co-authored-by: Steven <229881+styfle@users.noreply.github.com>
You can technically get similar ISR behavior setting the `Cache-Control` in `getServerSideProps()`, but this won't be automatically bypassed when enabling Preview Mode or Draft Mode so this PR adds that to the documentation.
x-ref: [slack discussion](https://vercel.slack.com/archives/C03S8ED1DKM/p1691514209722429)
In the data fetching page, we discuss the different ways you can fetch data in Next.js. This PR adds a fourth option which is to call route handlers from client components. I've also added a note that you shouldn't call a route handler from a server component.
Co-authored-by: Lee Robinson <9113740+leerob@users.noreply.github.com>
This PR updates cache revalidation snippets in the docs. It seems that `res` should not be there since you can't find it anywhere in the snippet so I suppose that the intent was to use `NextResponse` instead. Another thing is that now we're checking the existence of the params so typescript doesn't get mad at us. And last I changed the methods to `POST` since AFAIK webhooks normally use the `POST` method.
Please let me know if there's anything left to do on my side.
Have a great day!
Co-authored-by: Steven <229881+styfle@users.noreply.github.com>
This adds support for `--use-bun` to `create-next-app` to use `bun
install` when bootstrapping a new project.
```
npx create-next-app --use-bun
```
As with Yarn and pnpm, it reads from `npm_config_user_agent` to
determine if the user ran `bunx create-next-app`. If so, it defaults to
using Bun.
```sh
bunx create-next-app
```
## For Contributors
### Improving Documentation
- [x] Run `pnpm prettier-fix`
- [x] `pnpm build && pnpm lint`
- [x] Added test to
`test/integration/create-next-app/package-manager.test.ts`
---------
### What?
Fix documentation about `fetch` polyfilling, and drop `node-fetch` references.
### Why?
Since we stopped using `node-fetch` in `next` in favor of `undici` there were some inconsistencies in the docs, and unused references to the `node-fetch` package inside `packages/next`-
Noted this while answering this [Slack thread](https://vercel.slack.com/archives/C03S8ED1DKM/p1691089801007129)
Adding docs about how Dynamic Segments aren't supported with Static Exports.
- Related to https://github.com/vercel/next.js/issues/48022
Co-authored-by: Steven <229881+styfle@users.noreply.github.com>
Based on the feedback from #53435, this PR adds an example of redirection inside Server Actions to the docs. Currently, we have examples of getting/setting cookies but there's nothing for `redirect()`.
Added additional methods for deleting a cookie
Co-authored-by: Lee Robinson <9113740+leerob@users.noreply.github.com>
Co-authored-by: JJ Kasper <22380829+ijjk@users.noreply.github.com>
This PR:
- Makes minor content and formatting improvements
- Updates caching diagrams:
- Adds missing static/dynamic diagram (fixes#53460)
- Tweaks designs to explain things better
- Increases font sizes
Relies on: https://github.com/vercel/front/pull/24321
We got some feedback from that there is missing information when working with responsive images.
This PR adds a new section for Responsive Images along with some recipes how to achieve that.
### What?
Link to dynamic rendering is not appearing as such in the App router's draft-mode docs.
### Why?
The formatting is wrong, it misses a parenthesis
### How?
Added the missing parenthesis
Follow up from https://github.com/vercel/next.js/pull/52514.
We're still missing the static and dynamic diagram, it was missed in the PR to `front` to add the original diagrams. We'll need to get that in as well, could be here, or in a follow up.
This PR document the caching semantics in Next.js, how they interact, and what APIs affect them. We're also taking the opportunity to consolidate terminology, remove duplicate content, and update sections of the docs that relate to caching.
### Documentation
- [x] Create a new section for caching
- [x] Explain how the different caching mechanisms work
- [x] Request Memoization (React Cache)
- [x] Persistent Data Cache
- [x] Persistent Full Route Cache
- [x] In-memory, client-side Router Cache
- [x] Document how different APIs affect caching
- [x] Document cache interactions
- [x] Clean up stale information in the other docs sections
- [x] Routing Section
- [x] Move advanced navigation topics from fundamentals to **How Navigation Works** section
- [x] Rewrite the **How Navigation Works** section
- [x] Rendering Section
- [x] Simplify fundamentals page
- [x] Rewrite the **Static and Dynamic Rendering** pages
- [ ] ~Create a page to explain how **Client and Server Components** are rendered~. Moved to this PR: https://github.com/vercel/next.js/pull/51579
- [x] Data fetching section
- [x] Consolidate data fetching story for fetching, caching, and revalidating
- [x] Clarify data fetching story with 3rd party libraries and React `cache`
- [x] Create **Data Fetching Patterns** page
- [x] Document other related behaviors:
- [x] Update information on scroll position for back/forward navigation
- [x] Remove the concepts of **soft and hard navigation**
- [x] Remove the concepts of **static and dynamic data fetching**
- [x] Use consistent terminology **runtime** 👉🏼 **request time**. Runtime for Edge and Node.js, request time to describe when dynamic stuff happens
- [x] `generateStaticParams` being able to seed the Full Route Cache
- [x] Polish 💅🏼
---
### Related PRs:
- Diagrams: https://github.com/vercel/front/pull/24142
- Redirects: https://github.com/vercel/front/pull/24179
While `not-found.js` components do not accept any props, you can still turn the `not-found.js` component into an async server component to fetch dynamic data:
```tsx filename="app/blog/not-found.tsx" switcher
import Link from 'next/link'
import { headers } from "next/headers";
export default async function NotFound() {
const headersList = headers();
const domain = headersList.get("host")
const data = await getSiteData(domain)
return (
<div>
<h2>Not Found: {data.name}</h2>
<p>Could not find requested resource</p>
<p>
View <Link href="/blog">all posts</Link>
</p>
</div>
)
}
```
Co-authored-by: Lee Robinson <9113740+leerob@users.noreply.github.com>
Co-authored-by: JJ Kasper <22380829+ijjk@users.noreply.github.com>
changing AI example model from `text-davinci-003` to `gpt-3.5-turbo`
which is in a `chat/route.ts` format.
The alternative but with "completition" style would be a bit longer code
like:
```
// app/api/completion/route.ts
import { Configuration, OpenAIApi } from 'openai-edge'
import { OpenAIStream, StreamingTextResponse } from 'ai'
export const runtime = 'edge'
const apiConfig = new Configuration({
apiKey: process.env.OPENAI_API_KEY!,
})
const openai = new OpenAIApi(apiConfig)
function buildPrompt(prompt: string) {
return prompt.split('\n').map((message) => ({
role: 'user',
content: message,
}));
}
export async function POST(req: Request) {
// Extract the `prompt` from the body of the request
const { prompt } = await req.json();
// Request the OpenAI API for the response based on the prompt
const response = await openai.createChatCompletion({
model: 'gpt-3.5-turbo',
stream: true,
messages: buildPrompt(prompt),
max_tokens: 500,
temperature: 0.7,
top_p: 1,
frequency_penalty: 1,
presence_penalty: 1,
})
// Convert the response into a friendly text-stream
const stream = OpenAIStream(response)
// Respond with the stream
return new StreamingTextResponse(stream)
}
```
<!-- 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(s) that you're making:
## For Contributors
### Improving Documentation
- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide
### Adding or Updating Examples
- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md
### Fixing a bug
- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md
### Adding a feature
- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md
## For Maintainers
- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change
### What?
### Why?
### How?
Closes NEXT-
Fixes #
-->
---------
Co-authored-by: Lee Robinson <me@leerob.io>
Co-authored-by: Tim Neutkens <tim@timneutkens.nl>
Co-authored-by: JJ Kasper <jj@jjsweb.site>
## Description
This PR updates the provided example of nginx.conf in the documentation. The changes introduce more flexibility and clarity, making the example easier to understand and more suited for general use.
## What?
Changes include ↓
- Modifying the root directory to `/var/www/out`. This aligns more closely with typical server configurations and separates the public web content from other parts of the server.
- Updating the try_files directive for the `/` location block. The directive now attempts to serve `$uri`, `$uri.html`, and `$uri/` in that order. This setup caters to the common pattern in static websites of serving files derived directly from the URL and correctly handles URLs that omit the .html extension.
- The `/blog/` location block is retained as is, with the rewrite directive still relevant and not requiring changes.
## Why?
These modifications aim to improve the applicability of the example to a wider range of use cases and make it more comprehensible for new users.
## How?
The changes were made directly to the `nginx.conf` example provided in the docs, following the standard syntax and conventions of Nginx configuration files.
Please let me know if there are any questions, or if further modifications are needed !!
Co-authored-by: JJ Kasper <22380829+ijjk@users.noreply.github.com>
Colocated unit tests (such as ones in `packages/next` and `packages/font`) weren't running in CI since `run-tests` marks the glob cwd as `<root>/tests`. This modifies the working directory to be the root so the new expanded test pattern will pick up files outside of `test/`.
Several of these tests were failing so there are updates in here to fix them. Specifically:
- Source Sans Pro font was renamed to Source Sans 3
- `fillCacheWithDataProperty` test was hitting the `bailOptimistic` code path
- `resolve-metadata` had an invalid assertion (`rel: icon` gets added as part of `IconsMetadata`)
- `resolve-opengraph` wasn't handling undefined images
- `server-patch-reducer` now use inline snapshots as one was failing since it now has a prefetchCache
setLoading must be "true" at first and then set to "false". The documentation, as is, always has the value of setLoading set to "false".
The purpose of this code is to show "...loading" on the screen while the data is being fetched. In order for this to happen, setLoading must be initially set to "true" and then (after the data is successfully loaded) set to "false", since the line `if (isLoading) return <p>Loading...</p>` is asking if the content is still loading, and if it is, it'll return a message indicating it.
Because of this
### What?
setLoading should be set to "true" at first.
### Why?
Because the code then asks if the content is being loaded. The code (as is) always has setLoading set as "false" and it doesn't show the loading message when it's supposed to.
### How?
I changed the line to `const [isLoading, setLoading] = useState(true)`.
Co-authored-by: Steven <229881+styfle@users.noreply.github.com>
Previously, this warning message assumed the user knew what `yarn` was and had it installed.
This PR changes the warning message to assume the user knows what `npm` is and has it installed, since `npm` ships with the official `node` installation.
### Why?
The code snippet in the Route handler `formData` documentation
```ts
import { NextResponse } from 'next/server'
export async function POST(request: Request) {
const formData = await request.formData()
return NextResponse.json({ formData })
}
```
is slightly wrong, because `formData` is not a plain object and hence `return NextResponse.json({ formData })` doesn't actually work.
Since we are already in the topic of parsing `formData`, I also added a mention on `zod-form-data` which can be used to validate the form and parse it to non-string formats such as `number`.
This link is failing CI as seen here:
https://github.com/vercel/next.js/actions/runs/5623454975/job/15238167610
```
Error: The action could not create a Github comment because it is initiated from a forked repo. View the action logs for a list of broken links.
This PR introduces broken links to the docs:
┌─────────┬───────────────────────────────────────────────────────────────────────────────┬──────┬─────────────────────────────────────────────────────────────────────────────────────┐
│ (index) │ link │ type │ docPath │
├─────────┼───────────────────────────────────────────────────────────────────────────────┼──────┼─────────────────────────────────────────────────────────────────────────────────────┤
│ 0 │ 'app/building-your-application/configuring/typescript#statically-typed-links' │ │ 'docs/02-app/01-building-your-application/01-routing/03-linking-and-navigating.mdx' │
└─────────┴───────────────────────────────────────────────────────────────────────────────┴──────┴─────────────────────────────────────────────────────────────────────────────────────┘
Error: This PR introduces broken links to the docs. The action could not create a Github check because it is initiated from a forked repo.
Error: Process completed with exit code 1.
```
> Add a sentence to the instructions for using typescript in an existing project instructing the user to copy the `paths` compiler option from the existing jsconfig file to the new tsconfig file.
> Not doing so causes absolute imports from project directories to break, and gives "Module Not Found" messages that the docs do not have a case for solving"
### What and why?
The word "publicly" should be spelled consistently across the documentation. It is spelled currently as "publically" in a few places.
### How?
Fixed the spelling!
The correct filename is seen on PagesOnly. But on AppOnly, the filename is not correct. It should be "hello" instead of "ClientComponent".
line to change:
from:
import('../components/ClientComponent').then((mod) => mod.Hello)
to:
import('../components/hello').then((mod) => mod.Hello)
line to change:
from:
import('../components/ClientComponent').then((mod) => mod.Hello)
to:
import('../components/hello').then((mod) => mod.Hello)
Added clarification that runtime edge can be defined on Layout level too.
Co-authored-by: Steven <229881+styfle@users.noreply.github.com>
Co-authored-by: Balázs Orbán <18369201+balazsorban44@users.noreply.github.com>
The following files have been modified.
- `docs/02-app/01-building-your-application/05-optimizing/04-metadata.mdx`
programatically -> programmatically
- `docs/02-app/02-api-reference/04-functions/image-response.mdx`
ImageReponse -> ImageResponse
Co-authored-by: JJ Kasper <22380829+ijjk@users.noreply.github.com>
### Description
This PR fix typo in the description of Caching Data
### Changes
- Added types to React `cache()` exercise
File: `docs/02-app/01-building-your-application/03-data-fetching/02-caching.mdx`
Route handlers are not specifically different from API Routes in terms of forms or other usage, the only difference is how you write them (Request) => Response. Initially this mention was supposed to be removed when server actions are marked stable, but it's leading to some confusion so I've updated the mention to clarify that there will be a more integrated solution for React.
- Remove specific TypeScript sections and add JS/TS code block toggles
- Consolidate "Good to know" information into sections
- Add links back to incrementally adopting the App Router when trying to
use escape hatches
- Add better TS example for `getInitialProps` (even tho it's not
recommended, still helpful)
Adds missing `Metadata` type to a few declarations.
---------
Co-authored-by: Steven <steven@ceriously.com>
Co-authored-by: Delba de Oliveira <32464864+delbaoliveira@users.noreply.github.com>
Co-authored-by: Tim Neutkens <tim@timneutkens.nl>
#52486
Here I fixed the typo error of fetchUsers to fetchUser in
docs/api-reference/04-functions/not-found.mdx
async function fetchUser(id) { // Here instead of fetchUsers i changed
it to fetchUser
const res = await fetch('https://...')
if (!res.ok) return undefined
return res.json()
}
export default async function Profile({ params }) {
const user = await fetchUser(params.id)
if (!user) {
notFound()
}
// ...
}
https://nextjs.org/docs/app/api-reference/functions/not-found
The `incrementalCacheHandlerPath` have to be under `experimental`.
And the path should use `path` library so that the custom cache handler can be used.
Hey Next.js Team, 👋🏻
I noticed Next.js apps scaffolded with create-next-app weren't prompting me for the TypeScript workspace version in VS Code. After digging through the repo, I stumbled on this https://github.com/vercel/next.js/pull/49133 PR from Tim. While this PR explains why it was removed, I'm not sure the docs were ever updated to reflect this change.
This PR aims to address that with a simple note in the TypeScript Plugin section of the TypeScript docs page.
Co-authored-by: Delba de Oliveira <32464864+delbaoliveira@users.noreply.github.com>
Co-authored-by: Tim Neutkens <6324199+timneutkens@users.noreply.github.com>
Co-authored-by: Lee Robinson <9113740+leerob@users.noreply.github.com>
This PR adds more info about `error.message`, `error.digest`, and
omission of sensitive error details from Server Components.
---------
Co-authored-by: Tim Neutkens <tim@timneutkens.nl>
Co-authored-by: Lee Robinson <me@leerob.io>
### Overview
The purpose of this PR is to remove the wrong link to useParams in the useSearchParams documentation.
Co-authored-by: Steven <229881+styfle@users.noreply.github.com>
There's a small typo: `[pagesExtension]` -> `[pageExtensions]`.
Got confused why my instrumentation hook was not called. When I searched my source code for `pagesExtension` there was no occurrence so I thought I did not use it; soon after I realized the field in the docs has a typo .
- Add app router example to 03-environment-variables.mdx
Co-authored-by: Delba de Oliveira <32464864+delbaoliveira@users.noreply.github.com>
Co-authored-by: Steven <229881+styfle@users.noreply.github.com>
I read the PR checklist, but this is such a small PR that I feel it's
self-explanatory.
I believe the wrong function name (`generateMetadata`) is used on this
page, and it was meant to be `generateImageMetadata`.
If not... apologies 😅
This PR documents the `NODE_ENV` environment variable behavior.
This feature was originally added in
152c2c2af3 which was released in `next@5`.
See the current source code here:
e3e76a45ee/packages/next/src/bin/next.ts (L82)
---------