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.