instruction
stringlengths 31
302
| output
stringlengths 22
4.36k
| source_url
stringlengths 41
99
|
---|---|---|
How do I implement Rewrites with basePath support in Next.js? | When leveraging basePath support with rewrites each source and destination is automatically prefixed with the basePath unless you add basePath: false to the rewrite:
```javascript
module.exports = {
basePath: '/docs',
async rewrites() {
return [
{
source: '/with-basePath', // automatically becomes /docs/with-basePath
destination: '/another', // automatically becomes /docs/another
},
{
// does not add /docs to /without-basePath since basePath: false is set
// Note: this can not be used for internal rewrites e.g. `destination: '/another'`
source: '/without-basePath',
destination: 'https://example.com',
basePath: false,
},
]
},
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/config/next-config-js/rewrites |
How do I implement Rewrites with i18n support in Next.js? | When leveraging i18n support with rewrites each source and destination is automatically prefixed to handle the configured locales unless you add locale: false to the rewrite. If locale: false is used you must prefix the source and destination with a locale for it to be matched correctly.
```javascript
module.exports = {
i18n: {
locales: ['en', 'fr', 'de'],
defaultLocale: 'en',
},
async rewrites() {
return [
{
source: '/with-locale', // automatically handles all locales
destination: '/another', // automatically passes the locale on
},
{
// does not handle locales automatically since locale: false is set
source: '/nl/with-locale-manual',
destination: '/nl/another',
locale: false,
},
{
// this matches '/' since `en` is the defaultLocale
source: '/en',
destination: '/en/another',
locale: false,
},
{
// it's possible to match all locales even when locale: false is set
source: '/:locale/api-alias/:path*',
destination: '/api/:path*',
locale: false,
},
{
// this gets converted to /(en|fr|de)/(.*) so will not match the top-level
// `/` or `/fr` routes like /:path* would
source: '/(.*)',
destination: '/another',
},
]
},
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/config/next-config-js/rewrites |
How do I implement in Next.js? | sassOptions allow you to configure the Sass compiler.
Was this helpful?
```typescript
/** @type {import('next').NextConfig} */
const sassOptions = {
additionalData: `
$var: red;
`,
}
const nextConfig = {
sassOptions: {
...sassOptions,
implementation: 'sass-embedded',
},
}
module.exports = nextConfig
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/config/next-config-js/sassOptions |
How do I implement bodySizeLimit in Next.js? | By default, the maximum size of the request body sent to a Server Action is 1MB, to prevent the consumption of excessive server resources in parsing large amounts of data, as well as potential DDoS attacks.
However, you can configure this limit using the serverActions.bodySizeLimit option. It can take the number of bytes or any string format supported by bytes, for example 1000, '500kb' or '3mb'.
```javascript
/** @type {import('next').NextConfig} */
module.exports = {
experimental: {
serverActions: {
bodySizeLimit: '2mb',
},
},
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/config/next-config-js/serverActions |
How do I implement in Next.js? | The experimental serverComponentsHmrCache option allows you to cache fetch responses in Server Components across Hot Module Replacement (HMR) refreshes in local development. This results in faster responses and reduced costs for billed API calls.
Good to know: For better observability, we recommend using the logging.fetches option which logs fetch cache hits and misses in the console during development.
Was this helpful?
```typescript
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
serverComponentsHmrCache: false, // defaults to true
},
}
module.exports = nextConfig
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/config/next-config-js/serverComponentsHmrCache |
How do I implement in Next.js? | If a dependency is using Node.js specific features, you can choose to opt-out specific dependencies from the Server Components bundling and use native Node.js require.
Was this helpful?
```javascript
/** @type {import('next').NextConfig} */
const nextConfig = {
serverExternalPackages: ['@acme/ui'],
}
module.exports = nextConfig
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/config/next-config-js/serverExternalPackages |
How do I implement in Next.js? | staleTimes is an experimental feature that enables caching of page segments in the client-side router cache.
You can enable this experimental feature and provide custom revalidation times by setting the experimental staleTimes flag:
The static and dynamic properties correspond with the time period (in seconds) based on different types of link prefetching.
The dynamic property is used when the page is neither statically generated nor fully prefetched (e.g. with prefetch={true}).
Default: 0 seconds (not cached)
The static property is used for statically generated pages, or when the prefetch prop on Link is set to true, or when calling router.prefetch.
Default: 0 seconds (not cached)
Good to know:
You can learn more about the Client Router Cache here.
```javascript
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
staleTimes: {
dynamic: 30,
static: 180,
},
},
}
module.exports = nextConfig
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/config/next-config-js/staleTimes |
How do I implement * in Next.js? | The staticGeneration* options allow you to configure the Static Generation process for advanced use cases.
```typescript
const nextConfig = {
experimental: {
staticGenerationRetryCount: 1,
staticGenerationMaxConcurrency: 8,
staticGenerationMinPagesPerWorker: 25,
},
}
export default nextConfig
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/config/next-config-js/staticGeneration |
How do I implement in Next.js? | With this option set, URLs like /about will redirect to /about/.
Static file URLs, such as files with extensions.
Any paths under .well-known/.
For example, the following URLs will remain unchanged: /file.txt, images/photos/picture.png, and .well-known/subfolder/config.json.
When used with output: "export" configuration, the /about page will output /about/index.html (instead of the default /about.html).
```javascript
module.exports = {
trailingSlash: true,
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/config/next-config-js/trailingSlash |
How do I implement in Next.js? | The turbo option lets you customize Turbopack to transform different files and change how modules are resolved.
Good to know:
```typescript
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
turbo: {
// ...
},
},
}
module.exports = nextConfig
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/config/next-config-js/turbo |
How do I implement Configuring webpack loaders in Next.js? | If you need loader support beyond what's built in, many webpack loaders already work with Turbopack. There are currently some limitations:
Only a core subset of the webpack loader API is implemented. Currently, there is enough coverage for some popular loaders, and we'll expand our API support in the future.
Only loaders that return JavaScript code are supported. Loaders that transform files like stylesheets or images are not currently supported.
Options passed to webpack loaders must be plain JavaScript primitives, objects, and arrays. For example, it's not possible to pass require() plugin modules as option values.
```javascript
module.exports = {
experimental: {
turbo: {
rules: {
'*.svg': {
loaders: ['@svgr/webpack'],
as: '*.js',
},
},
},
},
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/config/next-config-js/turbo |
How do I implement Resolving aliases in Next.js? | This aliases imports of the underscore package to the lodash package. In other words, import underscore from 'underscore' will load the lodash module instead of underscore.
Turbopack also supports conditional aliasing through this field, similar to Node.js' conditional exports. At the moment only the browser condition is supported. In the case above, imports of the mocha module will be aliased to mocha/browser-entry.js when Turbopack targets browser environments.
```javascript
module.exports = {
experimental: {
turbo: {
resolveAlias: {
underscore: 'lodash',
mocha: { browser: 'mocha/browser-entry.js' },
},
},
},
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/config/next-config-js/turbo |
How do I implement Resolving custom extensions in Next.js? | Turbopack can be configured to resolve modules with custom extensions, similar to webpack's resolve.extensions configuration.
This overwrites the original resolve extensions with the provided list. Make sure to include the default extensions.
For more information and guidance for how to migrate your app to Turbopack from webpack, see Turbopack's documentation on webpack compatibility.
```javascript
module.exports = {
experimental: {
turbo: {
resolveExtensions: [
'.mdx',
'.tsx',
'.ts',
'.jsx',
'.js',
'.mjs',
'.json',
],
},
},
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/config/next-config-js/turbo |
How do I implement Assigning module IDs in Next.js? | Turbopack currently supports two strategies for assigning module IDs:
'named' assigns readable module IDs based on the module's path and functionality.
'deterministic' assigns small hashed numeric module IDs, which are mostly consistent between builds and therefore help with long-term caching.
If not set, Turbopack will use 'named' for development builds and 'deterministic' for production builds.
```javascript
module.exports = {
experimental: {
turbo: {
moduleIdStrategy: 'deterministic',
},
},
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/config/next-config-js/turbo |
How do I implement in Next.js? | Experimental support for statically typed links. This feature requires using the App Router as well as TypeScript in your project.
Was this helpful?
```javascript
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
typedRoutes: true,
},
}
module.exports = nextConfig
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/config/next-config-js/typedRoutes |
How do I implement in Next.js? | URL imports are an experimental feature that allows you to import modules directly from external servers (instead of from the local disk).
Then, you can import modules directly from URLs:
URL Imports can be used everywhere normal package imports can be used.
```javascript
module.exports = {
experimental: {
urlImports: ['https://example.com/assets/', 'https://cdn.skypack.dev'],
},
}
```
```javascript
import { a, b, c } from 'https://example.com/assets/some/module.js'
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/config/next-config-js/urlImports |
How do I implement Usage in Next.js? | When useCache is enabled, you can use the following cache functions and configurations:
The use cache directive
The cacheLife function with use cache
The cacheTag function
Was this helpful?
```jsx
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
useCache: true,
},
}
export default nextConfig
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/config/next-config-js/useCache |
How do I implement in Next.js? | Experimental support for using Lightning CSS, a fast CSS bundler and minifier, written in Rust.
Was this helpful?
```typescript
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
useLightningcss: true,
},
}
module.exports = nextConfig
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/config/next-config-js/useLightningcss |
How do I implement V in Next.js? | viewTransition is an experimental flag that enables the new experimental View Transitions API in React. This API allows you to leverage the native View Transitions browser API to create seamless transitions between UI states.
```javascript
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
viewTransition: true,
},
}
module.exports = nextConfig
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/config/next-config-js/viewTransition |
How do I implement Usage in Next.js? | Once enabled, you can import the ViewTransition component from React in your application:
However, documentation and examples are currently limited, and you will need to refer directly to React’s source code and discussions to understand how this works.
```javascript
import { unstable_ViewTransition as ViewTransition } from 'react'
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/config/next-config-js/viewTransition |
How do I implement C W C in Next.js? | Good to know: changes to webpack config are not covered by semver so proceed at your own risk
Some commonly asked for features are available as plugins:
The webpack function is executed three times, twice for the server (nodejs / edge runtime) and once for the client. This allows you to distinguish between client and server configuration using the isServer property.
The second argument to the webpack function is an object with the following properties:
babel: Object - Default babel-loader configuration.
Example usage of defaultLoaders.babel:
```javascript
module.exports = {
webpack: (
config,
{ buildId, dev, isServer, defaultLoaders, nextRuntime, webpack }
) => {
// Important: return the modified config
return config
},
}
```
```css
// Example config for adding a loader that depends on babel-loader
// This source was taken from the @next/mdx plugin source:
// https://github.com/vercel/next.js/tree/canary/packages/next-mdx
module.exports = {
webpack: (config, options) => {
config.module.rules.push({
test: /\.mdx/,
use: [
options.defaultLoaders.babel,
{
loader: '@mdx-js/loader',
options: pluginOptions.options,
},
],
})
return config
},
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/config/next-config-js/webpack |
How do I implement Statically Typed Links in Next.js? | To opt-into this feature, experimental.typedRoutes need to be enabled and the project needs to be using TypeScript.
Currently, experimental support includes any string literal, including dynamic segments. For non-literal strings, you currently need to manually cast the href with as Route:
How does it work?
```jsx
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
typedRoutes: true,
},
}
export default nextConfig
```
```jsx
import type { Route } from 'next'
import Link from 'next/link'
function Card<T extends string>({ href }: { href: Route<T> | URL }) {
return (
<Link href={href}>
<div>My Card</div>
</Link>
)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/config/typescript |
How do I implement Usage in Next.js? | Additionally, use cache directives are also enabled when the dynamicIO flag is set.
Then, you can use the use cache directive at the file, component, or function level:
```typescript
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
useCache: true,
},
}
module.exports = nextConfig
```
```javascript
// File level
'use cache'
export default async function Page() {
// ...
}
// Component level
export async function MyComponent() {
'use cache'
return <></>
}
// Function level
export async function getData() {
'use cache'
const data = await fetch('/api/data')
return data
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/directives/use-cache |
How do I implement Caching entire routes with use cache in Next.js? | To prerender an entire route, add use cache to the top of both the layout and page files. Each of these segments are treated as separate entry points in your application, and will be cached independently.
Any components imported and nested in page file will inherit the cache behavior of page.
```jsx
'use cache'
export default function Layout({ children }) {
return <div>{children}</div>
}
```
```javascript
'use cache'
async function Users() {
const users = await fetch('/api/users')
// loop through users
}
export default function Page() {
return (
<main>
<Users />
</main>
)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/directives/use-cache |
How do I implement Caching component output with use cache in Next.js? | You can use use cache at the component level to cache any fetches or computations performed within that component. When you reuse the component throughout your application it can share the same cache entry as long as the props maintain the same structure.
The props are serialized and form part of the cache key, and the cache entry will be reused as long as the serialized props produce the same value in each instance.
```javascript
export async function Bookings({ type = 'haircut' }) {
'use cache'
async function getBookingsData() {
const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`)
return data
}
return //...
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/directives/use-cache |
How do I implement Caching function output with use cache in Next.js? | Since you can add use cache to any asynchronous function, you aren't limited to caching components or routes only. You might want to cache a network request or database query or compute something that is very slow. By adding use cache to a function containing this type of work it becomes cacheable, and when reused, will share the same cache entry.
```javascript
export async function getData() {
'use cache'
const data = await fetch('/api/data')
return data
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/directives/use-cache |
How do I implement Interleaving in Next.js? | If you need to pass non-serializable arguments to a cacheable function, you can pass them as children. This means the children reference can change without affecting the cache entry.
You can also pass Server Actions through cached components to Client Components without invoking them inside the cacheable function.
```jsx
export default async function Page() {
const uncachedData = await getData()
return (
<CacheComponent>
<DynamicComponent data={uncachedData} />
</CacheComponent>
)
}
async function CacheComponent({ children }) {
'use cache'
const cachedData = await fetch('/api/cached-data')
return (
<div>
<PrerenderedComponent data={cachedData} />
{children}
</div>
)
}
```
```jsx
import ClientComponent from './ClientComponent'
export default async function Page() {
const performUpdate = async () => {
'use server'
// Perform some server-side update
await db.update(...)
}
return <CacheComponent performUpdate={performUpdate} />
}
async function CachedComponent({ performUpdate }) {
'use cache'
// Do not call performUpdate here
return <ClientComponent action={performUpdate} />
}
```
```jsx
'use client'
export default function ClientComponent({ action }) {
return <button onClick={action}>Update</button>
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/directives/use-cache |
How do I implement Usage in Next.js? | To designate a component as a Client Component, add the use client directive at the top of the file, before any imports:
```jsx
'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>
)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/directives/use-client |
How do I implement Nesting Client Components within Server Components in Next.js? | Combining Server and Client Components allows you to build applications that are both performant and interactive:
Server Components: Use for static content, data fetching, and SEO-friendly elements.
Client Components: Use for interactive elements that require state, effects, or browser APIs.
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.
```html
import Header from './header'
import Counter from './counter' // This is a Client Component
export default function Page() {
return (
<div>
<Header />
<Counter />
</div>
)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/directives/use-client |
How do I implement Using use server at the top of a file in Next.js? | The following example shows a file with a use server directive at the top. All functions in the file are executed on the server.
```jsx
'use server'
import { db } from '@/lib/db' // Your database client
export async function createUser(data) {
const user = await db.user.create({ data })
return user
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/directives/use-server |
How do I implement Using Server Functions in a Client Component in Next.js? | 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:
Then you can import the fetchUsers Server Function into a Client Component and execute it on the client-side.
```jsx
'use server'
import { db } from '@/lib/db' // Your database client
export async function fetchUsers() {
const users = await db.user.findMany()
return users
}
```
```jsx
'use client'
import { fetchUsers } from '../actions'
export default function MyButton() {
return <button onClick={() => fetchUsers()}>Fetch Users</button>
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/directives/use-server |
How do I implement Using use server inline in Next.js? | In the following example, use server is used inline at the top of a function to mark it as a Server Function:
```jsx
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>
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/directives/use-server |
How do I implement params (optional) in Next.js? | A promise that resolves to an object containing the dynamic route parameters from the root segment down to the slot's subpages. For example:
```jsx
export default async function Default({ params }) {
const { artist } = await params
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/default |
How do I implement .js in Next.js? | A root layout is the top-most layout in the root app directory. It is used to define the <html> and <body> tags and other globally shared UI.
```jsx
export default function DashboardLayout({ children }) {
return <section>{children}</section>
}
```
```jsx
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/layout |
How do I implement params (optional) in Next.js? | A promise that resolves to an object containing the dynamic route parameters object from the root segment down to that layout.
```jsx
export default async function Layout({ params }) {
const { team } = await params
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/layout |
How do I implement Root Layouts in Next.js? | The app directory must include a root app/layout.js.
You should not manually add <head> tags such as <title> and <meta> to root layouts. Instead, you should use the Metadata API which automatically handles advanced requirements such as streaming and de-duplicating <head> elements.
```jsx
export default function RootLayout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/layout |
How do I implement Layouts cannot access pathname in Next.js? | Common pathname patterns can also be implemented with params prop.
See the examples section for more information.
```jsx
import { ClientComponent } from '@/app/ui/ClientComponent'
export default function Layout({ children }) {
return (
<>
<ClientComponent />
{/* Other Layout UI */}
<main>{children}</main>
</>
)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/layout |
How do I implement Displaying content based on params in Next.js? | Using dynamic route segments, you can display or fetch specific content based on the params prop.
```jsx
export default async function DashboardLayout({ children, params }) {
const { team } = await params
return (
<section>
<header>
<h1>Welcome to {team}'s Dashboard</h1>
</header>
<main>{children}</main>
</section>
)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/layout |
How do I implement Reading params in Client Components in Next.js? | To use params in a Client Component (which cannot be async), you can use React's use function to read the promise:
```jsx
'use client'
import { use } from 'react'
export default function Page({ params }) {
const { slug } = use(params)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/layout |
How do I implement .js in Next.js? | A loading file can create instant loading states built on Suspense.
By default, this file is a Server Component - but can also be used as a Client Component through the "use client" directive.
Loading UI components do not accept any parameters.
Good to know:
While designing loading UI, you may find it helpful to use the React Developer Tools to manually toggle Suspense boundaries.
```jsx
export default function Loading() {
// Or a custom loading skeleton component
return <p>Loading...</p>
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/loading |
How do I implement mdx-.js in Next.js? | Use the file mdx-components.tsx (or .js) in the root of your project to define MDX Components. For example, at the same level as pages or app, or inside src if applicable.
```jsx
export function useMDXComponents(components) {
return {
...components,
}
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/mdx-components |
How do I implement useMDXComponents function in Next.js? | The file must export a single function, either as a default export or named useMDXComponents.
```jsx
export function useMDXComponents(components) {
return {
...components,
}
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/mdx-components |
How do I implement Generate a Manifest file in Next.js? | Add a manifest.js or manifest.ts file that returns a Manifest object.
Good to know: manifest.js is special Route Handlers that is cached by default unless it uses a Dynamic API or dynamic config option.
```typescript
export default function manifest() {
return {
name: 'Next.js App',
short_name: 'Next.js App',
description: 'Next.js App',
start_url: '/',
display: 'standalone',
background_color: '#fff',
theme_color: '#fff',
icons: [
{
src: '/favicon.ico',
sizes: 'any',
type: 'image/x-icon',
},
],
}
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/manifest |
How do I implement opengraph-image.alt.txt in Next.js? | Add an accompanying opengraph-image.alt.txt file in the same route segment as the opengraph-image.(jpg|jpeg|png|gif) image it's alt text.
```jsx
<meta property="og:image:alt" content="About Acme" />
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/opengraph-image |
How do I implement twitter-image.alt.txt in Next.js? | Add an accompanying twitter-image.alt.txt file in the same route segment as the twitter-image.(jpg|jpeg|png|gif) image it's alt text.
```jsx
<meta property="twitter:image:alt" content="About Acme" />
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/opengraph-image |
How do I implement Generate images using code (.js, .ts, .tsx) in Next.js? | In addition to using literal image files, you can programmatically generate images using code.
Generate a route segment's shared image by creating an opengraph-image or twitter-image route that default exports a function.
Good to know:
```jsx
import { ImageResponse } from 'next/og'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
// Image metadata
export const alt = 'About Acme'
export const size = {
width: 1200,
height: 630,
}
export const contentType = 'image/png'
// Image generation
export default async function Image() {
// Font loading, process.cwd() is Next.js project directory
const interSemiBold = await readFile(
join(process.cwd(), 'assets/Inter-SemiBold.ttf')
)
return new ImageResponse(
(
// ImageResponse JSX element
<div
style={{
fontSize: 128,
background: 'white',
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
About Acme
</div>
),
// ImageResponse options
{
// For convenience, we can re-use the exported opengraph-image
// size config to also set the ImageResponse's width and height.
...size,
fonts: [
{
name: 'Inter',
data: interSemiBold,
style: 'normal',
weight: 400,
},
],
}
)
}
```
```jsx
<meta property="og:image" content="<generated>" />
<meta property="og:image:alt" content="About Acme" />
<meta property="og:image:type" content="image/png" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/opengraph-image |
How do I implement params (optional) in Next.js? | An object containing the dynamic route parameters object from the root segment down to the segment opengraph-image or twitter-image is colocated in.
```jsx
export default function Image({ params }) {
// ...
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/opengraph-image |
How do I implement Using external data in Next.js? | This example uses the params object and external data to generate the image.
Good to know:
By default, this generated image will be statically optimized. You can configure the individual fetch options or route segments options to change this behavior.
```jsx
import { ImageResponse } from 'next/og'
export const alt = 'About Acme'
export const size = {
width: 1200,
height: 630,
}
export const contentType = 'image/png'
export default async function Image({ params }) {
const post = await fetch(`https://.../posts/${params.slug}`).then((res) =>
res.json()
)
return new ImageResponse(
(
<div
style={{
fontSize: 48,
background: 'white',
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
{post.title}
</div>
),
{
...size,
}
)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/opengraph-image |
How do I implement Using Node.js runtime with local assets in Next.js? | This example uses the Node.js runtime to fetch a local image on the file system and passes it as an ArrayBuffer to the src attribute of an <img> element. The local asset should be placed relative to the root of your project, rather than the location of the example source file.
```jsx
import { ImageResponse } from 'next/og'
import { join } from 'node:path'
import { readFile } from 'node:fs/promises'
export default async function Image() {
const logoData = await readFile(join(process.cwd(), 'logo.png'))
const logoSrc = Uint8Array.from(logoData).buffer
return new ImageResponse(
(
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<img src={logoSrc} height="100" />
</div>
)
)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/opengraph-image |
How do I implement Generate a Robots file in Next.js? | Add a robots.js or robots.ts file that returns a Robots object.
Good to know: robots.js is a special Route Handlers that is cached by default unless it uses a Dynamic API or dynamic config option.
Output:
```typescript
export default function robots() {
return {
rules: {
userAgent: '*',
allow: '/',
disallow: '/private/',
},
sitemap: 'https://acme.com/sitemap.xml',
}
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/robots |
How do I implement Customizing specific user agents in Next.js? | You can customise how individual search engine bots crawl your site by passing an array of user agents to the rules property. For example:
Output:
```typescript
export default function robots() {
return {
rules: [
{
userAgent: 'Googlebot',
allow: ['/'],
disallow: ['/private/'],
},
{
userAgent: ['Applebot', 'Bingbot'],
disallow: ['/'],
},
],
sitemap: 'https://acme.com/sitemap.xml',
}
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/robots |
How do I implement Sitemap files (.xml) in Next.js? | For smaller applications, you can create a sitemap.xml file and place it in the root of your app directory.
```html
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://acme.com</loc>
<lastmod>2023-04-06T15:02:24.021Z</lastmod>
<changefreq>yearly</changefreq>
<priority>1</priority>
</url>
<url>
<loc>https://acme.com/about</loc>
<lastmod>2023-04-06T15:02:24.021Z</lastmod>
<changefreq>monthly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://acme.com/blog</loc>
<lastmod>2023-04-06T15:02:24.021Z</lastmod>
<changefreq>weekly</changefreq>
<priority>0.5</priority>
</url>
</urlset>
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/sitemap |
How do I implement Generating a sitemap using code (.js, .ts) in Next.js? | You can use the sitemap.(js|ts) file convention to programmatically generate a sitemap by exporting a default function that returns an array of URLs. If using TypeScript, a Sitemap type is available.
Good to know: sitemap.js is a special Route Handler that is cached by default unless it uses a Dynamic API or dynamic config option.
Output:
```typescript
export default function sitemap() {
return [
{
url: 'https://acme.com',
lastModified: new Date(),
changeFrequency: 'yearly',
priority: 1,
},
{
url: 'https://acme.com/about',
lastModified: new Date(),
changeFrequency: 'monthly',
priority: 0.8,
},
{
url: 'https://acme.com/blog',
lastModified: new Date(),
changeFrequency: 'weekly',
priority: 0.5,
},
]
}
```
```html
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://acme.com</loc>
<lastmod>2023-04-06T15:02:24.021Z</lastmod>
<changefreq>yearly</changefreq>
<priority>1</priority>
</url>
<url>
<loc>https://acme.com/about</loc>
<lastmod>2023-04-06T15:02:24.021Z</lastmod>
<changefreq>monthly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://acme.com/blog</loc>
<lastmod>2023-04-06T15:02:24.021Z</lastmod>
<changefreq>weekly</changefreq>
<priority>0.5</priority>
</url>
</urlset>
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/sitemap |
How do I implement Image Sitemaps in Next.js? | You can use images property to create image sitemaps. Learn more details in the Google Developer Docs.
Output:
```html
<?xml version="1.0" encoding="UTF-8"?>
<urlset
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
>
<url>
<loc>https://example.com</loc>
<image:image>
<image:loc>https://example.com/image.jpg</image:loc>
</image:image>
<lastmod>2021-01-01</lastmod>
<changefreq>weekly</changefreq>
<priority>0.5</priority>
</url>
</urlset>
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/sitemap |
How do I implement Video Sitemaps in Next.js? | You can use videos property to create video sitemaps. Learn more details in the Google Developer Docs.
Output:
```html
<?xml version="1.0" encoding="UTF-8"?>
<urlset
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"
>
<url>
<loc>https://example.com</loc>
<video:video>
<video:title>example</video:title>
<video:thumbnail_loc>https://example.com/image.jpg</video:thumbnail_loc>
<video:description>this is the description</video:description>
</video:video>
<lastmod>2021-01-01</lastmod>
<changefreq>weekly</changefreq>
<priority>0.5</priority>
</url>
</urlset>
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/sitemap |
How do I implement Generating multiple sitemaps in Next.js? | For example, to split a sitemap using generateSitemaps, return an array of objects with the sitemap id. Then, use the id to generate the unique sitemaps.
Your generated sitemaps will be available at /.../sitemap/[id]. For example, /product/sitemap/1.xml.
See the generateSitemaps API reference for more information.
```jsx
import { BASE_URL } from '@/app/lib/constants'
export async function generateSitemaps() {
// Fetch the total number of products and calculate the number of sitemaps needed
return [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }]
}
export default async function sitemap({ id }) {
// Google's limit is 50,000 URLs per sitemap
const start = id * 50000
const end = start + 50000
const products = await getProducts(
`SELECT id, date FROM products WHERE id BETWEEN ${start} AND ${end}`
)
return products.map((product) => ({
url: `${BASE_URL}/product/${product.id}`,
lastModified: product.date,
}))
}
```
## Best Practices
- While a single sitemap will work for most applications. For large web applications, you may need to split a sitemap into multiple files.
- There are two ways you can create multiple sitemaps:
- By nesting sitemap.(xml|js|ts) inside multiple route segments e.g. app/sitemap.xml and app/products/sitemap.xml.
By using the generateSitemaps function.
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/sitemap |
What are the best practices for Generating multiple sitemaps in Next.js? |
```jsx
import { BASE_URL } from '@/app/lib/constants'
export async function generateSitemaps() {
// Fetch the total number of products and calculate the number of sitemaps needed
return [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }]
}
export default async function sitemap({ id }) {
// Google's limit is 50,000 URLs per sitemap
const start = id * 50000
const end = start + 50000
const products = await getProducts(
`SELECT id, date FROM products WHERE id BETWEEN ${start} AND ${end}`
)
return products.map((product) => ({
url: `${BASE_URL}/product/${product.id}`,
lastModified: product.date,
}))
}
```
## Best Practices
- While a single sitemap will work for most applications. For large web applications, you may need to split a sitemap into multiple files.
- There are two ways you can create multiple sitemaps:
- By nesting sitemap.(xml|js|ts) inside multiple route segments e.g. app/sitemap.xml and app/products/sitemap.xml.
By using the generateSitemaps function.
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/sitemap |
How do I implement page.js in Next.js? | The page file allows you to define UI that is unique to a route. You can create a page by default exporting a component from the file:
```javascript
export default function Page({ params, searchParams }) {
return <h1>My Page</h1>
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/page |
How do I implement params (optional) in Next.js? | A promise that resolves to an object containing the dynamic route parameters from the root segment down to that page.
```jsx
export default async function Page({ params }) {
const { slug } = await params
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/page |
How do I implement searchParams (optional) in Next.js? | A promise that resolves to an object containing the search parameters of the current URL. For example:
```jsx
export default async function Page({ searchParams }) {
const filters = (await searchParams).filters
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/page |
How do I implement Displaying content based on params in Next.js? | Using dynamic route segments, you can display or fetch specific content for the page based on the params prop.
```jsx
export default async function Page({ params }) {
const { slug } = await params
return <h1>Blog Post: {slug}</h1>
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/page |
How do I implement Handling filtering with searchParams in Next.js? | You can use the searchParams prop to handle filtering, pagination, or sorting based on the query string of the URL.
```jsx
export default async function Page({ searchParams }) {
const { page = '1', sort = 'asc', query = '' } = await searchParams
return (
<div>
<h1>Product Listing</h1>
<p>Search query: {query}</p>
<p>Current page: {page}</p>
<p>Sort order: {sort}</p>
</div>
)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/page |
How do I implement Reading searchParams and params in Client Components in Next.js? | To use searchParams and params in a Client Component (which cannot be async), you can use React's use function to read the promise:
```jsx
'use client'
import { use } from 'react'
export default function Page({ params, searchParams }) {
const { slug } = use(params)
const { query } = use(searchParams)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/page |
How do I implement .js in Next.js? | Route Handlers allow you to create custom request handlers for a given route using the Web Request and Response APIs.
```typescript
export async function GET() {
return Response.json({ message: 'Hello World' })
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/route |
How do I implement HTTP Methods in Next.js? | A route file allows you to create custom request handlers for a given route. The following HTTP methods are supported: GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS.
```javascript
export async function GET(request) {}
export async function HEAD(request) {}
export async function POST(request) {}
export async function PUT(request) {}
export async function DELETE(request) {}
export async function PATCH(request) {}
// If `OPTIONS` is not defined, Next.js will automatically implement `OPTIONS` and set the appropriate Response `Allow` header depending on the other methods defined in the Route Handler.
export async function OPTIONS(request) {}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/route |
How do I implement context (optional) in Next.js? | params: a promise that resolves to an object containing the dynamic route parameters for the current route.
```jsx
export async function GET(request, { params }) {
const { team } = await params
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/route |
How do I implement dynamicParams in Next.js? | Control what happens when a dynamic segment is visited that was not generated with generateStaticParams.
true (default): Dynamic segments not included in generateStaticParams are generated on demand.
false: Dynamic segments not included in generateStaticParams will return a 404.
Good to know:
```javascript
export const dynamicParams = true // true | false,
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config |
How do I implement revalidate in Next.js? | Set the default revalidation time for a layout or page. This option does not override the revalidate value set by individual fetch requests.
false (default): The default heuristic to cache any fetch requests that set their cache option to 'force-cache' or are discovered before a Dynamic API is used. Semantically equivalent to revalidate: Infinity which effectively means the resource should be cached indefinitely. It is still possible for individual fetch requests to use cache: 'no-store' or revalidate: 0 to avoid being cached and make the route dynamically rendered. Or set revalidate to a positive number lower than the route default to increase the revalidation frequency of a route.
0: Ensure a layout or page is always dynamically rendered even if no Dynamic APIs or uncached data fetches are discovered. This option changes the default of fetch requests that do not set a cache option to 'no-store' but leaves fetch requests that opt into 'force-cache' or use a positive revalidate as is.
number: (in seconds) Set the default revalidation frequency of a layout or page to n seconds.
Good to know:
The revalidate value needs to be statically analyzable. For example revalidate = 600 is valid, but revalidate = 60 * 10 is not.
The revalidate value is not available when using runtime = 'edge'.
In Development, Pages are always rendered on-demand and are never cached. This allows you to see changes immediately without waiting for a revalidation period to pass.
```javascript
export const revalidate = false
// false | 0 | number
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config |
How do I implement fetchCache in Next.js? | fetchCache allows you to override the default cache option of all fetch requests in a layout or page.
```javascript
export const fetchCache = 'auto'
// 'auto' | 'default-cache' | 'only-cache'
// 'force-cache' | 'force-no-store' | 'default-no-store' | 'only-no-store'
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config |
How do I implement runtime in Next.js? | We recommend using the Node.js runtime for rendering your application, and the Edge runtime for Middleware (only supported option).
Learn more about the different runtimes.
```javascript
export const runtime = 'nodejs'
// 'nodejs' | 'edge'
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config |
How do I implement preferredRegion in Next.js? | Support for preferredRegion, and regions supported, is dependent on your deployment platform.
Good to know:
If a preferredRegion is not specified, it will inherit the option of the nearest parent layout.
The root layout defaults to all regions.
```javascript
export const preferredRegion = 'auto'
// 'auto' | 'global' | 'home' | ['iad1', 'sfo1']
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config |
How do I implement maxDuration in Next.js? | Good to know:
If using Server Actions, set the maxDuration at the page level to change the default timeout of all Server Actions used on the page.
```javascript
export const maxDuration = 5
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config |
How do I implement .js in Next.js? | While less common, you might choose to use a template over a layout if you want:
```jsx
export default function Template({ children }) {
return <div>{children}</div>
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/template |
How do I implement children (required) in Next.js? | Template accepts a children prop. For example:
Good to know:
By default, template is a Server Component, but can also be used as a Client Component through the "use client" directive.
When a user navigates between routes that share a template, a new instance of the component is mounted, DOM elements are recreated, state is not preserved in Client Components, and effects are re-synchronized.
```jsx
<Layout>
{/* Note that the template is automatically given a unique key. */}
<Template key={routeParam}>{children}</Template>
</Layout>
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/template |
How do I implement Displaying login UI to unauthenticated users in Next.js? | You can use unauthorized function to render the unauthorized.js file with a login UI.
```jsx
import { verifySession } from '@/app/lib/dal'
import { unauthorized } from 'next/navigation'
export default async function DashboardPage() {
const session = await verifySession()
if (!session) {
unauthorized()
}
return <div>Dashboard</div>
}
```
```jsx
import Login from '@/app/components/Login'
export default function UnauthorizedPage() {
return (
<main>
<h1>401 - Unauthorized</h1>
<p>Please log in to access this page.</p>
<Login />
</main>
)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/file-conventions/unauthorized |
How do I implement Usage in Next.js? | Then, import and invoke the cacheLife function within the scope of the function or component:
```typescript
const nextConfig = {
experimental: {
dynamicIO: true,
},
}
export default nextConfig
```
```html
'use cache'
import { unstable_cacheLife as cacheLife } from 'next/cache'
export default async function Page() {
cacheLife('hours')
return <div>Page</div>
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/functions/cacheLife |
How do I implement Defining reusable cache profiles in Next.js? | The example above caches for 14 days, checks for updates daily, and expires the cache after 14 days. You can then reference this profile throughout your application by its name:
```typescript
const nextConfig = {
experimental: {
dynamicIO: true,
cacheLife: {
biweekly: {
stale: 60 * 60 * 24 * 14, // 14 days
revalidate: 60 * 60 * 24, // 1 day
expire: 60 * 60 * 24 * 14, // 14 days
},
},
},
}
module.exports = nextConfig
```
```typescript
'use cache'
import { unstable_cacheLife as cacheLife } from 'next/cache'
export default async function Page() {
cacheLife('biweekly')
return <div>Page</div>
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/functions/cacheLife |
How do I implement Overriding the default cache profiles in Next.js? | While the default cache profiles provide a useful way to think about how fresh or stale any given part of cacheable output can be, you may prefer different named profiles to better align with your applications caching strategies.
You can override the default named cache profiles by creating a new configuration with the same name as the defaults.
The example below shows how to override the default “days” cache profile:
```typescript
const nextConfig = {
experimental: {
dynamicIO: true,
cacheLife: {
days: {
stale: 3600, // 1 hour
revalidate: 900, // 15 minutes
expire: 86400, // 1 day
},
},
},
}
module.exports = nextConfig
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/functions/cacheLife |
How do I implement Defining cache profiles inline in Next.js? | For specific use cases, you can set a custom cache profile by passing an object to the cacheLife function:
```html
'use cache'
import { unstable_cacheLife as cacheLife } from 'next/cache'
export default async function Page() {
cacheLife({
stale: 3600, // 1 hour
revalidate: 900, // 15 minutes
expire: 86400, // 1 day
})
return <div>Page</div>
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/functions/cacheLife |
How do I implement Nested usage of use cache and cacheLife in Next.js? | For example, if you add the use cache directive to your page, without specifying a cache profile, the default cache profile will be applied implicitly (cacheLife(”default”)). If a component imported into the page also uses the use cache directive with its own cache profile, the outer and inner cache profiles are compared, and shortest duration set in the profiles will be applied.
And in a separate file, we defined the Child component that was imported:
```typescript
// Parent component
import { unstable_cacheLife as cacheLife } from 'next/cache'
import { ChildComponent } from './child'
export async function ParentComponent() {
'use cache'
cacheLife('days')
return (
<div>
<ChildComponent />
</div>
)
}
```
```typescript
// Child component
import { unstable_cacheLife as cacheLife } from 'next/cache'
export async function ChildComponent() {
'use cache'
cacheLife('hours')
return <div>Child Content</div>
// This component's cache will respect the shorter 'hours' profile
}
```
## Best Practices
- When defining multiple caching behaviors in the same route or component tree, if the inner caches specify their own cacheLife profile, the outer cache will respect the shortest cache duration among them. This applies only if the outer cache does not have its own explicit cacheLife profile defined.
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/functions/cacheLife |
What are the best practices for Nested usage of use cache and cacheLife in Next.js? |
```typescript
// Parent component
import { unstable_cacheLife as cacheLife } from 'next/cache'
import { ChildComponent } from './child'
export async function ParentComponent() {
'use cache'
cacheLife('days')
return (
<div>
<ChildComponent />
</div>
)
}
```
```typescript
// Child component
import { unstable_cacheLife as cacheLife } from 'next/cache'
export async function ChildComponent() {
'use cache'
cacheLife('hours')
return <div>Child Content</div>
// This component's cache will respect the shorter 'hours' profile
}
```
## Best Practices
- When defining multiple caching behaviors in the same route or component tree, if the inner caches specify their own cacheLife profile, the outer cache will respect the shortest cache duration among them. This applies only if the outer cache does not have its own explicit cacheLife profile defined.
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/functions/cacheLife |
How do I implement Usage in Next.js? | The cacheTag function takes a single string value, or a string array.
You can then purge the cache on-demand using revalidateTag API in another function, for example, a route handler or Server Action:
```typescript
const nextConfig = {
experimental: {
dynamicIO: true,
},
}
export default nextConfig
```
```javascript
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
}
```
```jsx
'use server'
import { revalidateTag } from 'next/cache'
export default async function submit() {
await addPost()
revalidateTag('my-data')
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/functions/cacheTag |
What are the best practices for Good to know in Next.js? |
```text
cacheTag('tag-one', 'tag-two')
```
## Best Practices
- 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.
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/functions/cacheTag |
How do I implement Tagging components or functions in Next.js? | Tag your cached data by calling cacheTag within a cached function or component:
```javascript
import { unstable_cacheTag as cacheTag } from 'next/cache'
export async function Bookings({ type = 'haircut' }) {
'use cache'
cacheTag('bookings-data')
async function getBookingsData() {
const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`)
return data
}
return //...
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/functions/cacheTag |
How do I implement Creating tags from external data in Next.js? | You can use the data returned from an async function to tag the cache entry.
```javascript
import { unstable_cacheTag as cacheTag } from 'next/cache'
export async function Bookings({ type = 'haircut' }) {
async function getBookingsData() {
'use cache'
const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`)
cacheTag('bookings-data', data.id)
return data
}
return //...
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/functions/cacheTag |
How do I implement Invalidating tagged cache in Next.js? | Using revalidateTag, you can invalidate the cache for a specific tag when needed:
```jsx
'use server'
import { revalidateTag } from 'next/cache'
export async function updateBookings() {
await updateBookingData()
revalidateTag('bookings-data')
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/functions/cacheTag |
How do I implement in Next.js? | The connection() function allows you to indicate rendering should wait for an incoming user request before continuing.
It's useful when a component doesn’t use Dynamic APIs, but you want it to be dynamically rendered at runtime and not statically rendered at build time. This usually occurs when you access external information that you intentionally want to change the result of a render, such as Math.random() or new Date().
```jsx
import { connection } from 'next/server'
export default async function Page() {
await connection()
// Everything below will be excluded from prerendering
const rand = Math.random()
return <span>{rand}</span>
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/functions/connection |
How do I implement in Next.js? | cookies is an async function that allows you to read the HTTP incoming request cookies in Server Components, and read/write outgoing request cookies in Server Actions or Route Handlers.
```jsx
import { cookies } from 'next/headers'
export default async function Page() {
const cookieStore = await cookies()
const theme = cookieStore.get('theme')
return '...'
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/functions/cookies |
How do I implement Getting a cookie in Next.js? | You can use the (await cookies()).get('name') method to get a single cookie:
```jsx
import { cookies } from 'next/headers'
export default async function Page() {
const cookieStore = await cookies()
const theme = cookieStore.get('theme')
return '...'
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/functions/cookies |
How do I implement Getting all cookies in Next.js? | You can use the (await cookies()).getAll() method to get all cookies with a matching name. If name is unspecified, it returns all the available cookies.
```jsx
import { cookies } from 'next/headers'
export default async function Page() {
const cookieStore = await cookies()
return cookieStore.getAll().map((cookie) => (
<div key={cookie.name}>
<p>Name: {cookie.name}</p>
<p>Value: {cookie.value}</p>
</div>
))
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/functions/cookies |
How do I implement Setting a cookie in Next.js? | You can use the (await cookies()).set(name, value, options) method in a Server Action or Route Handler to set a cookie. The options object is optional.
```jsx
'use server'
import { cookies } from 'next/headers'
export async function create(data) {
const cookieStore = await cookies()
cookieStore.set('name', 'lee')
// or
cookieStore.set('name', 'lee', { secure: true })
// or
cookieStore.set({
name: 'name',
value: 'lee',
httpOnly: true,
path: '/',
})
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/functions/cookies |
How do I implement Checking if a cookie exists in Next.js? | You can use the (await cookies()).has(name) method to check if a cookie exists:
```jsx
import { cookies } from 'next/headers'
export default async function Page() {
const cookieStore = await cookies()
const hasCookie = cookieStore.has('theme')
return '...'
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/functions/cookies |
How do I implement Deleting cookies in Next.js? | There are three ways you can delete a cookie.
Using the delete() method:
Setting a new cookie with the same name and an empty value:
Setting the maxAge to 0 will immediately expire a cookie. maxAge accepts a value in seconds.
```jsx
'use server'
import { cookies } from 'next/headers'
export async function delete(data) {
(await cookies()).delete('name')
}
```
```jsx
'use server'
import { cookies } from 'next/headers'
export async function delete(data) {
(await cookies()).set('name', '')
}
```
```jsx
'use server'
import { cookies } from 'next/headers'
export async function delete(data) {
(await cookies()).set('name', 'value', { maxAge: 0 })
``
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/functions/cookies |
How do I implement in Next.js? | In the browser, the cache option indicates how a fetch request will interact with the browser's HTTP cache. With this extension, cache indicates how a server-side fetch request will interact with the framework's persistent Data Cache.
You can call fetch with async and await directly within Server Components.
```jsx
export default async function Page() {
let data = await fetch('https://api.vercel.app/blog')
let posts = await data.json()
return (
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/functions/fetch |
How do I implement options.next.revalidate in Next.js? | Set the cache lifetime of a resource (in seconds).
false - Cache the resource indefinitely. Semantically equivalent to revalidate: Infinity. The HTTP cache may evict older resources over time.
0 - Prevent the resource from being cached.
number - (in seconds) Specify the resource should have a cache lifetime of at most n seconds.
Good to know:
```css
fetch(`https://...`, { next: { revalidate: false | 0 | number } })
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/functions/fetch |
How do I implement options.next.tags in Next.js? | Set the cache tags of a resource. Data can then be revalidated on-demand using revalidateTag. The max length for a custom tag is 256 characters and the max tag items is 128.
```css
fetch(`https://...`, { next: { tags: ['collection'] } })
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/functions/fetch |
How do I implement in Next.js? | forbidden can be invoked in Server Components, Server Actions, and Route Handlers.
```jsx
import { verifySession } from '@/app/lib/dal'
import { forbidden } from 'next/navigation'
export default async function AdminPage() {
const session = await verifySession()
// Check if the user has the 'admin' role
if (session.role !== 'admin') {
forbidden()
}
// Render the admin page for authorized users
return <></>
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/functions/forbidden |
How do I implement Role-based route protection in Next.js? | You can use forbidden to restrict access to certain routes based on user roles. This ensures that users who are authenticated but lack the required permissions cannot access the route.
```jsx
import { verifySession } from '@/app/lib/dal'
import { forbidden } from 'next/navigation'
export default async function AdminPage() {
const session = await verifySession()
// Check if the user has the 'admin' role
if (session.role !== 'admin') {
forbidden()
}
// Render the admin page for authorized users
return (
<main>
<h1>Admin Dashboard</h1>
<p>Welcome, {session.user.name}!</p>
</main>
)
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/functions/forbidden |
How do I implement Mutations with Server Actions in Next.js? | When implementing mutations in Server Actions, you can use forbidden to only allow users with a specific role to update sensitive data.
```jsx
'use server'
import { verifySession } from '@/app/lib/dal'
import { forbidden } from 'next/navigation'
import db from '@/app/lib/db'
export async function updateRole(formData) {
const session = await verifySession()
// Ensure only admins can update roles
if (session.role !== 'admin') {
forbidden()
}
// Perform the role update for authorized users
// ...
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/functions/forbidden |
How do I implement params (optional) in Next.js? | An object containing the dynamic route parameters object from the root segment down to the segment generateImageMetadata is called from.
```jsx
export function generateImageMetadata({ params }) {
// ...
}
```
Version info: 15.2.1 | https://nextjs.org/docs/app/api-reference/functions/generate-image-metadata |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.