Amaraa0404/AI-First
Question Answering • Updated
id stringlengths 14 15 | text stringlengths 49 1.09k | source stringlengths 38 101 |
|---|---|---|
18165c3b636a-0 | App RouterThe App Router is a new paradigm for building applications using React's latest features. If you're already familiar with Next.js, you'll find that the App Router is a natural evolution of the existing file-system based router in the Pages Router.
For new applications, we recommend using the App Router. For e... | https://nextjs.org/docs/app/index.html |
73171eae48e7-0 | Next.js CLI
The Next.js CLI allows you to start, build, and export your application.
To get a list of the available CLI commands, run the following command inside your project directory:
Terminal npx next -h
(npx comes with npm 5.2+ and higher)
The output should look like this:
Terminal Usage
$ next <command>
Avail... | https://nextjs.org/docs/app/api-reference/next-cli |
73171eae48e7-1 | NODE_OPTIONS='-r esm' next
NODE_OPTIONS='--inspect' next
Good to know: Running next without a command is the same as running next dev
Build
next build creates an optimized production build of your application. The output displays information about each route.
Size – The number of assets downloaded when navigating to th... | https://nextjs.org/docs/app/api-reference/next-cli |
73171eae48e7-2 | After that, you can use the profiler in the same way as you would in development.
You can enable more verbose build output with the --debug flag in next build. This requires Next.js 9.5.3:
Terminal next build --debug
With this flag enabled additional build output like rewrites, redirects, and headers will be shown.
Dev... | https://nextjs.org/docs/app/api-reference/next-cli |
73171eae48e7-3 | You can also set the hostname to be different from the default of 0.0.0.0, this can be useful for making the application available for other devices on the network. The default hostname can be changed with -H, like so:
Terminal npx next dev -H 192.168.1.2
Production
next start starts the application in production mode.... | https://nextjs.org/docs/app/api-reference/next-cli |
73171eae48e7-4 | Keep Alive Timeout
When deploying Next.js behind a downstream proxy (e.g. a load-balancer like AWS ELB/ALB) it's important to configure Next's underlying HTTP server with keep-alive timeouts that are larger than the downstream proxy's timeouts. Otherwise, once a keep-alive timeout is reached for a given TCP connection,... | https://nextjs.org/docs/app/api-reference/next-cli |
73171eae48e7-5 | your application.
If you have other directories that you would like to lint, you can specify them using the --dir
flag:
Terminal next lint --dir utils
Telemetry
Next.js collects completely anonymous telemetry data about general usage.
Participation in this anonymous program is optional, and you may opt-out if you'd not... | https://nextjs.org/docs/app/api-reference/next-cli |
73171eae48e7-6 | Terminal
Operating System:
Platform: linux
Arch: x64
Version: #22-Ubuntu SMP Fri Nov 5 13:21:36 UTC 2021
Binaries:
Node: 16.13.0
npm: 8.1.0
Yarn: 1.22.17
pnpm: 6.24.2
Relevant packages:
next: 12.0.8
react: 17.0.2
react-dom: 17.0.2
This informat... | https://nextjs.org/docs/app/api-reference/next-cli |
6d2e46b338f7-0 | create-next-app
The easiest way to get started with Next.js is by using create-next-app. This CLI tool enables you to quickly start building a new Next.js application, with everything set up for you.
You can create a new app using the default Next.js template, or by using one of the official Next.js examples.
Interacti... | https://nextjs.org/docs/app/api-reference/create-next-app |
6d2e46b338f7-1 | Would you like to use App Router? (recommended) No / Yes
Would you like to customize the default import alias? No / Yes
Once you've answered the prompts, a new project will be created with the correct configuration depending on your answers.
Non-interactive
You can also pass command line arguments to set up a new pro... | https://nextjs.org/docs/app/api-reference/create-next-app |
6d2e46b338f7-2 | --tailwind
Initialize with Tailwind CSS config. (default)
--eslint
Initialize with ESLint config.
--app
Initialize as an App Router project.
--src-dir
Initialize inside a `src/` directory.
--import-alias <alias-to-configure>
Specify import alias to use (default "@/*").
... | https://nextjs.org/docs/app/api-reference/create-next-app |
6d2e46b338f7-3 | -e, --example [name]|[github-url]
An example to bootstrap the app with. You can use an example name
from the official Next.js repo or a public GitHub URL. The URL can use
any branch and/or subdirectory
--example-path <path-to-example>
In a rare case, your GitHub URL might contain a branch name w... | https://nextjs.org/docs/app/api-reference/create-next-app |
6d2e46b338f7-4 | -h, --help output usage information
Why use Create Next App?
create-next-app allows you to create a new Next.js app within seconds. It is officially maintained by the creators of Next.js, and includes a number of benefits:
Interactive Experience: Running npx create-next-app@latest (with no arg... | https://nextjs.org/docs/app/api-reference/create-next-app |
6d2e46b338f7-5 | Tested: The package is part of the Next.js monorepo and tested using the same integration test suite as Next.js itself, ensuring it works as expected with every release. | https://nextjs.org/docs/app/api-reference/create-next-app |
11f83af27076-0 | Edge Runtime
The Next.js Edge Runtime is based on standard Web APIs, it supports the following APIs:
Network APIs
APIDescriptionBlobRepresents a blobfetchFetches a resourceFetchEventRepresents a fetch eventFileRepresents a fileFormDataRepresents form dataHeadersRepresents HTTP headersRequestRepresents an HTTP requestRe... | https://nextjs.org/docs/app/api-reference/edge |
11f83af27076-1 | Stream APIs
APIDescriptionReadableStreamRepresents a readable streamReadableStreamBYOBReaderRepresents a reader of a ReadableStreamReadableStreamDefaultReaderRepresents a reader of a ReadableStreamTransformStreamRepresents a transform streamWritableStreamRepresents a writable streamWritableStreamDefaultWriterRepresents... | https://nextjs.org/docs/app/api-reference/edge |
11f83af27076-2 | APIDescriptionAbortControllerAllows you to abort one or more DOM requests as and when desiredArrayRepresents an array of valuesArrayBufferRepresents a generic, fixed-length raw binary data bufferAtomicsProvides atomic operations as static methodsBigIntRepresents a whole number with arbitrary precisionBigInt64ArrayRepre... | https://nextjs.org/docs/app/api-reference/edge |
11f83af27076-3 | Identifier (URI) previously created by encodeURI or by a similar routinedecodeURIComponentDecodes a Uniform Resource Identifier (URI) component previously created by encodeURIComponent or by a similar routineDOMExceptionRepresents an error that occurs in the DOMencodeURIEncodes a Uniform Resource Identifier (URI) by re... | https://nextjs.org/docs/app/api-reference/edge |
11f83af27076-4 | typed array of 64-bit floating point numbersFunctionRepresents a functionInfinityRepresents the mathematical Infinity valueInt8ArrayRepresents a typed array of 8-bit signed integersInt16ArrayRepresents a typed array of 16-bit signed integersInt32ArrayRepresents a typed array of 32-bit signed integersIntlProvides access... | https://nextjs.org/docs/app/api-reference/edge |
11f83af27076-5 | the eventual completion (or failure) of an asynchronous operation, and its resulting valueProxyRepresents an object that is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc)queueMicrotaskQueues a microtask to be executedRangeErrorRepresen... | https://nextjs.org/docs/app/api-reference/edge |
11f83af27076-6 | a deep copy of a valueSymbolRepresents a unique and immutable data type that is used as the key of an object propertySyntaxErrorRepresents an error when trying to interpret syntactically invalid codeTypeErrorRepresents an error when a value is not of the expected typeUint8ArrayRepresents a typed array of 8-bit unsigned... | https://nextjs.org/docs/app/api-reference/edge |
11f83af27076-7 | Next.js Specific Polyfills
AsyncLocalStorage
Environment Variables
You can use process.env to access Environment Variables for both next dev and next build.
Unsupported APIs
The Edge Runtime has some restrictions including:
Native Node.js APIs are not supported. For example, you can't read or write to the filesystem.
n... | https://nextjs.org/docs/app/api-reference/edge |
11f83af27076-8 | In rare cases, your code could contain (or import) some dynamic code evaluation statements which can not be reached at runtime and which can not be removed by treeshaking.
You can relax the check to allow specific files with your Middleware or Edge API Route exported configuration:
export const config = {
runtime: '... | https://nextjs.org/docs/app/api-reference/edge |
815751b8a477-0 | fetchNext.js extends the native Web fetch() API to allow each request on the server to set its own persistent caching semantics.
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 ... | https://nextjs.org/docs/app/api-reference/functions/fetch |
815751b8a477-1 | // This request should be cached with a lifetime of 10 seconds.
// Similar to `getStaticProps` with the `revalidate` option.
const revalidatedData = await fetch(`https://...`, {
next: { revalidate: 10 },
})
return <div>...</div>
}
fetch(url, options)
Since Next.js extends the Web fetch() API, you can use ... | https://nextjs.org/docs/app/api-reference/functions/fetch |
815751b8a477-2 | force-cache (default) - Next.js looks for a matching request in its HTTP cache.
If there is a match and it is fresh, it will be returned from the cache.
If there is no match or a stale match, Next.js will fetch the resource from the remote server and update the cache with the downloaded resource.
no-store - Next.js fet... | https://nextjs.org/docs/app/api-reference/functions/fetch |
815751b8a477-3 | 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 ... | https://nextjs.org/docs/app/api-reference/functions/fetch |
815751b8a477-4 | Conflicting options such as { revalidate: 0, cache: 'force-cache' } or { revalidate: 10, cache: 'no-store' } will cause an error.
Version History
VersionChangesv13.0.0fetch introduced. | https://nextjs.org/docs/app/api-reference/functions/fetch |
30e47af5f7d2-0 | redirectThe redirect function allows you to redirect the user to another URL. redirect can be used in Server Components, Client Components, Route Handlers, and Server Actions.
If you need to redirect to a 404, use the notFound function instead.
Parameters
The redirect function accepts two arguments:
redirect(path, typ... | https://nextjs.org/docs/app/api-reference/functions/redirect |
30e47af5f7d2-1 | Returns
redirect does not return any value.
Example
Invoking the redirect() function throws a NEXT_REDIRECT error and terminates rendering of the route segment in which it was thrown.
app/team/[id]/page.js import { redirect } from 'next/navigation'
async function fetchTeam(id) {
const res = await fetch('https://...... | https://nextjs.org/docs/app/api-reference/functions/redirect |
8e6c7648aeac-0 | generateStaticParamsThe generateStaticParams function can be used in combination with dynamic route segments to statically generate routes at build time instead of on-demand at request time.
app/blog/[slug]/page.js // Return a list of `params` to populate the [slug] dynamic segment
export async function generateStaticP... | https://nextjs.org/docs/app/api-reference/functions/generate-static-params |
8e6c7648aeac-1 | During next dev, generateStaticParams will be called when you navigate to a route.
During next build, generateStaticParams runs before the corresponding Layouts or Pages are generated.
During revalidation (ISR), generateStaticParams will not be called again.
generateStaticParams replaces the getStaticPaths function in ... | https://nextjs.org/docs/app/api-reference/functions/generate-static-params |
8e6c7648aeac-2 | Each property in the object is a dynamic segment to be filled in for the route.
The properties name is the segment's name, and the properties value is what that segment should be filled in with.
Example RoutegenerateStaticParams Return Type/product/[id]{ id: string }[]/products/[category]/[product]{ category: string, p... | https://nextjs.org/docs/app/api-reference/functions/generate-static-params |
8e6c7648aeac-3 | // - /product/2
// - /product/3
export default function Page({ params }: { params: { id: string } }) {
const { id } = params
// ...
}
Multiple Dynamic Segments
app/products/[category]/[product]/page.tsx export function generateStaticParams() {
return [
{ category: 'a', product: '1' },
{ category: 'b', pro... | https://nextjs.org/docs/app/api-reference/functions/generate-static-params |
8e6c7648aeac-4 | params,
}: {
params: { category: string; product: string }
}) {
const { category, product } = params
// ...
}
Catch-all Dynamic Segment
app/product/[...slug]/page.tsx export function generateStaticParams() {
return [{ slug: ['a', '1'] }, { slug: ['b', '2'] }, { slug: ['c', '3'] }]
}
// Three versions of this ... | https://nextjs.org/docs/app/api-reference/functions/generate-static-params |
8e6c7648aeac-5 | // ...
}
Examples
Multiple Dynamic Segments in a Route
You can generate params for dynamic segments above the current layout or page, but not below. For example, given the app/products/[category]/[product] route:
app/products/[category]/[product]/page.js can generate params for both [category] and [product].
app/produc... | https://nextjs.org/docs/app/api-reference/functions/generate-static-params |
8e6c7648aeac-6 | return products.map((product) => ({
category: product.category.slug,
product: product.id,
}))
}
export default function Page({
params,
}: {
params: { category: string; product: string }
}) {
// ...
}
Generate params from the top down
Generate the parent segments first and use the result to generate th... | https://nextjs.org/docs/app/api-reference/functions/generate-static-params |
8e6c7648aeac-7 | // ...
}
A child route segment's generateStaticParams function is executed once for each segment a parent generateStaticParams generates.
The child generateStaticParams function can use the params returned from the parent generateStaticParams function to dynamically generate its own segments.
app/products/[category]/[p... | https://nextjs.org/docs/app/api-reference/functions/generate-static-params |
8e6c7648aeac-8 | }))
}
export default function Page({
params,
}: {
params: { category: string; product: string }
}) {
// ...
}
Good to know: When rendering a route, Next.js will automatically deduplicate fetch requests for the same data across generateMetadata, generateStaticParams, Layouts, Pages, and Server Components. React ... | https://nextjs.org/docs/app/api-reference/functions/generate-static-params |
0354bd0d3636-0 | revalidatePathrevalidatePath allows you to revalidate data associated with a specific path. This is useful for scenarios where you want to update your cached data without waiting for a revalidation period to expire.
app/api/revalidate/route.ts import { NextRequest, NextResponse } from 'next/server'
import { revalidateP... | https://nextjs.org/docs/app/api-reference/functions/revalidatePath |
0354bd0d3636-1 | Good to know:
revalidatePath is available in both Node.js and Edge runtimes.
revalidatePath will revalidate all segments under a dynamic route segment. For example, if you have a dynamic segment /product/[id] and you call revalidatePath('/product/[id]'), then all segments under /product/[id] will be revalidated as requ... | https://nextjs.org/docs/app/api-reference/functions/revalidatePath |
0354bd0d3636-2 | Returns
revalidatePath does not return any value.
Examples
Node.js Runtime
app/api/revalidate/route.ts import { NextRequest, NextResponse } from 'next/server'
import { revalidatePath } from 'next/cache'
export async function GET(request: NextRequest) {
const path = request.nextUrl.searchParams.get('path') || '/'
... | https://nextjs.org/docs/app/api-reference/functions/revalidatePath |
0354bd0d3636-3 | revalidatePath(path)
return NextResponse.json({ revalidated: true, now: Date.now() })
} | https://nextjs.org/docs/app/api-reference/functions/revalidatePath |
1b31311bf4d1-0 | useRouterThe useRouter hook allows you to programmatically change routes inside Client Components.
Recommendation: Use the <Link> component for navigation unless you have a specific requirement for using useRouter.
app/example-client-component.tsx 'use client'
import { useRouter } from 'next/navigation'
export defa... | https://nextjs.org/docs/app/api-reference/functions/use-router |
1b31311bf4d1-1 | router.refresh(): Refresh the current route. Making a new request to the server, re-fetching data requests, and re-rendering Server Components. The client will merge the updated React Server Component payload without losing unaffected client-side React (e.g. useState) or browser state (e.g. scroll position).
router.pre... | https://nextjs.org/docs/app/api-reference/functions/use-router |
1b31311bf4d1-2 | next/link automatically prefetch routes as they become visible in the viewport.
refresh() could re-produce the same result if fetch requests are cached. Other dynamic functions like cookies and headers could also change the response.
Migrating from the pages directory:
The new useRouter hook should be imported from nex... | https://nextjs.org/docs/app/api-reference/functions/use-router |
1b31311bf4d1-3 | export function NavigationEvents() {
const pathname = usePathname()
const searchParams = useSearchParams()
useEffect(() => {
const url = `${pathname}?${searchParams}`
console.log(url)
// You can now use the current URL
// ...
}, [pathname, searchParams])
return null
}
Which can be imported... | https://nextjs.org/docs/app/api-reference/functions/use-router |
1b31311bf4d1-4 | </body>
</html>
)
}
Good to know: <NavigationEvents> is wrapped in a Suspense boundary becauseuseSearchParams() causes client-side rendering up to the closest Suspense boundary during static rendering. Learn more.
VersionChangesv13.0.0useRouter from next/navigation introduced. | https://nextjs.org/docs/app/api-reference/functions/use-router |
eee8adb3e46c-0 | useSelectedLayoutSegmentuseSelectedLayoutSegment is a Client Component hook that lets you read the active route segment one level below the Layout it is called from.
It is useful for navigation UI, such as tabs inside a parent layout that change style depending on the active child segment.
app/example-client-component.... | https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment |
eee8adb3e46c-1 | Parameters
const segment = useSelectedLayoutSegment()
useSelectedLayoutSegment does not take any parameters.
Returns
useSelectedLayoutSegment returns a string of the active segment or null if one doesn't exist.
For example, given the Layouts and URLs below, the returned segment would be:
LayoutVisited URLReturned Segm... | https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment |
eee8adb3e46c-2 | import { useSelectedLayoutSegment } from 'next/navigation'
// This *client* component will be imported into a blog layout
export default function BlogNavLink({
slug,
children,
}: {
slug: string
children: React.ReactNode
}) {
// Navigating to `/blog/hello-world` will return 'hello-world'
// for the selecte... | https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment |
eee8adb3e46c-3 | app/blog/layout.tsx // Import the Client Component into a parent Layout (Server Component)
import { BlogNavLink } from './blog-nav-link'
import getFeaturedPosts from './get-featured-posts'
export default async function Layout({
children,
}: {
children: React.ReactNode
}) {
const featuredPosts = await getFeature... | https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment |
be66a2948eba-0 | useParamsuseParams is a Client Component hook that lets you read a route's dynamic params filled in by the current URL.
app/example-client-component.tsx 'use client'
import { useParams } from 'next/navigation'
export default function ExampleClientComponent() {
const params = useParams()
// Route -> /shop/[tag... | https://nextjs.org/docs/app/api-reference/functions/use-params |
be66a2948eba-1 | Each property in the object is an active dynamic segment.
The properties name is the segment's name, and the properties value is what the segment is filled in with.
The properties value will either be a string or array of string's depending on the type of dynamic segment.
If the route contains no dynamic parameters, us... | https://nextjs.org/docs/app/api-reference/functions/use-params |
3de65793be96-0 | usePathnameusePathname is a Client Component hook that lets you read the current URL's pathname.
app/example-client-component.tsx 'use client'
import { usePathname } from 'next/navigation'
export default function ExampleClientComponent() {
const pathname = usePathname()
return <p>Current pathname: {pathname}</p... | https://nextjs.org/docs/app/api-reference/functions/use-pathname |
3de65793be96-1 | Good to know:
Reading the current URL from a Server Component is not supported. This design is intentional to support layout state being preserved across page navigations.
Compatibility mode:
usePathname can return null when a fallback route is being rendered or when a pages directory page has been automatically static... | https://nextjs.org/docs/app/api-reference/functions/use-pathname |
3de65793be96-2 | import { usePathname, useSearchParams } from 'next/navigation'
function ExampleClientComponent() {
const pathname = usePathname()
const searchParams = useSearchParams()
useEffect(() => {
// Do something here...
}, [pathname, searchParams])
}
VersionChangesv13.0.0usePathname introduced. | https://nextjs.org/docs/app/api-reference/functions/use-pathname |
0c3f3f878710-0 | generateImageMetadataYou can use generateImageMetadata to generate different versions of one image or return multiple images for one route segment. This is useful for when you want to avoid hard-coding metadata values, such as for icons.
Parameters
generateImageMetadata function accepts the following parameters:
params... | https://nextjs.org/docs/app/api-reference/functions/generate-image-metadata |
0c3f3f878710-1 | Returns
The generateImageMetadata function should return an array of objects containing the image's metadata such as alt and size. In addition, each item must include an id value will be passed to the props of the image generating function.
Image Metadata ObjectTypeidstring (required)altstringsize{ width: number; heigh... | https://nextjs.org/docs/app/api-reference/functions/generate-image-metadata |
0c3f3f878710-2 | return new ImageResponse(
(
<div
style={{
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: 88,
background: '#000',
color: '#fafafa',
}}
>
Icon ... | https://nextjs.org/docs/app/api-reference/functions/generate-image-metadata |
0c3f3f878710-3 | params,
}: {
params: { id: string }
}) {
const images = await getOGImages(params.id)
return images.map((image, idx) => ({
id: idx,
size: { width: 1200, height: 600 },
alt: image.text,
contentType: 'image/png',
}))
}
export default async function Image({
params,
id,
}: {
params: { id: s... | https://nextjs.org/docs/app/api-reference/functions/generate-image-metadata |
0c3f3f878710-4 | }
}
>
{text}
</div>
)
)
}
Version History
VersionChangesv13.3.0generateImageMetadata introduced. | https://nextjs.org/docs/app/api-reference/functions/generate-image-metadata |
d1b750946c0d-0 | draftModeThe draftMode function allows you to detect Draft Mode inside a Server Component.
app/page.js import { draftMode } from 'next/headers'
export default function Page() {
const { isEnabled } = draftMode()
return (
<main>
<h1>My Blog Post</h1>
<p>Draft Mode is currently {isEnabled ? 'Enabled'... | https://nextjs.org/docs/app/api-reference/functions/draft-mode |
d43f4d9b28b9-0 | useSearchParamsuseSearchParams is a Client Component hook that lets you read the current URL's query string.
useSearchParams returns a read-only version of the URLSearchParams interface.
app/dashboard/search-bar.tsx 'use client'
import { useSearchParams } from 'next/navigation'
export default function SearchBar() {... | https://nextjs.org/docs/app/api-reference/functions/use-search-params |
d43f4d9b28b9-1 | URLSearchParams.get(): Returns the first value associated with the search parameter. For example:
URLsearchParams.get("a")/dashboard?a=1'1'/dashboard?a=''/dashboard?b=3null/dashboard?a=1&a=2'1' - use getAll() to get all values
URLSearchParams.has(): Returns a boolean value indicating if the given parameter exists. For ... | https://nextjs.org/docs/app/api-reference/functions/use-search-params |
d43f4d9b28b9-2 | If an application includes the /pages directory, useSearchParams will return ReadonlyURLSearchParams | null. The null value is for compatibility during migration since search params cannot be known during pre-rendering of a page that doesn't use getServerSideProps
Behavior
Static Rendering
If a route is statically rend... | https://nextjs.org/docs/app/api-reference/functions/use-search-params |
d43f4d9b28b9-3 | const search = searchParams.get('search')
// This will not be logged on the server when using static rendering
console.log(search)
return <>Search: {search}</>
}
app/dashboard/page.tsx import { Suspense } from 'react'
import SearchBar from './search-bar'
// This component passed as a fallback to the Suspens... | https://nextjs.org/docs/app/api-reference/functions/use-search-params |
d43f4d9b28b9-4 | <SearchBar />
</Suspense>
</nav>
<h1>Dashboard</h1>
</>
)
}
Dynamic Rendering
If a route is dynamically rendered, useSearchParams will be available on the server during the initial server render of the Client Component.
Good to know: Setting the dynamic route segment config option to force-dyn... | https://nextjs.org/docs/app/api-reference/functions/use-search-params |
d43f4d9b28b9-5 | console.log(search)
return <>Search: {search}</>
}
app/dashboard/page.tsx import SearchBar from './search-bar'
export const dynamic = 'force-dynamic'
export default function Page() {
return (
<>
<nav>
<SearchBar />
</nav>
<h1>Dashboard</h1>
</>
)
}
Server Components
Pages
T... | https://nextjs.org/docs/app/api-reference/functions/use-search-params |
d43f4d9b28b9-6 | Instead, use the Page searchParams prop or the useSearchParams hook in a Client Component, which is re-rendered on the client with the latest searchParams.
Examples
Updating searchParams
You can use useRouter or Link to set new searchParams. After a navigation is performed, the current page.js will receive an updated s... | https://nextjs.org/docs/app/api-reference/functions/use-search-params |
d43f4d9b28b9-7 | return params.toString()
},
[searchParams]
)
return (
<>
<p>Sort By</p>
{/* using useRouter */}
<button
onClick={() => {
// <pathname>?sort=asc
router.push(pathname + '?' + createQueryString('sort', 'asc'))
}}
>
ASC
</button>
... | https://nextjs.org/docs/app/api-reference/functions/use-search-params |
d6a3f0d047bd-0 | headersThe headers function allows you to read the HTTP incoming request headers from a Server Component.
headers()
This API extends the Web Headers API. It is read-only, meaning you cannot set / delete the outgoing request headers.
app/page.tsx import { headers } from 'next/headers'
export default function Page() {
... | https://nextjs.org/docs/app/api-reference/functions/headers |
d6a3f0d047bd-1 | Headers.entries(): Returns an iterator allowing to go through all key/value pairs contained in this object.
Headers.forEach(): Executes a provided function once for each key/value pair in this Headers object.
Headers.get(): Returns a String sequence of all the values of a header within a Headers object with a given nam... | https://nextjs.org/docs/app/api-reference/functions/headers |
d6a3f0d047bd-2 | const authorization = headersInstance.get('authorization')
// Forward the authorization header
const res = await fetch('...', {
headers: { authorization },
})
return res.json()
}
export default async function UserPage() {
const user = await getUser()
return <h1>{user.name}</h1>
}
Version History
Versi... | https://nextjs.org/docs/app/api-reference/functions/headers |
3e10403f8547-0 | ImageResponseThe ImageResponse constructor allows you to generate dynamic images using JSX and CSS. This is useful for generating social media images such as Open Graph images, Twitter cards, and more.
The following options are available for ImageResponse:
import { ImageResponse } from 'next/server'
new ImageRespons... | https://nextjs.org/docs/app/api-reference/functions/image-response |
3e10403f8547-1 | status?: number = 200
statusText?: string
headers?: Record<string, string>
},
)
Supported CSS Properties
Please refer to Satori’s documentation for a list of supported HTML and CSS features.
Version History
VersionChangesv13.3.0ImageResponse can be imported from next/server.v13.0.0ImageResponse introduced via... | https://nextjs.org/docs/app/api-reference/functions/image-response |
bac454a098d7-0 | notFoundThe notFound function allows you to render the not-found file within a route segment as well as inject a <meta name="robots" content="noindex" /> tag.
notFound()
Invoking the notFound() function throws a NEXT_NOT_FOUND error and terminates rendering of the route segment in which it was thrown. Specifying a not-... | https://nextjs.org/docs/app/api-reference/functions/not-found |
bac454a098d7-1 | notFound()
}
// ...
}
Good to know: notFound() does not require you to use return notFound() due to using the TypeScript never type.
Version History
VersionChangesv13.0.0notFound introduced. | https://nextjs.org/docs/app/api-reference/functions/not-found |
196df85b10c4-0 | Metadata Object and generateMetadata OptionsThis page covers all Config-based Metadata options with generateMetadata and the static metadata object.
layout.tsx / page.tsx import { Metadata } from 'next'
// either Static metadata
export const metadata: Metadata = {
title: '...',
}
// or Dynamic metadata
export asy... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
196df85b10c4-1 | title: '...',
description: '...',
}
export default function Page() {}
See the Metadata Fields for a complete list of supported options.
generateMetadata function
Dynamic metadata depends on dynamic information, such as the current route parameters, external data, or metadata in parent segments, can be set by export... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
196df85b10c4-2 | // read route params
const id = params.id
// fetch data
const product = await fetch(`https://.../${id}`).then((res) => res.json())
// optionally access and extend (rather than replace) parent metadata
const previousImages = (await parent).openGraph?.images || []
return {
title: product.title,
... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
196df85b10c4-3 | RouteURLparamsapp/shop/[slug]/page.js/shop/1{ slug: '1' }app/shop/[tag]/[item]/page.js/shop/1/2{ tag: '1', item: '2' }app/shop/[...slug]/page.js/shop/1/2{ slug: ['1', '2'] }
searchParams - An object containing the current URL's search params. Examples:
URLsearchParams/shop?a=1{ a: '1' }/shop?a=1&b=2{ a: '1', b: '2' }/s... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
196df85b10c4-4 | generateMetadata should return a Metadata object containing one or more metadata fields.
Good to know:
If metadata doesn't depend on runtime information, it should be defined using the static metadata object rather than generateMetadata.
When rendering a route, Next.js will automatically deduplicate fetch requests for ... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
196df85b10c4-5 | }
<head> output <title>Next.js</title>
Template object
app/layout.tsx import { Metadata } from 'next'
export const metadata: Metadata = {
title: {
template: '...',
default: '...',
absolute: '...',
},
}
Default
title.default can be used to provide a fallback title to child route segments that don't def... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
196df85b10c4-6 | app/layout.tsx import { Metadata } from 'next'
export const metadata: Metadata = {
title: {
template: '%s | Acme',
default: 'Acme', // a default is required when creating a template
},
}
app/about/page.tsx import { Metadata } from 'next'
export const metadata: Metadata = {
title: 'About',
}
// Outpu... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
196df85b10c4-7 | title.template has no effect if a route has not defined a title or title.default.
Absolute
title.absolute can be used to provide a title that ignores title.template set in parent segments.
app/layout.tsx import { Metadata } from 'next'
export const metadata: Metadata = {
title: {
template: '%s | Acme',
},
}
a... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
196df85b10c4-8 | title.absolute defines the default title for child segments. It ignores title.template from parent segments.
title.template defines a new title template for child segments.
page.js
If a page does not define its own title the closest parents resolved title will be used.
title (string) defines the routes title. It will a... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
196df85b10c4-9 | generator: 'Next.js',
applicationName: 'Next.js',
referrer: 'origin-when-cross-origin',
keywords: ['Next.js', 'React', 'JavaScript'],
authors: [{ name: 'Seb' }, { name: 'Josh', url: 'https://nextjs.org' }],
colorScheme: 'dark',
creator: 'Jiachi Liu',
publisher: 'Sebastian Markbåge',
formatDetection: {
... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
196df85b10c4-10 | <meta name="generator" content="Next.js" />
<meta name="keywords" content="Next.js,React,JavaScript" />
<meta name="referrer" content="origin-when-cross-origin" />
<meta name="color-scheme" content="dark" />
<meta name="creator" content="Jiachi Liu" />
<meta name="publisher" content="Sebastian Markbåge" />
<meta name="... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
196df85b10c4-11 | If not configured, metadataBase is automatically populated with a default value.
layout.js / page.js export const metadata = {
metadataBase: new URL('https://acme.com'),
alternates: {
canonical: '/',
languages: {
'en-US': '/en-US',
'de-DE': '/de-DE',
},
},
openGraph: {
images: '/og-i... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
196df85b10c4-12 | Good to know:
metadataBase is typically set in root app/layout.js to apply to URL-based metadata fields across all routes.
All URL-based metadata fields that require absolute URLs can be configured with a metadataBase option.
metadataBase can contain a subdomain e.g. https://app.acme.com or base path e.g. https://acme.... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
196df85b10c4-13 | Default value
If not configured, metadataBase has a default value
When VERCEL_URL is detected: https://${process.env.VERCEL_URL} otherwise it falls back to http://localhost:${process.env.PORT || 3000}.
When overriding the default, we recommend using environment variables to compute the URL. This allows configuring a UR... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
196df85b10c4-14 | metadataBase: new URL('https://acme.com'),
}
Any metadata fields that inherit the above metadataBase and set their own value will be resolved as follows:
metadata fieldResolved URL/https://acme.com./https://acme.compaymentshttps://acme.com/payments/paymentshttps://acme.com/payments./paymentshttps://acme.com/payments../... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
196df85b10c4-15 | width: 800,
height: 600,
},
{
url: 'https://nextjs.org/og-alt.png',
width: 1800,
height: 1600,
alt: 'My custom alt',
},
],
locale: 'en_US',
type: 'website',
},
}
<head> output <meta property="og:title" content="Next.js" />
<meta property="og:descri... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
196df85b10c4-16 | <meta property="og:image:width" content="800" />
<meta property="og:image:height" content="600" />
<meta property="og:image:url" content="https://nextjs.org/og-alt.png" />
<meta property="og:image:width" content="1800" />
<meta property="og:image:height" content="1600" />
<meta property="og:image:alt" content="My custo... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
196df85b10c4-17 | authors: ['Seb', 'Josh'],
},
}
<head> output <meta property="og:title" content="Next.js" />
<meta property="og:description" content="The React Framework for the Web" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2023-01-01T00:00:00.000Z" />
<meta property="article:a... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
196df85b10c4-18 | export const metadata: Metadata = {
robots: {
index: false,
follow: true,
nocache: true,
googleBot: {
index: true,
follow: false,
noimageindex: true,
'max-video-preview': -1,
'max-image-preview': 'large',
'max-snippet': -1,
},
},
}
<head> output <meta name="ro... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
196df85b10c4-19 | />
icons
Good to know: We recommend using the file-based Metadata API for icons where possible. Rather than having to sync the config export with actual files, the file-based API will automatically generate the correct metadata for you.
layout.js / page.js export const metadata = {
icons: {
icon: '/icon.png',
... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
196df85b10c4-20 | href="/apple-touch-icon-precomposed.png"
/>
layout.js / page.js export const metadata = {
icons: {
icon: [{ url: '/icon.png' }, new URL('/icon.png', 'https://example.com')],
shortcut: ['/shortcut-icon.png'],
apple: [
{ url: '/apple-icon.png' },
{ url: '/apple-icon-x3.png', sizes: '180x180', ty... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |
196df85b10c4-21 | <link rel="apple-touch-icon" href="/apple-icon.png" />
<link
rel="apple-touch-icon-precomposed"
href="/apple-touch-icon-precomposed.png"
/>
<link rel="icon" href="https://example.com/icon.png" />
<link
rel="apple-touch-icon"
href="/apple-icon-x3.png"
sizes="180x180"
type="image/png"
/>
Good to know: The msa... | https://nextjs.org/docs/app/api-reference/functions/generate-metadata |