text stringlengths 49 1.09k | source stringclasses 119
values | id stringlengths 14 15 |
|---|---|---|
minimumCacheTTL
You can configure the Time to Live (TTL) in seconds for cached optimized images. In many cases, it's better to use a Static Image Import which will automatically hash the file contents and cache the image forever with a Cache-Control header of immutable.
next.config.js module.exports = {
images: {
... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-25 |
There is no mechanism to invalidate the cache at this time, so its best to keep minimumCacheTTL low. Otherwise you may need to manually change the src prop or delete <distDir>/cache/images.
disableStaticImages
The default behavior allows you to import static files such as import icon from './icon.png and then pass that... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-26 |
disableStaticImages: true,
},
}
dangerouslyAllowSVG
The default loader does not optimize SVG images for a few reasons. First, SVG is a vector format meaning it can be resized losslessly. Second, SVG has many of the same features as HTML/CSS, which can lead to vulnerabilities without proper Content Security Policy (CS... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-27 |
Animated Images
The default loader will automatically bypass Image Optimization for animated images and serve the image as-is.
Auto-detection for animated files is best-effort and supports GIF, APNG, and WebP. If you want to explicitly bypass Image Optimization for a given animated image, use the unoptimized prop.
Know... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-28 |
Use CSS @supports (font: -apple-system-body) and (-webkit-appearance: none) { img[loading="lazy"] { clip-path: inset(0.6px) } }
Use priority if the image is above the fold
Firefox 67+ displays a white background while loading. Possible solutions:
Enable AVIF formats
Use placeholder="blur"
Version History | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-29 |
VersionChangesv13.2.0contentDispositionType configuration added.v13.0.6ref prop added.v13.0.0The next/image import was renamed to next/legacy/image. The next/future/image import was renamed to next/image. A codemod is available to safely and automatically rename your imports. <span> wrapper removed. layout, objectFit, ... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-30 |
prop added.v12.0.0formats configuration added.AVIF support added.Wrapper <div> changed to <span>.v11.1.0onLoadingComplete and lazyBoundary props added.v11.0.0src prop support for static import.placeholder prop added.blurDataURL prop added.v10.0.5loader prop added.v10.0.1layout prop added.v10.0.0next/image introduced. | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-31 |
<Link>
Examples
Hello World
Active className on Link
<Link> is a React component that extends the HTML <a> element to provide prefetching and client-side navigation between routes. It is the primary way to navigate between routes in Next.js.
app/page.tsx import Link from 'next/link'
export default function Page() {
... | https://nextjs.org/docs/app/api-reference/components/link | 203eaae39911-0 |
The path or URL to navigate to.
<Link href="/dashboard">Dashboard</Link>
href can also accept an object, for example:
// Navigate to /about?name=test
<Link
href={{
pathname: '/about',
query: { name: 'test' },
}}
>
About
</Link>
replace
Defaults to false. When true, next/link will replace the current his... | https://nextjs.org/docs/app/api-reference/components/link | 203eaae39911-1 |
Dashboard
</Link>
)
}
prefetch
Defaults to true. When true, next/link will prefetch the page (denoted by the href) in the background. This is useful for improving the performance of client-side navigations. Any <Link /> in the viewport (initially or through scroll) will be preloaded.
Prefetch can be disabled by p... | https://nextjs.org/docs/app/api-reference/components/link | 203eaae39911-2 |
For dynamic routes, it can be handy to use template literals to create the link's path.
For example, you can generate a list of links to the dynamic route app/blog/[slug]/page.js:app/blog/page.js import Link from 'next/link'
function Page({ posts }) {
return (
<ul>
{posts.map((post) => (
<li key={... | https://nextjs.org/docs/app/api-reference/components/link | 203eaae39911-3 |
))}
</ul>
)
}
Middleware
It's common to use Middleware for authentication or other purposes that involve rewriting the user to a different page. In order for the <Link /> component to properly prefetch links with rewrites via Middleware, you need to tell Next.js both the URL to display and the URL to prefetch. Th... | https://nextjs.org/docs/app/api-reference/components/link | 203eaae39911-4 |
} else {
return NextResponse.rewrite(new URL('/public/dashboard', req.url))
}
}
}
In this case, you would want to use the following code in your <Link /> component:
import Link from 'next/link'
import useIsAuthed from './hooks/useIsAuthed'
export default function Page() {
const isAuthed = useIsAuthed()... | https://nextjs.org/docs/app/api-reference/components/link | 203eaae39911-5 |
Dashboard
</Link>
)
}
Version History
VersionChangesv13.0.0No longer requires a child <a> tag. A codemod is provided to automatically update your codebase.v10.0.0href props pointing to a dynamic route are automatically resolved and no longer require an as prop.v8.0.0Improved prefetching performance.v1.0.0next/lin... | https://nextjs.org/docs/app/api-reference/components/link | 203eaae39911-6 |
Font Module
This API reference will help you understand how to use next/font/google and next/font/local. For features and usage, please see the Optimizing Fonts page.
Font Function Arguments
For usage, review Google Fonts and Local Fonts.
Keyfont/googlefont/localTypeRequiredsrcString or Array of ObjectsYesweightString ... | https://nextjs.org/docs/app/api-reference/components/font | ffbe1227091a-0 |
src:[{path: './inter/Inter-Thin.ttf', weight: '100',},{path: './inter/Inter-Regular.ttf',weight: '400',},{path: './inter/Inter-Bold-Italic.ttf', weight: '700',style: 'italic',},]
if the font loader function is called in app/page.tsx using src:'../styles/fonts/my-font.ttf', then my-font.ttf is placed in styles/fonts at ... | https://nextjs.org/docs/app/api-reference/components/font | ffbe1227091a-1 |
Required if the font being used is not variable
Examples:
weight: '400': A string for a single weight value - for the font Inter, the possible values are '100', '200', '300', '400', '500', '600', '700', '800', '900' or 'variable' where 'variable' is the default)
weight: '100 900': A string for the range between 100 and... | https://nextjs.org/docs/app/api-reference/components/font | ffbe1227091a-2 |
style: 'italic': A string - it can be normal or italic for next/font/google
style: 'oblique': A string - it can take any value for next/font/local but is expected to come from standard font styles
style: ['italic','normal']: An array of 2 values for next/font/google - the values are from normal and italic
subsets
The f... | https://nextjs.org/docs/app/api-reference/components/font | ffbe1227091a-3 |
You can find a list of all subsets on the Google Fonts page for your font.
axes
Some variable fonts have extra axes that can be included. By default, only the font weight is included to keep the file size down. The possible values of axes depend on the specific font.
Used in next/font/google
Optional
Examples:
axes: ['... | https://nextjs.org/docs/app/api-reference/components/font | ffbe1227091a-4 |
Optional
Examples:
display: 'optional': A string assigned to the optional value
preload
A boolean value that specifies whether the font should be preloaded or not. The default is true.
Used in next/font/google and next/font/local
Optional
Examples:
preload: false
fallback
The fallback font to use if the font cannot be ... | https://nextjs.org/docs/app/api-reference/components/font | ffbe1227091a-5 |
For next/font/local: A string or boolean false value that sets whether an automatic fallback font should be used to reduce Cumulative Layout Shift. The possible values are 'Arial', 'Times New Roman' or false. The default is 'Arial'.
Used in next/font/google and next/font/local
Optional
Examples:
adjustFontFallback: fal... | https://nextjs.org/docs/app/api-reference/components/font | ffbe1227091a-6 |
declarations: [{ prop: 'ascent-override', value: '90%' }]
Applying Styles
You can apply the font styles in three ways:
className
style
CSS Variables
className
Returns a read-only CSS className for the loaded font to be passed to an HTML element.
<p className={inter.className}>Hello, Next.js!</p>
style
Returns a read-o... | https://nextjs.org/docs/app/api-reference/components/font | ffbe1227091a-7 |
app/page.tsx import { Inter } from 'next/font/google'
import styles from '../styles/component.module.css'
const inter = Inter({
variable: '--font-inter',
})
To use the font, set the className of the parent container of the text you would like to style to the font loader's variable value and the className of the tex... | https://nextjs.org/docs/app/api-reference/components/font | ffbe1227091a-8 |
font-weight: 200;
font-style: italic;
}
In the example above, the text Hello World is styled using the Inter font and the generated font fallback with font-weight: 200 and font-style: italic.
Using a font definitions file
Every time you call the localFont or Google font function, that font will be hosted as one insta... | https://nextjs.org/docs/app/api-reference/components/font | ffbe1227091a-9 |
// define your variable fonts
const inter = Inter()
const lora = Lora()
// define 2 weights of a non-variable font
const sourceCodePro400 = Source_Sans_Pro({ weight: '400' })
const sourceCodePro700 = Source_Sans_Pro({ weight: '700' })
// define a custom local font where GreatVibes-Regular.ttf is stored in the styles fo... | https://nextjs.org/docs/app/api-reference/components/font | ffbe1227091a-10 |
export default function Page() {
return (
<div>
<p className={inter.className}>Hello world using Inter font</p>
<p style={lora.style}>Hello world using Lora font</p>
<p className={sourceCodePro700.className}>
Hello world using Source_Sans_Pro font with weight 700
</p>
<p clas... | https://nextjs.org/docs/app/api-reference/components/font | ffbe1227091a-11 |
}
}
}
You can now import any font definition as follows:
app/about/page.tsx import { greatVibes, sourceCodePro400 } from '@/fonts'
Version Changes
VersionChangesv13.2.0@next/font renamed to next/font. Installation no longer required.v13.0.0@next/font was added. | https://nextjs.org/docs/app/api-reference/components/font | ffbe1227091a-12 |
loading.jsA 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.
app/feed/loading.tsx export default function Loading() {
// Or a custom loading skeleton component
return <p>'Loa... | https://nextjs.org/docs/app/api-reference/file-conventions/loading | b63befe4728f-0 |
page.jsA page is UI that is unique to a route.
app/blog/[slug]/page.tsx export default function Page({
params,
searchParams,
}: {
params: { slug: string }
searchParams: { [key: string]: string | string[] | undefined }
}) {
return <h1>My Page</h1>
}
Props
params (optional)
An object containing the dynamic rout... | https://nextjs.org/docs/app/api-reference/file-conventions/page | 5dff92328324-0 |
searchParams (optional)
An object containing the search parameters of the current URL. For example:
URLsearchParams/shop?a=1{ a: '1' }/shop?a=1&b=2{ a: '1', b: '2' }/shop?a=1&a=2{ a: ['1', '2'] }
Good to know:
searchParams is a Dynamic API whose values cannot be known ahead of time. Using it will opt the page into dyna... | https://nextjs.org/docs/app/api-reference/file-conventions/page | 5dff92328324-1 |
Route Segment ConfigThe Route Segment options allows you configure the behavior of a Page, Layout, or Route Handler by directly exporting the following variables:
OptionTypeDefaultdynamic'auto' | 'force-dynamic' | 'error' | 'force-static''auto'dynamicParamsbooleantruerevalidatefalse | 'force-cache' | 0 | numberfalsefet... | https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config | 3f6b8dc57d93-0 |
export const revalidate = false
export const fetchCache = 'auto'
export const runtime = 'nodejs'
export const preferredRegion = 'auto'
export const maxDuration = 5
export default function MyComponent() {}
Good to know:
The values of the config options currently need be statically analyzable. For example revalidate = ... | https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config | 3f6b8dc57d93-1 |
// 'auto' | 'force-dynamic' | 'error' | 'force-static'
Good to know: The new model in the app directory favors granular caching control at the fetch request level over the binary all-or-nothing model of getServerSideProps and getStaticProps at the page-level in the pages directory. The dynamic option is a way to opt ba... | https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config | 3f6b8dc57d93-2 |
Setting the segment config to export const fetchCache = 'force-no-store'
'error': Force static rendering and static data fetching of a layout or page by causing an error if any components use dynamic functions or dynamic fetches. This option is equivalent to:
getStaticProps() in the pages directory.
Setting the option ... | https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config | 3f6b8dc57d93-3 |
Good to know:
Instructions on how to migrate from getServerSideProps and getStaticProps to dynamic: 'force-dynamic' and dynamic: 'error' can be found in the upgrade guide.
dynamicParams
Control what happens when a dynamic segment is visited that was not generated with generateStaticParams.
layout.tsx / page.tsx export ... | https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config | 3f6b8dc57d93-4 |
revalidate
Set the default revalidation time for a layout or page. This option does not override the revalidate value set by individual fetch requests.
layout.tsx / page.tsx / route.ts export const revalidate = false
// false | 'force-cache' | 0 | number
false: (default) The default heuristic to cache any fetch request... | https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config | 3f6b8dc57d93-5 |
0: Ensure a layout or page is always dynamically rendered even if no dynamic functions or dynamic 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: ... | https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config | 3f6b8dc57d93-6 |
fetchCache
This is an advanced option that should only be used if you specifically need to override the default behavior.By default, Next.js will cache any fetch() requests that are reachable before any dynamic functions are used and will not cache fetch requests that are discovered after dynamic functions are used.fet... | https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config | 3f6b8dc57d93-7 |
'default-cache': Allow any cache option to be passed to fetch but if no option is provided then set the cache option to 'force-cache'. This means that even fetch requests after dynamic functions are considered static.
'only-cache': Ensure all fetch requests opt into caching by changing the default to cache: 'force-cach... | https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config | 3f6b8dc57d93-8 |
'only-no-store': Ensure all fetch requests opt out of caching by changing the default to cache: 'no-store' if no option is provided and causing an error if any fetch requests use cache: 'force-cache'
'force-no-store': Ensure all fetch requests opt out of caching by setting the cache option of all fetch requests to 'no-... | https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config | 3f6b8dc57d93-9 |
The intention of the 'only-*' and force-*' options is to guarantee the whole route is either fully static or fully dynamic. This means:
A combination of 'only-cache' and 'only-no-store' in a single route is not allowed.
A combination of 'force-cache' and 'force-no-store' in a single route is not allowed.
A parent canno... | https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config | 3f6b8dc57d93-10 |
edge
Learn more about the Edge and Node.js runtimes.
preferredRegion
layout.tsx / page.tsx / route.ts export const preferredRegion = 'auto'
// 'auto' | 'global' | 'home' | ['iad1', 'sfo1']
Support for preferredRegion, and regions supported, is dependent on your deployment platform.
Good to know:
If a preferredRegion is... | https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config | 3f6b8dc57d93-11 |
Good to know:
If a maxDuration is not specified, the default value is dependent on your deployment platform and plan.
generateStaticParams
The generateStaticParams function can be used in combination with dynamic route segments to define the list of route segment parameters that will be statically generated at build ti... | https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config | 3f6b8dc57d93-12 |
not-found.jsThe not-found file is used to render UI when the notFound function is thrown within a route segment. Along with serving a custom UI, Next.js will also return a 404 HTTP status code.
app/blog/not-found.tsx import Link from 'next/link'
export default function NotFound() {
return (
<div>
<h2>Not ... | https://nextjs.org/docs/app/api-reference/file-conventions/not-found | 549859653530-0 |
Props
not-found.js components do not accept any props.
Version History
VersionChangesv13.3.0Root app/not-found handles global unmatched URLs.v13.0.0not-found introduced. | https://nextjs.org/docs/app/api-reference/file-conventions/not-found | 549859653530-1 |
default.jsThis documentation is still being written. Please check back later. | https://nextjs.org/docs/app/api-reference/file-conventions/default | 5b4d53cb5f10-0 |
layout.jsA layout is UI that is shared between routes.
app/dashboard/layout.tsx export default function DashboardLayout({
children,
}: {
children: React.ReactNode
}) {
return <section>{children}</section>
}
A root layout is the top-most layout in the root app directory. It is used to define the <html> and <body> ... | https://nextjs.org/docs/app/api-reference/file-conventions/layout | daead9f057ce-0 |
</html>
)
}
Props
children (required)
Layout components should accept and use a children prop. During rendering, children will be populated with the route segments the layout is wrapping. These will primarily be the component of a child Layout (if it exists) or Page, but could also be other special files like Loading... | https://nextjs.org/docs/app/api-reference/file-conventions/layout | daead9f057ce-1 |
children,
params,
}: {
children: React.ReactNode
params: {
tag: string
item: string
}
}) {
// URL -> /shop/shoes/nike-air-max-97
// `params` -> { tag: 'shoes', item: 'nike-air-max-97' }
return <section>{children}</section>
}
Good to know
Layout's do not receive searchParams
Unlike Pages, Layout co... | https://nextjs.org/docs/app/api-reference/file-conventions/layout | daead9f057ce-2 |
app
└── dashboard
├── layout.tsx
├── settings
│ └── page.tsx
└── analytics
└── page.js
When navigating from /dashboard/settings to /dashboard/analytics, page.tsx in /dashboard/analytics will be rendered on the server because it is UI that changed, while dashboard/layout.tsx will not be re-rend... | https://nextjs.org/docs/app/api-reference/file-conventions/layout | daead9f057ce-3 |
Root Layouts
The app directory must include a root app/layout.js.
The root layout must define <html> and <body> tags.
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-du... | https://nextjs.org/docs/app/api-reference/file-conventions/layout | daead9f057ce-4 |
error.jsAn error file defines an error UI boundary for a route segment.
It is useful for catching unexpected errors that occur in Server Components and Client Components and displaying a fallback UI.
app/dashboard/error.tsx 'use client' // Error components must be Client Components
import { useEffect } from 'react'
... | https://nextjs.org/docs/app/api-reference/file-conventions/error | ce900edacbc3-0 |
}
>
Try again
</button>
</div>
)
}
Props
error
An instance of an Error object forwarded to the error.js Client Component.
error.message
The error message.
For errors forwarded from Client Components, this will be the original Error's message.
For errors forwarded from Server Components, this w... | https://nextjs.org/docs/app/api-reference/file-conventions/error | ce900edacbc3-1 |
Can be used to prompt the user to attempt to recover from the error.
Good to know:
error.js boundaries must be Client Components.
In Production builds, errors forwarded from Server Components will be stripped of specific error details to avoid leaking sensitive information.
An error.js boundary will not handle errors t... | https://nextjs.org/docs/app/api-reference/file-conventions/error | ce900edacbc3-2 |
reset,
}: {
error: Error & { digest?: string }
reset: () => void
}) {
return (
<html>
<body>
<h2>Something went wrong!</h2>
<button onClick={() => reset()}>Try again</button>
</body>
</html>
)
}
Good to know:
global-error.js replaces the root layout.js when active and so must... | https://nextjs.org/docs/app/api-reference/file-conventions/error | ce900edacbc3-3 |
route.jsRoute Handlers allow you to create custom request handlers for a given route using the Web Request and Response APIs.
HTTP Methods
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.
route.ts exp... | https://nextjs.org/docs/app/api-reference/file-conventions/route | 173d62e111d5-0 |
export async function OPTIONS(request: Request) {}
Good to know: Route Handlers are only available inside the app directory. You do not need to use API Routes (pages) and Route Handlers (app) together, as Route Handlers should be able to handle all use cases.
Parameters
request (optional)
The request object is a NextRe... | https://nextjs.org/docs/app/api-reference/file-conventions/route | 173d62e111d5-1 |
ExampleURLparamsapp/dashboard/[team]/route.js/dashboard/1{ team: '1' }app/shop/[tag]/[item]/route.js/shop/1/2{ tag: '1', item: '2' }app/blog/[...slug]/route.js/blog/1/2{ slug: ['1', '2'] }
NextResponse
Route Handlers can extend the Web Response API by returning a NextResponse object. This allows you to easily set cooki... | https://nextjs.org/docs/app/api-reference/file-conventions/route | 173d62e111d5-2 |
template.jsThis documentation is still being written. Please check back later. | https://nextjs.org/docs/app/api-reference/file-conventions/template | d3ecffb40136-0 |
sitemap.xmlAdd or generate a sitemap.xml file that matches the Sitemaps XML format in the root of app directory to help search engine crawlers crawl your site more efficiently.
Static sitemap.xml
app/sitemap.xml <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://acme.com</loc>
<la... | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/sitemap | 3cdd33546faf-0 |
<url>
<loc>https://acme.com/blog</loc>
<lastmod>2023-04-06T15:02:24.021Z</lastmod>
</url>
</urlset>
Generate a Sitemap
Add a sitemap.js or sitemap.ts file that returns Sitemap.
app/sitemap.ts import { MetadataRoute } from 'next'
export default function sitemap(): MetadataRoute.Sitemap {
return [
{
... | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/sitemap | 3cdd33546faf-1 |
lastModified: new Date(),
},
]
}
Output:
acme.com/sitemap.xml <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://acme.com</loc>
<lastmod>2023-04-06T15:02:24.021Z</lastmod>
</url>
<url>
<loc>https://acme.com/about</loc>
<lastmod>2023-04-06T15:02:24.021Z</lastmod>
... | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/sitemap | 3cdd33546faf-2 |
</url>
</urlset>
Sitemap Return Type
type Sitemap = Array<{
url: string
lastModified?: string | Date
}>
Good to know
In the future, we will support multiple sitemaps and sitemap indexes.
Version History
VersionChangesv13.3.0sitemap introduced. | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/sitemap | 3cdd33546faf-3 |
opengraph-image and twitter-imageThe opengraph-image and twitter-image file conventions allow you to set Open Graph and Twitter images for a route segment.
They are useful for setting the images that appear on social networks and messaging apps when a user shares a link to your site.
There are two ways to set Open Grap... | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/opengraph-image | bbc1244549d6-0 |
File conventionSupported file typesopengraph-image.jpg, .jpeg, .png, .giftwitter-image.jpg, .jpeg, .png, .gifopengraph-image.alt.txttwitter-image.alt.txt
opengraph-image
Add an opengraph-image.(jpg|jpeg|png|gif) image file to any route segment.
<head> output <meta property="og:image" content="<generated>" />
<meta prop... | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/opengraph-image | bbc1244549d6-1 |
<meta name="twitter:image:width" content="<generated>" />
<meta name="twitter:image:height" content="<generated>" />
opengraph-image.alt.txt
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.
opengraph-image.alt.txt About Acme
<head>... | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/opengraph-image | bbc1244549d6-2 |
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.
File conventionSupported file typesopengraph-image.js, .ts, .tsxtwitter-image.js, .ts, .tsx
Good t... | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/opengraph-image | bbc1244549d6-3 |
export const size = {
width: 1200,
height: 630,
}
export const contentType = 'image/png'
// Font
const interSemiBold = fetch(
new URL('./Inter-SemiBold.ttf', import.meta.url)
).then((res) => res.arrayBuffer())
// Image generation
export default async function Image() {
return new ImageResponse(
(
... | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/opengraph-image | bbc1244549d6-4 |
</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: await interSemiBold,
style: 'normal',
... | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/opengraph-image | bbc1244549d6-5 |
Props
The default export function receives the following props:
params (optional)
An object containing the dynamic route parameters object from the root segment down to the segment opengraph-image or twitter-image is colocated in.
app/shop/[slug]/opengraph-image.tsx export default function Image({ params }: { params: {... | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/opengraph-image | bbc1244549d6-6 |
Good to know: ImageResponse satisfies this return type.
Config exports
You can optionally configure the image's metadata by exporting alt, size, and contentType variables from opengraph-image or twitter-image route.
OptionTypealtstringsize{ width: number; height: number }contentTypestring - image MIME type
alt
opengrap... | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/opengraph-image | bbc1244549d6-7 |
<meta property="og:image:height" content="630" />
contentType
opengraph-image.tsx / twitter-image.tsx export const contentType = 'image/png'
export default function Image() {}
<head> output <meta property="og:image:type" content="image/png" />
Route Segment Config
opengraph-image and twitter-image are specialized Rou... | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/opengraph-image | bbc1244549d6-8 |
export default function Image() {}
Examples
Using external data
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.
app/... | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/opengraph-image | bbc1244549d6-9 |
res.json()
)
return new ImageResponse(
(
<div
style={{
fontSize: 48,
background: 'white',
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
{post.title}
... | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/opengraph-image | bbc1244549d6-10 |
favicon, icon, and apple-iconThe favicon, icon, or apple-icon file conventions allow you to set icons for your application.
They are useful for adding app icons that appear in places like web browser tabs, phone home screens, and search engine results.
There are two ways to set app icons:
Using image files (.ico, .jpg,... | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/app-icons | 1a9329fe7b0d-0 |
File conventionSupported file typesValid locationsfavicon.icoapp/icon.ico, .jpg, .jpeg, .png, .svgapp/**/*apple-icon.jpg, .jpeg, .pngapp/**/*
favicon
Add a favicon.ico image file to the root /app route segment.
<head> output <link rel="icon" href="/favicon.ico" sizes="any" />
icon
Add an icon.(ico|jpg|jpeg|png|svg) ima... | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/app-icons | 1a9329fe7b0d-1 |
type="image/<generated>"
sizes="<generated>"
/>
Good to know
You can set multiple icons by adding a number suffix to the file name. For example, icon1.png, icon2.png, etc. Numbered files will sort lexically.
Favicons can only be set in the root /app segment. If you need more granularity, you can use icon.
The appropr... | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/app-icons | 1a9329fe7b0d-2 |
Generate icons using code (.js, .ts, .tsx)
In addition to using literal image files, you can programmatically generate icons using code.
Generate an app icon by creating an icon or apple-icon route that default exports a function.
File conventionSupported file typesicon.js, .ts, .tsxapple-icon.js, .ts, .tsx
The easiest... | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/app-icons | 1a9329fe7b0d-3 |
(
// ImageResponse JSX element
<div
style={{
fontSize: 24,
background: 'black',
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: 'white',
}}
>
A... | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/app-icons | 1a9329fe7b0d-4 |
Good to know
By default, generated icons are statically optimized (generated at build time and cached) unless they use dynamic functions or dynamic data fetching.
You can generate multiple icons in the same file using generateImageMetadata.
You cannot generate a favicon icon. Use icon or a favicon.ico file instead.
Pro... | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/app-icons | 1a9329fe7b0d-5 |
// ...
}
RouteURLparamsapp/shop/icon.js/shopundefinedapp/shop/[slug]/icon.js/shop/1{ slug: '1' }app/shop/[tag]/[item]/icon.js/shop/1/2{ tag: '1', item: '2' }app/shop/[...slug]/icon.js/shop/1/2{ slug: ['1', '2'] }
Returns
The default export function should return a Blob | ArrayBuffer | TypedArray | DataView | ReadableSt... | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/app-icons | 1a9329fe7b0d-6 |
export default function Icon() {}
<head> output <link rel="icon" sizes="32x32" />
contentType
icon.tsx / apple-icon.tsx export const contentType = 'image/png'
export default function Icon() {}
<head> output <link rel="icon" type="image/png" />
Route Segment Config
icon and apple-icon are specialized Route Handlers th... | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/app-icons | 1a9329fe7b0d-7 |
export default function Icon() {}
Version History
VersionChangesv13.3.0favicon icon and apple-icon introduced | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/app-icons | 1a9329fe7b0d-8 |
robots.txtAdd or generate a robots.txt file that matches the Robots Exclusion Standard in the root of app directory to tell search engine crawlers which URLs they can access on your site.
Static robots.txt
app/robots.txt User-Agent: *
Allow: /
Disallow: /private/
Sitemap: https://acme.com/sitemap.xml
Generate a Robots ... | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/robots | 8824164bfdb7-0 |
Disallow: /private/
Sitemap: https://acme.com/sitemap.xml
Robots object
type Robots = {
rules:
| {
userAgent?: string | string[]
allow?: string | string[]
disallow?: string | string[]
crawlDelay?: number
}
| Array<{
userAgent: string | string[]
allow?: st... | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/robots | 8824164bfdb7-1 |
Building Your Application
Next.js provides the building blocks to create flexible, full-stack web applications. The guides in Building Your Application explain how to use these features and how to customize your application's behavior.
The sections and pages are organized sequentially, from basic to advanced, so you ca... | https://nextjs.org/docs/app/building-your-application/index.html | 4a40f1998031-0 |
Error HandlingThe error.js file convention allows you to gracefully handle unexpected runtime errors in nested routes.
Automatically wrap a route segment and its nested children in a React Error Boundary.
Create error UI tailored to specific segments using the file-system hierarchy to adjust granularity.
Isolate errors... | https://nextjs.org/docs/app/building-your-application/routing/error-handling | 33b391defb55-0 |
console.error(error)
}, [error])
return (
<div>
<h2>Something went wrong!</h2>
<button
onClick={
// Attempt to recover by trying to re-render the segment
() => reset()
}
>
Try again
</button>
</div>
)
}
How error.js Works
error.js autom... | https://nextjs.org/docs/app/building-your-application/routing/error-handling | 33b391defb55-1 |
Recovering From Errors
The cause of an error can sometimes be temporary. In these cases, simply trying again might resolve the issue.
An error component can use the reset() function to prompt the user to attempt to recover from the error. When executed, the function will try to re-render the Error boundary's contents. ... | https://nextjs.org/docs/app/building-your-application/routing/error-handling | 33b391defb55-2 |
}
Nested Routes
React components created through special files are rendered in a specific nested hierarchy.
For example, a nested route with two segments that both include layout.js and error.js files are rendered in the following simplified component hierarchy:
The nested component hierarchy has implications for the b... | https://nextjs.org/docs/app/building-your-application/routing/error-handling | 33b391defb55-3 |
Handling Errors in Layouts
error.js boundaries do not catch errors thrown in layout.js or template.js components of the same segment. This intentional hierarchy keeps important UI that is shared between sibling routes (such as navigation) visible and functional when an error occurs.
To handle errors within a specific l... | https://nextjs.org/docs/app/building-your-application/routing/error-handling | 33b391defb55-4 |
Unlike the root error.js, the global-error.js error boundary wraps the entire application, and its fallback component replaces the root layout when active. Because of this, it is important to note that global-error.js must define its own <html> and <body> tags.
global-error.js is the least granular error UI and can be ... | https://nextjs.org/docs/app/building-your-application/routing/error-handling | 33b391defb55-5 |
reset: () => void
}) {
return (
<html>
<body>
<h2>Something went wrong!</h2>
<button onClick={() => reset()}>Try again</button>
</body>
</html>
)
}
Handling Server Errors
If an error is thrown inside a Server Component, Next.js will forward an Error object (stripped of sensitive ... | https://nextjs.org/docs/app/building-your-application/routing/error-handling | 33b391defb55-6 |
During development, the Error object forwarded to the client will be serialized and include the message of the original error for easier debugging. | https://nextjs.org/docs/app/building-your-application/routing/error-handling | 33b391defb55-7 |
Route HandlersRoute Handlers allow you to create custom request handlers for a given route using the Web Request and Response APIs.
Good to know: Route Handlers are only available inside the app directory. They are the equivalent of API Routes inside the pages directory meaning you do not need to use API Routes and Rou... | https://nextjs.org/docs/app/building-your-application/routing/router-handlers | bca5fbe12397-0 |
Extended NextRequest and NextResponse APIs
In addition to supporting native Request and Response. Next.js extends them with
NextRequest and NextResponse to provide convenient helpers for advanced use cases.
Behavior
Static Route Handlers
Route Handlers are statically evaluated by default when using the GET method with ... | https://nextjs.org/docs/app/building-your-application/routing/router-handlers | bca5fbe12397-1 |
Dynamic Route Handlers
Route handlers are evaluated dynamically when:
Using the Request object with the GET method.
Using any of the other HTTP methods.
Using Dynamic Functions like cookies and headers.
The Segment Config Options manually specifies dynamic mode.
For example:
app/products/api/route.ts import { NextRespo... | https://nextjs.org/docs/app/building-your-application/routing/router-handlers | bca5fbe12397-2 |
}
Similarly, the POST method will cause the Route Handler to be evaluated dynamically.
app/items/route.ts import { NextResponse } from 'next/server'
export async function POST() {
const res = await fetch('https://data.mongodb-api.com/...', {
method: 'POST',
headers: {
'Content-Type': 'application/json... | https://nextjs.org/docs/app/building-your-application/routing/router-handlers | bca5fbe12397-3 |
Route Resolution
You can consider a route the lowest level routing primitive.
They do not participate in layouts or client-side navigations like page.
There cannot be a route.js file at the same route as page.js.
PageRouteResultapp/page.jsapp/route.js Conflictapp/page.jsapp/api/route.js Validapp/[user]/page.jsapp/api/r... | https://nextjs.org/docs/app/building-your-application/routing/router-handlers | bca5fbe12397-4 |
You can revalidate static data fetches using the next.revalidate option:
app/items/route.ts import { NextResponse } from 'next/server'
export async function GET() {
const res = await fetch('https://data.mongodb-api.com/...', {
next: { revalidate: 60 }, // Revalidate every 60 seconds
})
const data = await re... | https://nextjs.org/docs/app/building-your-application/routing/router-handlers | bca5fbe12397-5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.