Unverified Commit 53011ed8 authored by Rich Haines's avatar Rich Haines Committed by GitHub

Update docs 1 (#71812)

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

-->
parent 5ab28cd6
---
title: Directives
description: Directives are used to modify the behavior of your Next.js application.
---
The following directives are available:
\ No newline at end of file
This diff is collapsed.
---
title: use client
description: Learn how to use the use client directive to render a component on the client.
related:
description: React documentation for use client.
links:
- https://react.dev/reference/rsc/use-client
---
The `use client` directive designates a component to be rendered on the **client side** and should be used when creating interactive user interfaces (UI) that require client-side JavaScript capabilities, such as state management, event handling, and access to browser APIs. This is a React feature.
## Usage
To designate a component as a Client Component, add the `use client` directive **at the top of the file**, before any imports:
````tsx filename="app/components/counter.tsx" highlight={1} switcher
'use client'
import { useState } from 'react'
export default function Counter() {
const [count, setCount] = useState(0)
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
)
}
````
````jsx filename="app/components/counter.js" highlight={1} switcher
'use client'
import { useState } from 'react'
export default function Counter() {
const [count, setCount] = useState(0)
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
)
}
````
## Nesting Client Components within Server Components
Combining Server and Client Components allows you to build applications that are both performant and interactive:
1. **Server Components**: Use for static content, data fetching, and SEO-friendly elements.
2. **Client Components**: Use for interactive elements that require state, effects, or browser APIs.
3. **Component composition**: Nest Client Components within Server Components as needed for a clear separation of server and client logic.
In the following example:
- `Header` is a Server Component handling static content.
- `Counter` is a Client Component enabling interactivity within the page.
```tsx filename="app/page.tsx" highlight={2,8} switcher
import Header from './header'
import Counter from './counter' // This is a Client Component
export default function Page() {
return (
<div>
<Header />
<Counter />
</div>
)
}
```
```jsx filename="app/page.js" highlight={2,8} switcher
import Header from './header'
import Counter from './counter' // This is a Client Component
export default function Page() {
return (
<div>
<Header />
<Counter />
</div>
)
}
```
## Reference
See the [React documentation](https://react.dev/reference/rsc/use-client) for more information on `use client`.
---
title: use server
description: Learn how to use the use server directive to execute code on the server.
related:
description: React documentation for use server.
links:
- https://react.dev/reference/rsc/use-server
---
The `use server` directive designates a function or file to be executed on the **server side**. It can be used at the top of a file to indicate that all functions in the file are server-side, or inline at the top of a function to mark the function as a [Server Function](https://19.react.dev/reference/rsc/server-functions). This is a React feature.
## Using `use server` at the top of a file
The following example shows a file with a `use server` directive at the top. All functions in the file are executed on the server.
```tsx filename="app/actions.ts" highlight={1} switcher
'use server'
import { db } from '@/lib/db' // Your database client
export async function createUser(data: { name: string; email: string }) {
const user = await db.user.create({ data })
return user
}
```
```jsx filename="app/actions.js" highlight={1} switcher
'use server'
import { db } from '@/lib/db' // Your database client
export async function createUser(data) {
const user = await db.user.create({ data })
return user
}
```
### Using Server Functions in a Client Component
To use Server Functions in Client Components you need to create your Server Functions in a dedicated file using the `use server` directive at the top of the file. These Server Functions can then be imported into Client and Server Components and executed.
Assuming you have a `fetchUsers` Server Function in `actions.ts`:
```tsx filename="app/actions.ts" highlight={1} switcher
'use server'
import { db } from '@/lib/db' // Your database client
export async function fetchUsers() {
const users = await db.user.findMany()
return users
}
```
```jsx filename="app/actions.js" highlight={1} switcher
'use server'
import { db } from '@/lib/db' // Your database client
export async function fetchUsers() {
const users = await db.user.findMany()
return users
}
```
Then you can import the `fetchUsers` Server Function into a Client Component and execute it on the client-side.
```tsx filename="app/components/my-button.tsx" highlight={1,2,8} switcher
'use client'
import { fetchUsers } from '../actions'
export default function MyButton() {
return <button onClick={() => fetchUsers()}>Fetch Users</button>
}
```
```jsx filename="app/components/my-button.js" highlight={1,2,8} switcher
'use client'
import { fetchUsers } from '../actions'
export default function MyButton() {
return <button onClick={() => fetchUsers()}>Fetch Users</button>
}
```
## Using `use server` inline
In the following example, `use server` is used inline at the top of a function to mark it as a [Server Function](https://19.react.dev/reference/rsc/server-functions):
```tsx filename="app/page.tsx" highlight={5} switcher
import { db } from '@/lib/db' // Your database client
export default function UserList() {
async function fetchUsers() {
'use server'
const users = await db.user.findMany()
return users
}
return <button onClick={() => fetchUsers()}>Fetch Users</button>
}
```
```jsx filename="app/page.js" highlight={5} switcher
import { db } from '@/lib/db' // Your database client
export default function UserList() {
async function fetchUsers() {
'use server'
const users = await db.user.findMany()
return users
}
return <button onClick={() => fetchUsers()}>Fetch Users</button>
}
```
## Security considerations
When using the `use server` directive, it's important to ensure that all server-side logic is secure and that sensitive data remains protected.
### Authentication and authorization
Always authenticate and authorize users before performing sensitive server-side operations.
```tsx filename="app/actions.ts" highlight={1,7,8,9,10} switcher
'use server'
import { db } from '@/lib/db' // Your database client
import { authenticate } from '@/lib/auth' // Your authentication library
export async function createUser(data: { name: string; email: string }, token: string) {
const user = authenticate(token)
if (!user) {
throw new Error('Unauthorized')
}
const newUser = await db.user.create({ data })
return newUser
}
```
```jsx filename="app/actions.js" highlight={1,7,8,9,10} switcher
'use server'
import { db } from '@/lib/db' // Your database client
import { authenticate } from '@/lib/auth' // Your authentication library
export async function createUser(data, token) {
const user = authenticate(token)
if (!user) {
throw new Error('Unauthorized')
}
const newUser = await db.user.create({ data })
return newUser
}
```
## Reference
See the [React documentation](https://react.dev/reference/rsc/use-server) for more information on `use server`.
......@@ -3,6 +3,8 @@ title: Route Segment Config
description: Learn about how to configure options for Next.js route segments.
---
> The options outlined on this page are disabled if the [`dynamicIO`](/docs/app/api-reference/next-config-js/dynamicIO) flag is on, and will eventually be deprecated in the future.
The Route Segment options allows you to configure the behavior of a [Page](/docs/app/building-your-application/routing/layouts-and-templates), [Layout](/docs/app/building-your-application/routing/layouts-and-templates), or [Route Handler](/docs/app/building-your-application/routing/route-handlers) by directly exporting the following variables:
| Option | Type | Default |
......
---
title: cacheTag
description: Learn how to use the cacheTag function to manage cache invalidation in your Next.js application.
version: experimental
related:
title: Related
description: View related API references.
links:
- app/api-reference/next-config-js/dynamicIO
- app/api-reference/directives/use-cache
- app/api-reference/functions/revalidateTag
---
The `cacheTag` function allows you to tag cached data for on-demand invalidation. By associating tags with cache entries, you can selectively purge or revalidate specific parts of your cache without affecting other cached data.
## Usage
To use `cacheTag`, enable the [`dynamicIO` flag](/docs/app/api-reference/next-config-js/dynamicIO) in your `next.config.js` and import `cacheTag` from `next/cache`:
```ts filename="next.config.ts"
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
experimental: {
dynamicIO: true,
}
};
export default nextConfig;
```
```tsx filename="app/actions.ts"
import { unstable_cacheTag as cacheTag } from 'next/cache'
export async function getData() {
"use cache"
cacheTag('my-data')
const data = await fetch('/api/data')
return data
}
```
## Combining with `revalidateTag`
Use `cacheTag` in conjunction with `revalidateTag` to purge tagged cache entries on-demand. This is useful for scenarios like updating data after a mutation or an external event.
```tsx filename="app/submit.ts"
'use server'
import { revalidateTag } from 'next/cache'
export default async function submit() {
await addPost()
revalidateTag('my-data')
}
```
## Examples
### Tagging cached data
Tag your cached data by calling `cacheTag` within a cached function or component:
```tsx filename="app/components/bookings.tsx"
import { unstable_cacheTag as cacheTag, unstable_cacheLife as cacheLife } from 'next/cache'
interface BookingsProps {
type: string
}
export async function Bookings({type = 'massage'}: BookingsProps) {
"use cache"
cacheLife('minutes')
cacheTag('bookings-data')
async function getBookingsData() {
const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`)
return data
}
return //...
}
```
### Tagging using data
You can use the data returned from an async function to tag the cache entry.
```tsx filename="app/components/bookings.tsx"
import { unstable_cacheTag as cacheTag, unstable_cacheLife as cacheLife } from 'next/cache'
interface BookingsProps {
type: string
}
export async function Bookings({type = 'massage'}: BookingsProps) {
async function getBookingsData() {
"use cache"
cacheLife('minutes')
const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`)
cacheTag('bookings-data', data.id)
return data
}
return //...
}
```
### Invalidating tagged cache
Invalidate the cache for a specific tag when needed:
```tsx filename="app/actions.ts"
'use server'
import { revalidateTag } from 'next/cache'
export async function updateBookings() {
await updateBookingData()
revalidateTag('bookings-data')
}
```
## Notes
- **Idempotent Tags**: Applying the same tag multiple times has no additional effect.
- **Multiple Tags**: You can assign multiple tags to a single cache entry by passing an array to `cacheTag`.
```tsx
cacheTag(['tag-one', 'tag-two'])
```
---
title: cacheLife
description: Learn how to set up cacheLife configurations in Next.js.
version: experimental
---
The `cacheLife` option allows you to define custom configurations when using the `cacheLife` function with the [`use cache` directive](/docs/app/api-reference/directives/use-cache) at the level of components, functions or files, for more granular control over caching.
## Usage
To use `cacheLife`, enable the [`dynamicIO` flag](/docs/app/api-reference/next-config-js/dynamicIO) and define the configuration in your `next.config.js` file as follows:
```js filename="next.config.js"
module.exports = {
experimental: {
dynamicIO: true,
cacheLife: {
blog: {
stale: 3600, // 1 hour
revalidate: 900, // 15 minutes
expire: 86400 // 1 day
},
},
}
}
```
You can now use this custom `blog` configuration in your component, function or file as follows:
```tsx filename="app/actions.ts" highlight={4,5}
import { unstable_cacheLife as cacheLife} from 'next/cache'
export async function getCachedData() {
"use cache"
cacheLife('blog')
const data = await fetch('/api/data')
return data
}
```
## Configuration structure
The configuration object has key values with the following format:
| **Property** | **Value** | **Description** | **Requirement** |
| --- | --- | --- | --- |
| `stale` | `number` | Duration the client should cache a value without checking the server. | Optional |
| `revalidate` | `number` | Frequency at which the cache should refresh on the server; stale values may be served while revalidating. | Optional |
| `expire` | `number` | Maximum duration for which a value can remain stale before switching to dynamic fetching; must be longer than `revalidate`. | Optional - Must be longer than `revalidate` |
\ No newline at end of file
---
title: dynamicIO
description: Learn how to enable the dynamicIO flag in Next.js.
version: experimental
---
The `dynamicIO` flag is an experimental feature in Next.js that causes data fetching operations in the App Router to be excluded from pre-renders unless they are explicitly cached. This can be useful for optimizing the performance of dynamic data fetching in server components.
It is useful if your application requires fresh data fetching during runtime rather than serving from a pre-rendered cache.
It is expected to be used in conjunction with [`use cache`](/docs/app/api-reference/directives/use-cache) so that your data fetching happens at runtime by default unless you define specific parts of your application to be cached with `use cache` at the page, function, or component level.
## Usage
To enable the `dynamicIO` flag, set it to `true` in the `experimental` section of your `next.config.ts` file:
```ts filename="next.config.ts"
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
experimental: {
dynamicIO: true,
}
};
export default nextConfig;
```
When `dynamicIO` is enabled, you can use the following cache functions and configurations:
- The [`use cache` directive](/docs/app/api-reference/directives/use-cache)
- The [`cacheLife` function](/docs/app/api-reference/next-config-js/cacheLife) with `use cache`
- The [`cacheTag` function](/docs/app/api-reference/functions/cacheTag)
## Notes
- While `dynamicIO` can optimize performance by ensuring fresh data fetching during runtime, it may also introduce additional latency compared to serving pre-rendered content.
\ No newline at end of file
---
title: Legacy APIs
description: API Reference for Next.js Legacy APIs.
---
The following APIs are considered legacy and will be removed in a future version of Next.js:
......@@ -4,6 +4,8 @@ description: API Reference for the unstable_cache function.
version: unstable
---
> This API will be deprecated in future versions. In version 15 we recommend using the [`use cache`](app/api-reference/directives/use-cache) directive instead.
`unstable_cache` allows you to cache the results of expensive operations, like database queries, and reuse them across multiple requests.
```jsx
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment