{"id": "18165c3b636a-0", "text": "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.\nFor new applications, we recommend using the App Router. For existing applications, you can incrementally migrate to the App Router.\nThis section of the documentation includes the features available in the App Router:", "source": "https://nextjs.org/docs/app/index.html"} {"id": "73171eae48e7-0", "text": "Next.js CLI\nThe Next.js CLI allows you to start, build, and export your application.\nTo get a list of the available CLI commands, run the following command inside your project directory:\nTerminal npx next -h\n(npx comes with npm 5.2+ and higher)\nThe output should look like this:\nTerminal Usage\n $ next \n \nAvailable commands\n build, start, export, dev, lint, telemetry, info\n \nOptions\n --version, -v Version number\n --help, -h Displays this message\n \nFor more information run a command with the --help flag\n $ next build --help\nYou can pass any node arguments to next commands:\nTerminal NODE_OPTIONS='--throw-deprecation' next\nNODE_OPTIONS='-r esm' next\nNODE_OPTIONS='--inspect' next", "source": "https://nextjs.org/docs/app/api-reference/next-cli"} {"id": "73171eae48e7-1", "text": "NODE_OPTIONS='-r esm' next\nNODE_OPTIONS='--inspect' next\nGood to know: Running next without a command is the same as running next dev\nBuild\nnext build creates an optimized production build of your application. The output displays information about each route.\nSize \u2013 The number of assets downloaded when navigating to the page client-side. The size for each route only includes its dependencies.\nFirst Load JS \u2013 The number of assets downloaded when visiting the page from the server. The amount of JS shared by all is shown as a separate metric.\nBoth of these values are compressed with gzip. The first load is indicated by green, yellow, or red. Aim for green for performant applications.\nYou can enable production profiling for React with the --profile flag in next build. This requires Next.js 9.5:\nTerminal next build --profile\nAfter that, you can use the profiler in the same way as you would in development.", "source": "https://nextjs.org/docs/app/api-reference/next-cli"} {"id": "73171eae48e7-2", "text": "After that, you can use the profiler in the same way as you would in development.\nYou can enable more verbose build output with the --debug flag in next build. This requires Next.js 9.5.3:\nTerminal next build --debug\nWith this flag enabled additional build output like rewrites, redirects, and headers will be shown.\nDevelopment\nnext dev starts the application in development mode with hot-code reloading, error reporting, and more:\nThe application will start at http://localhost:3000 by default. The default port can be changed with -p, like so:\nTerminal npx next dev -p 4000\nOr using the PORT environment variable:\nTerminal PORT=4000 npx next dev\nGood to know: PORT cannot be set in .env as booting up the HTTP server happens before any other code is initialized.", "source": "https://nextjs.org/docs/app/api-reference/next-cli"} {"id": "73171eae48e7-3", "text": "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:\nTerminal npx next dev -H 192.168.1.2\nProduction\nnext start starts the application in production mode. The application should be compiled with next build first.\nThe application will start at http://localhost:3000 by default. The default port can be changed with -p, like so:\nTerminal npx next start -p 4000\nOr using the PORT environment variable:\nTerminal PORT=4000 npx next start\nGood to know:\n-PORT cannot be set in .env as booting up the HTTP server happens before any other code is initialized.\nnext start cannot be used with output: 'standalone' or output: 'export'.\nKeep Alive Timeout", "source": "https://nextjs.org/docs/app/api-reference/next-cli"} {"id": "73171eae48e7-4", "text": "Keep Alive Timeout\nWhen 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, Node.js will immediately terminate that connection without notifying the downstream proxy. This results in a proxy error whenever it attempts to reuse a connection that Node.js has already terminated.\nTo configure the timeout values for the production Next.js server, pass --keepAliveTimeout (in milliseconds) to next start, like so:\nTerminal npx next start --keepAliveTimeout 70000\nLint\nnext lint runs ESLint for all files in the pages/, app/, components/, lib/, and src/ directories. It also\nprovides a guided setup to install any required dependencies if ESLint is not already configured in\nyour application.", "source": "https://nextjs.org/docs/app/api-reference/next-cli"} {"id": "73171eae48e7-5", "text": "your application.\nIf you have other directories that you would like to lint, you can specify them using the --dir\nflag:\nTerminal next lint --dir utils\nTelemetry\nNext.js collects completely anonymous telemetry data about general usage.\nParticipation in this anonymous program is optional, and you may opt-out if you'd not like to share any information.\nTo learn more about Telemetry, please read this document.\nNext Info\nnext info prints relevant details about the current system which can be used to report Next.js bugs.\nThis information includes Operating System platform/arch/version, Binaries (Node.js, npm, Yarn, pnpm) and npm package versions (next, react, react-dom).\nRunning the following in your project's root directory:\nTerminal next info\nwill give you information like this example:\nTerminal \n Operating System:\n Platform: linux\n Arch: x64", "source": "https://nextjs.org/docs/app/api-reference/next-cli"} {"id": "73171eae48e7-6", "text": "Terminal \n Operating System:\n Platform: linux\n Arch: x64\n Version: #22-Ubuntu SMP Fri Nov 5 13:21:36 UTC 2021\n Binaries:\n Node: 16.13.0\n npm: 8.1.0\n Yarn: 1.22.17\n pnpm: 6.24.2\n Relevant packages:\n next: 12.0.8\n react: 17.0.2\n react-dom: 17.0.2\n \nThis information should then be pasted into GitHub Issues.", "source": "https://nextjs.org/docs/app/api-reference/next-cli"} {"id": "6d2e46b338f7-0", "text": "create-next-app\nThe 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.\nYou can create a new app using the default Next.js template, or by using one of the official Next.js examples.\nInteractive\nYou can create a new project interactively by running:\nTerminal npx create-next-app@latest\nTerminal yarn create next-app\nTerminal pnpm create next-app\nYou will then be asked the following prompts:\nTerminal What is your project named? my-app\nWould you like to use TypeScript? No / Yes\nWould you like to use ESLint? No / Yes\nWould you like to use Tailwind CSS? No / Yes\nWould you like to use `src/` directory? No / Yes\nWould you like to use App Router? (recommended) No / Yes", "source": "https://nextjs.org/docs/app/api-reference/create-next-app"} {"id": "6d2e46b338f7-1", "text": "Would you like to use App Router? (recommended) No / Yes\nWould you like to customize the default import alias? No / Yes\nOnce you've answered the prompts, a new project will be created with the correct configuration depending on your answers.\nNon-interactive\nYou can also pass command line arguments to set up a new project non-interactively.\nFurther, you can negate default options by prefixing them with --no- (e.g. --no-eslint).\nSee create-next-app --help:\nTerminal Usage: create-next-app [options]\n \nOptions:\n -V, --version output the version number\n --ts, --typescript\n \n Initialize as a TypeScript project. (default)\n \n --js, --javascript\n \n Initialize as a JavaScript project.\n \n --tailwind\n \n Initialize with Tailwind CSS config. (default)", "source": "https://nextjs.org/docs/app/api-reference/create-next-app"} {"id": "6d2e46b338f7-2", "text": "--tailwind\n \n Initialize with Tailwind CSS config. (default)\n \n --eslint\n \n Initialize with ESLint config.\n \n --app\n \n Initialize as an App Router project.\n \n --src-dir\n \n Initialize inside a `src/` directory.\n \n --import-alias \n \n Specify import alias to use (default \"@/*\").\n \n --use-npm\n \n Explicitly tell the CLI to bootstrap the app using npm\n \n --use-pnpm\n \n Explicitly tell the CLI to bootstrap the app using pnpm\n \n --use-yarn\n \n Explicitly tell the CLI to bootstrap the app using Yarn\n \n -e, --example [name]|[github-url]", "source": "https://nextjs.org/docs/app/api-reference/create-next-app"} {"id": "6d2e46b338f7-3", "text": "-e, --example [name]|[github-url]\n \n An example to bootstrap the app with. You can use an example name\n from the official Next.js repo or a public GitHub URL. The URL can use\n any branch and/or subdirectory\n \n --example-path \n \n In a rare case, your GitHub URL might contain a branch name with\n a slash (e.g. bug/fix-1) and the path to the example (e.g. foo/bar).\n In this case, you must specify the path to the example separately:\n --example-path foo/bar\n \n --reset-preferences\n \n Explicitly tell the CLI to reset any stored preferences\n \n -h, --help output usage information\nWhy use Create Next App?", "source": "https://nextjs.org/docs/app/api-reference/create-next-app"} {"id": "6d2e46b338f7-4", "text": "-h, --help output usage information\nWhy use Create Next App?\ncreate-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:\nInteractive Experience: Running npx create-next-app@latest (with no arguments) launches an interactive experience that guides you through setting up a project.\nZero Dependencies: Initializing a project is as quick as one second. Create Next App has zero dependencies.\nOffline Support: Create Next App will automatically detect if you're offline and bootstrap your project using your local package cache.\nSupport for Examples: Create Next App can bootstrap your application using an example from the Next.js examples collection (e.g. npx create-next-app --example api-routes) or any public GitHub repository.", "source": "https://nextjs.org/docs/app/api-reference/create-next-app"} {"id": "6d2e46b338f7-5", "text": "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.", "source": "https://nextjs.org/docs/app/api-reference/create-next-app"} {"id": "11f83af27076-0", "text": "Edge Runtime\nThe Next.js Edge Runtime is based on standard Web APIs, it supports the following APIs:\nNetwork APIs\nAPIDescriptionBlobRepresents a blobfetchFetches a resourceFetchEventRepresents a fetch eventFileRepresents a fileFormDataRepresents form dataHeadersRepresents HTTP headersRequestRepresents an HTTP requestResponseRepresents an HTTP responseURLSearchParamsRepresents URL search parametersWebSocketRepresents a websocket connection\nEncoding APIs\nAPIDescriptionatobDecodes a base-64 encoded stringbtoaEncodes a string in base-64TextDecoderDecodes a Uint8Array into a stringTextDecoderStreamChainable decoder for streamsTextEncoderEncodes a string into a Uint8ArrayTextEncoderStreamChainable encoder for streams\nStream APIs", "source": "https://nextjs.org/docs/app/api-reference/edge"} {"id": "11f83af27076-1", "text": "Stream APIs\nAPIDescriptionReadableStreamRepresents a readable streamReadableStreamBYOBReaderRepresents a reader of a ReadableStreamReadableStreamDefaultReaderRepresents a reader of a ReadableStreamTransformStreamRepresents a transform streamWritableStreamRepresents a writable streamWritableStreamDefaultWriterRepresents a writer of a WritableStream\nCrypto APIs\nAPIDescriptioncryptoProvides access to the cryptographic functionality of the platformCryptoKeyRepresents a cryptographic keySubtleCryptoProvides access to common cryptographic primitives, like hashing, signing, encryption or decryption\nWeb Standard APIs", "source": "https://nextjs.org/docs/app/api-reference/edge"} {"id": "11f83af27076-2", "text": "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 precisionBigInt64ArrayRepresents a typed array of 64-bit signed integersBigUint64ArrayRepresents a typed array of 64-bit unsigned integersBooleanRepresents a logical entity and can have two values: true and falseclearIntervalCancels a timed, repeating action which was previously established by a call to setInterval()clearTimeoutCancels a timed, repeating action which was previously established by a call to setTimeout()consoleProvides access to the browser's debugging consoleDataViewRepresents a generic view of an ArrayBufferDateRepresents a single moment in time in a platform-independent formatdecodeURIDecodes a Uniform Resource Identifier (URI) previously created by encodeURI or by a similar routinedecodeURIComponentDecodes", "source": "https://nextjs.org/docs/app/api-reference/edge"} {"id": "11f83af27076-3", "text": "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 replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the characterencodeURIComponentEncodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the characterErrorRepresents an error when trying to execute a statement or accessing a propertyEvalErrorRepresents an error that occurs regarding the global function eval()Float32ArrayRepresents a typed array of 32-bit floating point numbersFloat64ArrayRepresents a typed array of 64-bit floating point numbersFunctionRepresents a functionInfinityRepresents the mathematical Infinity", "source": "https://nextjs.org/docs/app/api-reference/edge"} {"id": "11f83af27076-4", "text": "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 to internationalization and localization functionalityisFiniteDetermines whether a value is a finite numberisNaNDetermines whether a value is NaN or notJSONProvides functionality to convert JavaScript values to and from the JSON formatMapRepresents a collection of values, where each value may occur only onceMathProvides access to mathematical functions and constantsNumberRepresents a numeric valueObjectRepresents the object that is the base of all JavaScript objectsparseFloatParses a string argument and returns a floating point numberparseIntParses a string argument and returns an integer of the specified radixPromiseRepresents the eventual completion (or failure) of an asynchronous operation, and its resulting valueProxyRepresents", "source": "https://nextjs.org/docs/app/api-reference/edge"} {"id": "11f83af27076-5", "text": "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 executedRangeErrorRepresents an error when a value is not in the set or range of allowed valuesReferenceErrorRepresents an error when a non-existent variable is referencedReflectProvides methods for interceptable JavaScript operationsRegExpRepresents a regular expression, allowing you to match combinations of charactersSetRepresents a collection of values, where each value may occur only oncesetIntervalRepeatedly calls a function, with a fixed time delay between each callsetTimeoutCalls a function or evaluates an expression after a specified number of millisecondsSharedArrayBufferRepresents a generic, fixed-length raw binary data bufferStringRepresents a sequence of charactersstructuredCloneCreates a deep copy of a valueSymbolRepresents a unique and immutable data type that is used", "source": "https://nextjs.org/docs/app/api-reference/edge"} {"id": "11f83af27076-6", "text": "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 integersUint8ClampedArrayRepresents a typed array of 8-bit unsigned integers clamped to 0-255Uint32ArrayRepresents a typed array of 32-bit unsigned integersURIErrorRepresents an error when a global URI handling function was used in a wrong wayURLRepresents an object providing static methods used for creating object URLsURLPatternRepresents a URL patternURLSearchParamsRepresents a collection of key/value pairsWeakMapRepresents a collection of key/value pairs in which the keys are weakly referencedWeakSetRepresents a collection of objects in which each object may occur only onceWebAssemblyProvides access to WebAssembly", "source": "https://nextjs.org/docs/app/api-reference/edge"} {"id": "11f83af27076-7", "text": "Next.js Specific Polyfills\nAsyncLocalStorage\nEnvironment Variables\nYou can use process.env to access Environment Variables for both next dev and next build.\nUnsupported APIs\nThe Edge Runtime has some restrictions including:\nNative Node.js APIs are not supported. For example, you can't read or write to the filesystem.\nnode_modules can be used, as long as they implement ES Modules and do not use native Node.js APIs.\nCalling require directly is not allowed. Use ES Modules instead.\nThe following JavaScript language features are disabled, and will not work:\nAPIDescriptionevalEvaluates JavaScript code represented as a stringnew Function(evalString)Creates a new function with the code provided as an argumentWebAssembly.compileCompiles a WebAssembly module from a buffer sourceWebAssembly.instantiateCompiles and instantiates a WebAssembly module from a buffer source", "source": "https://nextjs.org/docs/app/api-reference/edge"} {"id": "11f83af27076-8", "text": "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.\nYou can relax the check to allow specific files with your Middleware or Edge API Route exported configuration:\n export const config = {\n runtime: 'edge', // for Edge API Routes only\n unstable_allowDynamic: [\n // allows a single file\n '/lib/utilities.js',\n // use a glob to allow anything in the function-bind 3rd party module\n '/node_modules/function-bind/**',\n ],\n}\nunstable_allowDynamic is a glob, or an array of globs, ignoring dynamic code evaluation for specific files. The globs are relative to your application root folder.\nBe warned that if these statements are executed on the Edge, they will throw and cause a runtime error.", "source": "https://nextjs.org/docs/app/api-reference/edge"} {"id": "815751b8a477-0", "text": "fetchNext.js extends the native Web fetch() API to allow each request on the server to set its own persistent caching semantics.\nIn 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 HTTP cache.\nYou can call fetch with async and await directly within Server Components.\napp/page.tsx export default async function Page() {\n // This request should be cached until manually invalidated.\n // Similar to `getStaticProps`.\n // `force-cache` is the default and can be omitted.\n const staticData = await fetch(`https://...`, { cache: 'force-cache' })\n \n // This request should be refetched on every request.\n // Similar to `getServerSideProps`.\n const dynamicData = await fetch(`https://...`, { cache: 'no-store' })", "source": "https://nextjs.org/docs/app/api-reference/functions/fetch"} {"id": "815751b8a477-1", "text": "// This request should be cached with a lifetime of 10 seconds.\n // Similar to `getStaticProps` with the `revalidate` option.\n const revalidatedData = await fetch(`https://...`, {\n next: { revalidate: 10 },\n })\n \n return
...
\n}\nfetch(url, options)\nSince Next.js extends the Web fetch() API, you can use any of the native options available.\nFurther, Next.js polyfills fetch on both the client and the server, so you can use fetch in both Server and Client Components.\noptions.cache\nConfigure how the request should interact with Next.js HTTP cache.\n fetch(`https://...`, { cache: 'force-cache' | 'no-store' })\nforce-cache (default) - Next.js looks for a matching request in its HTTP cache.", "source": "https://nextjs.org/docs/app/api-reference/functions/fetch"} {"id": "815751b8a477-2", "text": "force-cache (default) - Next.js looks for a matching request in its HTTP cache.\nIf there is a match and it is fresh, it will be returned from the cache.\nIf 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.\nno-store - Next.js fetches the resource from the remote server on every request without looking in the cache, and it will not update the cache with the downloaded resource.\nGood to know:\nIf you don't provide a cache option, Next.js will default to force-cache, unless a dynamic function such as cookies() is used, in which case it will default to no-store.\nThe no-cache option behaves the same way as no-store in Next.js.\noptions.next.revalidate\n fetch(`https://...`, { next: { revalidate: false | 0 | number } })", "source": "https://nextjs.org/docs/app/api-reference/functions/fetch"} {"id": "815751b8a477-3", "text": "Set the cache lifetime of a resource (in seconds).\nfalse - Cache the resource indefinitely. Semantically equivalent to revalidate: Infinity. The HTTP cache may evict older resources over time.\n0 - Prevent the resource from being cached.\nnumber - (in seconds) Specify the resource should have a cache lifetime of at most n seconds.\nGood to know:\nIf an individual fetch() request sets a revalidate number lower than the default revalidate of a route, the whole route revalidation interval will be decreased.\nIf two fetch requests with the same URL in the same route have different revalidate values, the lower value will be used.\nAs a convenience, it is not necessary to set the cache option if revalidate is set to a number since 0 implies cache: 'no-store' and a positive value implies cache: 'force-cache'.", "source": "https://nextjs.org/docs/app/api-reference/functions/fetch"} {"id": "815751b8a477-4", "text": "Conflicting options such as { revalidate: 0, cache: 'force-cache' } or { revalidate: 10, cache: 'no-store' } will cause an error.\nVersion History\nVersionChangesv13.0.0fetch introduced.", "source": "https://nextjs.org/docs/app/api-reference/functions/fetch"} {"id": "30e47af5f7d2-0", "text": "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.\nIf you need to redirect to a 404, use the notFound function instead.\nParameters\nThe redirect function accepts two arguments:\n redirect(path, type)\nParameterTypeDescriptionpathstringThe URL to redirect to. Can be a relative or absolute path.type'replace' (default) or 'push' (default in Server Actions)The type of redirect to perform.\nBy default, redirect will use push (adding a new entry to the browser history stack) in Server Actions) and replace (replacing the current URL in the browser history stack) everywhere else. You can override this behavior by specifying the type parameter.\nThe type parameter has no effect when used in Server Components.\nReturns\nredirect does not return any value.\nExample", "source": "https://nextjs.org/docs/app/api-reference/functions/redirect"} {"id": "30e47af5f7d2-1", "text": "Returns\nredirect does not return any value.\nExample\nInvoking the redirect() function throws a NEXT_REDIRECT error and terminates rendering of the route segment in which it was thrown.\napp/team/[id]/page.js import { redirect } from 'next/navigation'\n \nasync function fetchTeam(id) {\n const res = await fetch('https://...')\n if (!res.ok) return undefined\n return res.json()\n}\n \nexport default async function Profile({ params }) {\n const team = await fetchTeam(params.id)\n if (!team) {\n redirect('/login')\n }\n \n // ...\n}\nGood to know: redirect does not require you to use return redirect() as it uses the TypeScript never type.\nVersionChangesv13.0.0redirect introduced.", "source": "https://nextjs.org/docs/app/api-reference/functions/redirect"} {"id": "8e6c7648aeac-0", "text": "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.\napp/blog/[slug]/page.js // Return a list of `params` to populate the [slug] dynamic segment\nexport async function generateStaticParams() {\n const posts = await fetch('https://.../posts').then((res) => res.json())\n \n return posts.map((post) => ({\n slug: post.slug,\n }))\n}\n \n// Multiple versions of this page will be statically generated\n// using the `params` returned by `generateStaticParams`\nexport default function Page({ params }) {\n const { slug } = params\n // ...\n}\nGood to know\nYou can use the dynamicParams segment config option to control what happens when a dynamic segment is visited that was not generated with generateStaticParams.", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-static-params"} {"id": "8e6c7648aeac-1", "text": "During next dev, generateStaticParams will be called when you navigate to a route.\nDuring next build, generateStaticParams runs before the corresponding Layouts or Pages are generated.\nDuring revalidation (ISR), generateStaticParams will not be called again.\ngenerateStaticParams replaces the getStaticPaths function in the Pages Router.\nParameters\noptions.params (optional)\nIf multiple dynamic segments in a route use generateStaticParams, the child generateStaticParams function is executed once for each set of params the parent generates.\nThe params object contains the populated params from the parent generateStaticParams, which can be used to generate the params in a child segment.\nReturns\ngenerateStaticParams should return an array of objects where each object represents the populated dynamic segments of a single route.\nEach property in the object is a dynamic segment to be filled in for the route.", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-static-params"} {"id": "8e6c7648aeac-2", "text": "Each property in the object is a dynamic segment to be filled in for the route.\nThe properties name is the segment's name, and the properties value is what that segment should be filled in with.\nExample RoutegenerateStaticParams Return Type/product/[id]{ id: string }[]/products/[category]/[product]{ category: string, product: string }[]/products/[...slug]{ slug: string[] }[]\nSingle Dynamic Segment\napp/product/[id]/page.tsx export function generateStaticParams() {\n return [{ id: '1' }, { id: '2' }, { id: '3' }]\n}\n \n// Three versions of this page will be statically generated\n// using the `params` returned by `generateStaticParams`\n// - /product/1\n// - /product/2\n// - /product/3", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-static-params"} {"id": "8e6c7648aeac-3", "text": "// - /product/2\n// - /product/3\nexport default function Page({ params }: { params: { id: string } }) {\n const { id } = params\n // ...\n}\nMultiple Dynamic Segments\napp/products/[category]/[product]/page.tsx export function generateStaticParams() {\n return [\n { category: 'a', product: '1' },\n { category: 'b', product: '2' },\n { category: 'c', product: '3' },\n ]\n}\n \n// Three versions of this page will be statically generated\n// using the `params` returned by `generateStaticParams`\n// - /products/a/1\n// - /products/b/2\n// - /products/c/3\nexport default function Page({\n params,\n}: {\n params: { category: string; product: string }", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-static-params"} {"id": "8e6c7648aeac-4", "text": "params,\n}: {\n params: { category: string; product: string }\n}) {\n const { category, product } = params\n // ...\n}\nCatch-all Dynamic Segment\napp/product/[...slug]/page.tsx export function generateStaticParams() {\n return [{ slug: ['a', '1'] }, { slug: ['b', '2'] }, { slug: ['c', '3'] }]\n}\n \n// Three versions of this page will be statically generated\n// using the `params` returned by `generateStaticParams`\n// - /product/a/1\n// - /product/b/2\n// - /product/c/3\nexport default function Page({ params }: { params: { slug: string[] } }) {\n const { slug } = params\n // ...\n}\nExamples\nMultiple Dynamic Segments in a Route", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-static-params"} {"id": "8e6c7648aeac-5", "text": "// ...\n}\nExamples\nMultiple Dynamic Segments in a Route\nYou can generate params for dynamic segments above the current layout or page, but not below. For example, given the app/products/[category]/[product] route:\napp/products/[category]/[product]/page.js can generate params for both [category] and [product].\napp/products/[category]/layout.js can only generate params for [category].\nThere are two approaches to generating params for a route with multiple dynamic segments:\nGenerate params from the bottom up\nGenerate multiple dynamic segments from the child route segment.\napp/products/[category]/[product]/page.tsx // Generate segments for both [category] and [product]\nexport async function generateStaticParams() {\n const products = await fetch('https://.../products').then((res) => res.json())\n \n return products.map((product) => ({\n category: product.category.slug,", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-static-params"} {"id": "8e6c7648aeac-6", "text": "return products.map((product) => ({\n category: product.category.slug,\n product: product.id,\n }))\n}\n \nexport default function Page({\n params,\n}: {\n params: { category: string; product: string }\n}) {\n // ...\n}\nGenerate params from the top down\nGenerate the parent segments first and use the result to generate the child segments.\napp/products/[category]/layout.tsx // Generate segments for [category]\nexport async function generateStaticParams() {\n const products = await fetch('https://.../products').then((res) => res.json())\n \n return products.map((product) => ({\n category: product.category.slug,\n }))\n}\n \nexport default function Layout({ params }: { params: { category: string } }) {\n // ...\n}", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-static-params"} {"id": "8e6c7648aeac-7", "text": "// ...\n}\nA child route segment's generateStaticParams function is executed once for each segment a parent generateStaticParams generates.\nThe child generateStaticParams function can use the params returned from the parent generateStaticParams function to dynamically generate its own segments.\napp/products/[category]/[product]/page.tsx // Generate segments for [product] using the `params` passed from\n// the parent segment's `generateStaticParams` function\nexport async function generateStaticParams({\n params: { category },\n}: {\n params: { category: string }\n}) {\n const products = await fetch(\n `https://.../products?category=${category}`\n ).then((res) => res.json())\n \n return products.map((product) => ({\n product: product.id,\n }))\n}\n \nexport default function Page({\n params,\n}: {", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-static-params"} {"id": "8e6c7648aeac-8", "text": "}))\n}\n \nexport default function Page({\n params,\n}: {\n params: { category: string; product: string }\n}) {\n // ...\n}\nGood 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 cache can be used if fetch is unavailable.\nVersion History\nVersionChangesv13.0.0generateStaticParams introduced.", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-static-params"} {"id": "0354bd0d3636-0", "text": "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.\napp/api/revalidate/route.ts import { NextRequest, NextResponse } from 'next/server'\nimport { revalidatePath } from 'next/cache'\n \nexport async function GET(request: NextRequest) {\n const path = request.nextUrl.searchParams.get('path') || '/'\n revalidatePath(path)\n return NextResponse.json({ revalidated: true, now: Date.now() })\n}\nGood to know:\nrevalidatePath is available in both Node.js and Edge runtimes.", "source": "https://nextjs.org/docs/app/api-reference/functions/revalidatePath"} {"id": "0354bd0d3636-1", "text": "Good to know:\nrevalidatePath is available in both Node.js and Edge runtimes.\nrevalidatePath 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 requested.\nrevalidatePath only invalidates the cache when the path is next visited. This means calling revalidatePath with a dynamic route segment will not immediately trigger many revalidations at once. The invalidation only happens when the path is next visited.\nParameters\n revalidatePath(path: string): void;\npath: A string representing the filesystem path associated with the data you want to revalidate. This is not the literal route segment (e.g. /product/123) but instead the path on the filesystem (e.g. /product/[id]).\nReturns", "source": "https://nextjs.org/docs/app/api-reference/functions/revalidatePath"} {"id": "0354bd0d3636-2", "text": "Returns\nrevalidatePath does not return any value.\nExamples\nNode.js Runtime\napp/api/revalidate/route.ts import { NextRequest, NextResponse } from 'next/server'\nimport { revalidatePath } from 'next/cache'\n \nexport async function GET(request: NextRequest) {\n const path = request.nextUrl.searchParams.get('path') || '/'\n revalidatePath(path)\n return NextResponse.json({ revalidated: true, now: Date.now() })\n}\nEdge Runtime\napp/api/revalidate/route.ts import { NextRequest, NextResponse } from 'next/server'\nimport { revalidatePath } from 'next/cache'\n \nexport const runtime = 'edge'\n \nexport async function GET(request: NextRequest) {\n const path = request.nextUrl.searchParams.get('path') || '/'\n revalidatePath(path)", "source": "https://nextjs.org/docs/app/api-reference/functions/revalidatePath"} {"id": "0354bd0d3636-3", "text": "revalidatePath(path)\n return NextResponse.json({ revalidated: true, now: Date.now() })\n}", "source": "https://nextjs.org/docs/app/api-reference/functions/revalidatePath"} {"id": "1b31311bf4d1-0", "text": "useRouterThe useRouter hook allows you to programmatically change routes inside Client Components.\nRecommendation: Use the component for navigation unless you have a specific requirement for using useRouter.\napp/example-client-component.tsx 'use client'\n \nimport { useRouter } from 'next/navigation'\n \nexport default function Page() {\n const router = useRouter()\n \n return (\n \n )\n}\nuseRouter()\nrouter.push(href: string): Perform a client-side navigation to the provided route. Adds a new entry into the browser\u2019s history stack.\nrouter.replace(href: string): Perform a client-side navigation to the provided route without adding a new entry into the browser\u2019s history stack.", "source": "https://nextjs.org/docs/app/api-reference/functions/use-router"} {"id": "1b31311bf4d1-1", "text": "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).\nrouter.prefetch(href: string): Prefetch the provided route for faster client-side transitions.\nrouter.back(): Navigate back to the previous route in the browser\u2019s history stack using soft navigation.\nrouter.forward(): Navigate forwards to the next page in the browser\u2019s history stack using soft navigation.\nGood to know:\nThe push() and replace() methods will perform a soft navigation if the new route has been prefetched, and either, doesn't include dynamic segments or has the same dynamic parameters as the current route.\nnext/link automatically prefetch routes as they become visible in the viewport.", "source": "https://nextjs.org/docs/app/api-reference/functions/use-router"} {"id": "1b31311bf4d1-2", "text": "next/link automatically prefetch routes as they become visible in the viewport.\nrefresh() could re-produce the same result if fetch requests are cached. Other dynamic functions like cookies and headers could also change the response.\nMigrating from the pages directory:\nThe new useRouter hook should be imported from next/navigation and not next/router\nThe pathname string has been removed and is replaced by usePathname()\nThe query object has been removed and is replaced by useSearchParams()\nrouter.events is not currently supported. See below.\nView the full migration guide.\nExamples\nRouter Events\nYou can listen for page changes by composing other Client Component hooks like usePathname and useSearchParams.\napp/components/navigation-events.js 'use client'\n \nimport { useEffect } from 'react'\nimport { usePathname, useSearchParams } from 'next/navigation'\n \nexport function NavigationEvents() {\n const pathname = usePathname()", "source": "https://nextjs.org/docs/app/api-reference/functions/use-router"} {"id": "1b31311bf4d1-3", "text": "export function NavigationEvents() {\n const pathname = usePathname()\n const searchParams = useSearchParams()\n \n useEffect(() => {\n const url = `${pathname}?${searchParams}`\n console.log(url)\n // You can now use the current URL\n // ...\n }, [pathname, searchParams])\n \n return null\n}\nWhich can be imported into a layout.\napp/layout.js import { Suspense } from 'react'\nimport { NavigationEvents } from './components/navigation-events'\n \nexport default function Layout({ children }) {\n return (\n \n \n {children}\n \n \n \n \n \n \n )\n}", "source": "https://nextjs.org/docs/app/api-reference/functions/use-router"} {"id": "1b31311bf4d1-4", "text": "\n \n )\n}\nGood to know: is wrapped in a Suspense boundary becauseuseSearchParams() causes client-side rendering up to the closest Suspense boundary during static rendering. Learn more.\nVersionChangesv13.0.0useRouter from next/navigation introduced.", "source": "https://nextjs.org/docs/app/api-reference/functions/use-router"} {"id": "eee8adb3e46c-0", "text": "useSelectedLayoutSegmentuseSelectedLayoutSegment is a Client Component hook that lets you read the active route segment one level below the Layout it is called from.\nIt is useful for navigation UI, such as tabs inside a parent layout that change style depending on the active child segment.\napp/example-client-component.tsx 'use client'\n \nimport { useSelectedLayoutSegment } from 'next/navigation'\n \nexport default function ExampleClientComponent() {\n const segment = useSelectedLayoutSegment()\n \n return

Active segment: {segment}

\n}\nGood to know:\nSince useSelectedLayoutSegment is a Client Component hook, and Layouts are Server Components by default, useSelectedLayoutSegment is usually called via a Client Component that is imported into a Layout.\nuseSelectedLayoutSegment only returns the segment one level down. To return all active segments, see useSelectedLayoutSegments\nParameters\n const segment = useSelectedLayoutSegment()", "source": "https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment"} {"id": "eee8adb3e46c-1", "text": "Parameters\n const segment = useSelectedLayoutSegment()\nuseSelectedLayoutSegment does not take any parameters.\nReturns\nuseSelectedLayoutSegment returns a string of the active segment or null if one doesn't exist.\nFor example, given the Layouts and URLs below, the returned segment would be:\nLayoutVisited URLReturned Segmentapp/layout.js/nullapp/layout.js/dashboard'dashboard'app/dashboard/layout.js/dashboardnullapp/dashboard/layout.js/dashboard/settings'settings'app/dashboard/layout.js/dashboard/analytics'analytics'app/dashboard/layout.js/dashboard/analytics/monthly'analytics'\nExamples\nCreating an active link component\nYou can use useSelectedLayoutSegment to create an active link component that changes style depending on the active segment. For example, a featured posts list in the sidebar of a blog:\napp/blog/blog-nav-link.tsx 'use client'\n \nimport Link from 'next/link'\nimport { useSelectedLayoutSegment } from 'next/navigation'", "source": "https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment"} {"id": "eee8adb3e46c-2", "text": "import { useSelectedLayoutSegment } from 'next/navigation'\n \n// This *client* component will be imported into a blog layout\nexport default function BlogNavLink({\n slug,\n children,\n}: {\n slug: string\n children: React.ReactNode\n}) {\n // Navigating to `/blog/hello-world` will return 'hello-world'\n // for the selected layout segment\n const segment = useSelectedLayoutSegment()\n const isActive = slug === segment\n \n return (\n \n {children}\n \n )\n}\napp/blog/layout.tsx // Import the Client Component into a parent Layout (Server Component)", "source": "https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment"} {"id": "eee8adb3e46c-3", "text": "app/blog/layout.tsx // Import the Client Component into a parent Layout (Server Component)\nimport { BlogNavLink } from './blog-nav-link'\nimport getFeaturedPosts from './get-featured-posts'\n \nexport default async function Layout({\n children,\n}: {\n children: React.ReactNode\n}) {\n const featuredPosts = await getFeaturedPosts()\n return (\n
\n {featuredPosts.map((post) => (\n
\n {post.title}\n
\n ))}\n
{children}
\n
\n )\n}\nVersion History\nVersionChangesv13.0.0useSelectedLayoutSegment introduced.", "source": "https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment"} {"id": "be66a2948eba-0", "text": "useParamsuseParams is a Client Component hook that lets you read a route's dynamic params filled in by the current URL.\napp/example-client-component.tsx 'use client'\n \nimport { useParams } from 'next/navigation'\n \nexport default function ExampleClientComponent() {\n const params = useParams()\n \n // Route -> /shop/[tag]/[item]\n // URL -> /shop/shoes/nike-air-max-97\n // `params` -> { tag: 'shoes', item: 'nike-air-max-97' }\n console.log(params)\n \n return <>\n}\nParameters\n const params = useParams()\nuseParams does not take any parameters.\nReturns\nuseParams returns an object containing the current route's filled in dynamic parameters.\nEach property in the object is an active dynamic segment.", "source": "https://nextjs.org/docs/app/api-reference/functions/use-params"} {"id": "be66a2948eba-1", "text": "Each property in the object is an active dynamic segment.\nThe properties name is the segment's name, and the properties value is what the segment is filled in with.\nThe properties value will either be a string or array of string's depending on the type of dynamic segment.\nIf the route contains no dynamic parameters, useParams returns an empty object.\nIf used in pages, useParams will return null.\nFor example:\nRouteURLuseParams()app/shop/page.js/shopnullapp/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'] }\nVersion History\nVersionChangesv13.3.0useParams introduced.", "source": "https://nextjs.org/docs/app/api-reference/functions/use-params"} {"id": "3de65793be96-0", "text": "usePathnameusePathname is a Client Component hook that lets you read the current URL's pathname.\napp/example-client-component.tsx 'use client'\n \nimport { usePathname } from 'next/navigation'\n \nexport default function ExampleClientComponent() {\n const pathname = usePathname()\n return

Current pathname: {pathname}

\n}\nusePathname intentionally requires using a Client Component. It's important to note Client Components are not a de-optimization. They are an integral part of the Server Components architecture.\nFor example, a Client Component with usePathname will be rendered into HTML on the initial page load. When navigating to a new route, this component does not need to be re-fetched. Instead, the component is downloaded once (in the client JavaScript bundle), and re-renders based on the current state.\nGood to know:", "source": "https://nextjs.org/docs/app/api-reference/functions/use-pathname"} {"id": "3de65793be96-1", "text": "Good to know:\nReading the current URL from a Server Component is not supported. This design is intentional to support layout state being preserved across page navigations.\nCompatibility mode:\nusePathname can return null when a fallback route is being rendered or when a pages directory page has been automatically statically optimized by Next.js and the router is not ready.\nNext.js will automatically update your types if it detects both an app and pages directory in your project.\nParameters\n const pathname = usePathname()\nusePathname does not take any parameters.\nReturns\nusePathname returns a string of the current URL's pathname. For example:\nURLReturned value/'/'/dashboard'/dashboard'/dashboard?v=2'/dashboard'/blog/hello-world'/blog/hello-world'\nExamples\nDo something in response to a route change\napp/example-client-component.tsx 'use client'\n \nimport { usePathname, useSearchParams } from 'next/navigation'", "source": "https://nextjs.org/docs/app/api-reference/functions/use-pathname"} {"id": "3de65793be96-2", "text": "import { usePathname, useSearchParams } from 'next/navigation'\n \nfunction ExampleClientComponent() {\n const pathname = usePathname()\n const searchParams = useSearchParams()\n useEffect(() => {\n // Do something here...\n }, [pathname, searchParams])\n}\nVersionChangesv13.0.0usePathname introduced.", "source": "https://nextjs.org/docs/app/api-reference/functions/use-pathname"} {"id": "0c3f3f878710-0", "text": "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.\nParameters\ngenerateImageMetadata function accepts the following parameters:\nparams (optional)\nAn object containing the dynamic route parameters object from the root segment down to the segment generateImageMetadata is called from.\nicon.tsx export function generateImageMetadata({\n params,\n}: {\n params: { slug: string }\n}) {\n // ...\n}\nRouteURLparamsapp/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'] }\nReturns", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-image-metadata"} {"id": "0c3f3f878710-1", "text": "Returns\nThe 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.\nImage Metadata ObjectTypeidstring (required)altstringsize{ width: number; height: number }contentTypestring\nicon.tsx import { ImageResponse } from 'next/server'\n \nexport function generateImageMetadata() {\n return [\n {\n contentType: 'image/png',\n size: { width: 48, height: 48 },\n id: 'small',\n },\n {\n contentType: 'image/png',\n size: { width: 72, height: 72 },\n id: 'medium',\n },\n ]\n}\n \nexport default function Icon({ id }: { id: string }) {\n return new ImageResponse(", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-image-metadata"} {"id": "0c3f3f878710-2", "text": "return new ImageResponse(\n (\n \n Icon {id}\n \n )\n )\n}\nExamples\nUsing external data\nThis example uses the params object and external data to generate multiple Open Graph images for a route segment.\napp/products/[id]/opengraph-image.tsx import { ImageResponse } from 'next/server'\nimport { getCaptionForImage, getOGImages } from '@/app/utils/images'\n \nexport async function generateImageMetadata({\n params,\n}: {\n params: { id: string }\n}) {", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-image-metadata"} {"id": "0c3f3f878710-3", "text": "params,\n}: {\n params: { id: string }\n}) {\n const images = await getOGImages(params.id)\n \n return images.map((image, idx) => ({\n id: idx,\n size: { width: 1200, height: 600 },\n alt: image.text,\n contentType: 'image/png',\n }))\n}\n \nexport default async function Image({\n params,\n id,\n}: {\n params: { id: string }\n id: number\n}) {\n const productId = params.id\n const imageId = id\n const text = await getCaptionForImage(productId, imageId)\n \n return new ImageResponse(\n (\n \n {text}\n ", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-image-metadata"} {"id": "0c3f3f878710-4", "text": "}\n }\n >\n {text}\n \n )\n )\n}\nVersion History\nVersionChangesv13.3.0generateImageMetadata introduced.", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-image-metadata"} {"id": "d1b750946c0d-0", "text": "draftModeThe draftMode function allows you to detect Draft Mode inside a Server Component.\napp/page.js import { draftMode } from 'next/headers'\n \nexport default function Page() {\n const { isEnabled } = draftMode()\n return (\n
\n

My Blog Post

\n

Draft Mode is currently {isEnabled ? 'Enabled' : 'Disabled'}

\n
\n )\n}\nVersion History\nVersionChangesv13.4.0draftMode introduced.", "source": "https://nextjs.org/docs/app/api-reference/functions/draft-mode"} {"id": "d43f4d9b28b9-0", "text": "useSearchParamsuseSearchParams is a Client Component hook that lets you read the current URL's query string.\nuseSearchParams returns a read-only version of the URLSearchParams interface.\napp/dashboard/search-bar.tsx 'use client'\n \nimport { useSearchParams } from 'next/navigation'\n \nexport default function SearchBar() {\n const searchParams = useSearchParams()\n \n const search = searchParams.get('search')\n \n // URL -> `/dashboard?search=my-project`\n // `search` -> 'my-project'\n return <>Search: {search}\n}\nParameters\n const searchParams = useSearchParams()\nuseSearchParams does not take any parameters.\nReturns\nuseSearchParams returns a read-only version of the URLSearchParams interface, which includes utility methods for reading the URL's query string:\nURLSearchParams.get(): Returns the first value associated with the search parameter. For example:", "source": "https://nextjs.org/docs/app/api-reference/functions/use-search-params"} {"id": "d43f4d9b28b9-1", "text": "URLSearchParams.get(): Returns the first value associated with the search parameter. For example:\nURLsearchParams.get(\"a\")/dashboard?a=1'1'/dashboard?a=''/dashboard?b=3null/dashboard?a=1&a=2'1' - use getAll() to get all values\nURLSearchParams.has(): Returns a boolean value indicating if the given parameter exists. For example:\nURLsearchParams.has(\"a\")/dashboard?a=1true/dashboard?b=3false\nLearn more about other read-only methods of URLSearchParams, including the getAll(), keys(), values(), entries(), forEach(), and toString().\nGood to know:\nuseSearchParams is a Client Component hook and is not supported in Server Components to prevent stale values during partial rendering.", "source": "https://nextjs.org/docs/app/api-reference/functions/use-search-params"} {"id": "d43f4d9b28b9-2", "text": "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\nBehavior\nStatic Rendering\nIf a route is statically rendered, calling useSearchParams() will cause the tree up to the closest Suspense boundary to be client-side rendered.\nThis allows a part of the page to be statically rendered while the dynamic part that uses searchParams is client-side rendered.\nYou can reduce the portion of the route that is client-side rendered by wrapping the component that uses useSearchParams in a Suspense boundary. For example:\napp/dashboard/search-bar.tsx 'use client'\n \nimport { useSearchParams } from 'next/navigation'\n \nexport default function SearchBar() {\n const searchParams = useSearchParams()\n \n const search = searchParams.get('search')", "source": "https://nextjs.org/docs/app/api-reference/functions/use-search-params"} {"id": "d43f4d9b28b9-3", "text": "const search = searchParams.get('search')\n \n // This will not be logged on the server when using static rendering\n console.log(search)\n \n return <>Search: {search}\n}\napp/dashboard/page.tsx import { Suspense } from 'react'\nimport SearchBar from './search-bar'\n \n// This component passed as a fallback to the Suspense boundary\n// will be rendered in place of the search bar in the initial HTML.\n// When the value is available during React hydration the fallback\n// will be replaced with the `` component.\nfunction SearchBarFallback() {\n return <>placeholder\n}\n \nexport default function Page() {\n return (\n <>\n ", "source": "https://nextjs.org/docs/app/api-reference/functions/use-search-params"} {"id": "d43f4d9b28b9-4", "text": "\n \n \n

Dashboard

\n \n )\n}\nDynamic Rendering\nIf a route is dynamically rendered, useSearchParams will be available on the server during the initial server render of the Client Component.\nGood to know: Setting the dynamic route segment config option to force-dynamic can be used to force dynamic rendering.\nFor example:\napp/dashboard/search-bar.tsx 'use client'\n \nimport { useSearchParams } from 'next/navigation'\n \nexport default function SearchBar() {\n const searchParams = useSearchParams()\n \n const search = searchParams.get('search')\n \n // This will be logged on the server during the initial render\n // and on the client on subsequent navigations.\n console.log(search)\n \n return <>Search: {search}\n}", "source": "https://nextjs.org/docs/app/api-reference/functions/use-search-params"} {"id": "d43f4d9b28b9-5", "text": "console.log(search)\n \n return <>Search: {search}\n}\napp/dashboard/page.tsx import SearchBar from './search-bar'\n \nexport const dynamic = 'force-dynamic'\n \nexport default function Page() {\n return (\n <>\n \n

Dashboard

\n \n )\n}\nServer Components\nPages\nTo access search params in Pages (Server Components), use the searchParams prop.\nLayouts\nUnlike Pages, Layouts (Server Components) do not receive the searchParams prop. This is because a shared layout is not re-rendered during navigation which could lead to stale searchParams between navigations. View detailed explanation.", "source": "https://nextjs.org/docs/app/api-reference/functions/use-search-params"} {"id": "d43f4d9b28b9-6", "text": "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.\nExamples\nUpdating searchParams\nYou can use useRouter or Link to set new searchParams. After a navigation is performed, the current page.js will receive an updated searchParams prop.\napp/example-client-component.tsx export default function ExampleClientComponent() {\n const router = useRouter()\n const pathname = usePathname()\n const searchParams = useSearchParams()!\n \n // Get a new searchParams string by merging the current\n // searchParams with a provided key/value pair\n const createQueryString = useCallback(\n (name: string, value: string) => {\n const params = new URLSearchParams(searchParams)\n params.set(name, value)\n \n return params.toString()\n },\n [searchParams]\n )", "source": "https://nextjs.org/docs/app/api-reference/functions/use-search-params"} {"id": "d43f4d9b28b9-7", "text": "return params.toString()\n },\n [searchParams]\n )\n \n return (\n <>\n

Sort By

\n \n {/* using useRouter */}\n {\n // ?sort=asc\n router.push(pathname + '?' + createQueryString('sort', 'asc'))\n }}\n >\n ASC\n \n \n {/* using */}\n ?sort=desc\n pathname + '?' + createQueryString('sort', 'desc')\n }\n >\n DESC\n \n \n )\n}\nVersion History\nVersionChangesv13.0.0useSearchParams introduced.", "source": "https://nextjs.org/docs/app/api-reference/functions/use-search-params"} {"id": "d6a3f0d047bd-0", "text": "headersThe headers function allows you to read the HTTP incoming request headers from a Server Component.\nheaders()\nThis API extends the Web Headers API. It is read-only, meaning you cannot set / delete the outgoing request headers.\napp/page.tsx import { headers } from 'next/headers'\n \nexport default function Page() {\n const headersList = headers()\n const referer = headersList.get('referer')\n \n return
Referer: {referer}
\n}\nGood to know:\nheaders() is a Dynamic Function whose returned values cannot be known ahead of time. Using it in a layout or page will opt a route into dynamic rendering at request time.\nAPI Reference\n const headersList = headers()\nParameters\nheaders does not take any parameters.\nReturns\nheaders returns a read-only Web Headers object.\nHeaders.entries(): Returns an iterator allowing to go through all key/value pairs contained in this object.", "source": "https://nextjs.org/docs/app/api-reference/functions/headers"} {"id": "d6a3f0d047bd-1", "text": "Headers.entries(): Returns an iterator allowing to go through all key/value pairs contained in this object.\nHeaders.forEach(): Executes a provided function once for each key/value pair in this Headers object.\nHeaders.get(): Returns a String sequence of all the values of a header within a Headers object with a given name.\nHeaders.has(): Returns a boolean stating whether a Headers object contains a certain header.\nHeaders.keys(): Returns an iterator allowing you to go through all keys of the key/value pairs contained in this object.\nHeaders.values(): Returns an iterator allowing you to go through all values of the key/value pairs contained in this object.\nExamples\nUsage with Data Fetching\nheaders() can be used in combination with Suspense for Data Fetching.\napp/page.js import { headers } from 'next/headers'\n \nasync function getUser() {\n const headersInstance = headers()\n const authorization = headersInstance.get('authorization')\n // Forward the authorization header", "source": "https://nextjs.org/docs/app/api-reference/functions/headers"} {"id": "d6a3f0d047bd-2", "text": "const authorization = headersInstance.get('authorization')\n // Forward the authorization header\n const res = await fetch('...', {\n headers: { authorization },\n })\n return res.json()\n}\n \nexport default async function UserPage() {\n const user = await getUser()\n return

{user.name}

\n}\nVersion History\nVersionChangesv13.0.0headers introduced.", "source": "https://nextjs.org/docs/app/api-reference/functions/headers"} {"id": "3e10403f8547-0", "text": "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.\nThe following options are available for ImageResponse:\n import { ImageResponse } from 'next/server'\n \nnew ImageResponse(\n element: ReactElement,\n options: {\n width?: number = 1200\n height?: number = 630\n emoji?: 'twemoji' | 'blobmoji' | 'noto' | 'openmoji' = 'twemoji',\n fonts?: {\n name: string,\n data: ArrayBuffer,\n weight: number,\n style: 'normal' | 'italic'\n }[]\n debug?: boolean = false\n \n // Options that will be passed to the HTTP response\n status?: number = 200\n statusText?: string", "source": "https://nextjs.org/docs/app/api-reference/functions/image-response"} {"id": "3e10403f8547-1", "text": "status?: number = 200\n statusText?: string\n headers?: Record\n },\n)\nSupported CSS Properties\nPlease refer to Satori\u2019s documentation for a list of supported HTML and CSS features.\nVersion History\nVersionChangesv13.3.0ImageResponse can be imported from next/server.v13.0.0ImageResponse introduced via @vercel/og package.", "source": "https://nextjs.org/docs/app/api-reference/functions/image-response"} {"id": "bac454a098d7-0", "text": "notFoundThe notFound function allows you to render the not-found file within a route segment as well as inject a tag.\nnotFound()\nInvoking the notFound() function throws a NEXT_NOT_FOUND error and terminates rendering of the route segment in which it was thrown. Specifying a not-found file allows you to gracefully handle such errors by rendering a Not Found UI within the segment.\napp/user/[id]/page.js import { notFound } from 'next/navigation'\n \nasync function fetchUser(id) {\n const res = await fetch('https://...')\n if (!res.ok) return undefined\n return res.json()\n}\n \nexport default async function Profile({ params }) {\n const user = await fetchUser(params.id)\n \n if (!user) {\n notFound()\n }\n \n // ...\n}", "source": "https://nextjs.org/docs/app/api-reference/functions/not-found"} {"id": "bac454a098d7-1", "text": "notFound()\n }\n \n // ...\n}\nGood to know: notFound() does not require you to use return notFound() due to using the TypeScript never type.\nVersion History\nVersionChangesv13.0.0notFound introduced.", "source": "https://nextjs.org/docs/app/api-reference/functions/not-found"} {"id": "196df85b10c4-0", "text": "Metadata Object and generateMetadata OptionsThis page covers all Config-based Metadata options with generateMetadata and the static metadata object.\nlayout.tsx / page.tsx import { Metadata } from 'next'\n \n// either Static metadata\nexport const metadata: Metadata = {\n title: '...',\n}\n \n// or Dynamic metadata\nexport async function generateMetadata({ params }) {\n return {\n title: '...',\n }\n}\nGood to know:\nThe metadata object and generateMetadata function exports are only supported in Server Components.\nYou cannot export both the metadata object and generateMetadata function from the same route segment.\nThe metadata object\nTo define static metadata, export a Metadata object from a layout.js or page.js file.\nlayout.tsx / page.tsx import { Metadata } from 'next'\n \nexport const metadata: Metadata = {\n title: '...',\n description: '...',\n}", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-1", "text": "title: '...',\n description: '...',\n}\n \nexport default function Page() {}\nSee the Metadata Fields for a complete list of supported options.\ngenerateMetadata function\nDynamic metadata depends on dynamic information, such as the current route parameters, external data, or metadata in parent segments, can be set by exporting a generateMetadata function that returns a Metadata object.\napp/products/[id]/page.tsx import { Metadata, ResolvingMetadata } from 'next'\n \ntype Props = {\n params: { id: string }\n searchParams: { [key: string]: string | string[] | undefined }\n}\n \nexport async function generateMetadata(\n { params, searchParams }: Props,\n parent: ResolvingMetadata\n): Promise {\n // read route params\n const id = params.id\n \n // fetch data", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-2", "text": "// read route params\n const id = params.id\n \n // fetch data\n const product = await fetch(`https://.../${id}`).then((res) => res.json())\n \n // optionally access and extend (rather than replace) parent metadata\n const previousImages = (await parent).openGraph?.images || []\n \n return {\n title: product.title,\n openGraph: {\n images: ['/some-specific-page-image.jpg', ...previousImages],\n },\n }\n}\n \nexport default function Page({ params, searchParams }: Props) {}\nParameters\ngenerateMetadata function accepts the following parameters:\nprops - An object containing the parameters of the current route:\nparams - An object containing the dynamic route parameters object from the root segment down to the segment generateMetadata is called from. Examples:", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-3", "text": "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'] }\nsearchParams - An object containing the current URL's search params. Examples:\nURLsearchParams/shop?a=1{ a: '1' }/shop?a=1&b=2{ a: '1', b: '2' }/shop?a=1&a=2{ a: ['1', '2'] }\nparent - A promise of the resolved metadata from parent route segments.\nReturns\ngenerateMetadata should return a Metadata object containing one or more metadata fields.\nGood to know:", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-4", "text": "generateMetadata should return a Metadata object containing one or more metadata fields.\nGood to know:\nIf metadata doesn't depend on runtime information, it should be defined using the static metadata object rather than generateMetadata.\nWhen rendering a route, Next.js will automatically deduplicate fetch requests for the same data across generateMetadata, generateStaticParams, Layouts, Pages, and Server Components. React cache can be used if fetch is unavailable.\nsearchParams are only available in page.js segments.\nThe redirect() and notFound() Next.js methods can also be used inside generateMetadata.\nMetadata Fields\ntitle\nThe title attribute is used to set the title of the document. It can be defined as a simple string or an optional template object.\nString\nlayout.js / page.js export const metadata = {\n title: 'Next.js',\n}\n output Next.js\nTemplate object", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-5", "text": "}\n output Next.js\nTemplate object\napp/layout.tsx import { Metadata } from 'next'\n \nexport const metadata: Metadata = {\n title: {\n template: '...',\n default: '...',\n absolute: '...',\n },\n}\nDefault\ntitle.default can be used to provide a fallback title to child route segments that don't define a title.\napp/layout.tsx import type { Metadata } from 'next'\n \nexport const metadata: Metadata = {\n title: {\n default: 'Acme',\n },\n}\napp/about/page.tsx import type { Metadata } from 'next'\n \nexport const metadata: Metadata = {}\n \n// Output: Acme\nTemplate\ntitle.template can be used to add a prefix or a suffix to titles defined in child route segments.", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-6", "text": "app/layout.tsx import { Metadata } from 'next'\n \nexport const metadata: Metadata = {\n title: {\n template: '%s | Acme',\n default: 'Acme', // a default is required when creating a template\n },\n}\napp/about/page.tsx import { Metadata } from 'next'\n \nexport const metadata: Metadata = {\n title: 'About',\n}\n \n// Output: About | Acme\nGood to know:\ntitle.template applies to child route segments and not the segment it's defined in. This means:\ntitle.default is required when you add a title.template.\ntitle.template defined in layout.js will not apply to a title defined in a page.js of the same route segment.\ntitle.template defined in page.js has no effect because a page is always the terminating segment (it doesn't have any children route segments).", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-7", "text": "title.template has no effect if a route has not defined a title or title.default.\nAbsolute\ntitle.absolute can be used to provide a title that ignores title.template set in parent segments.\napp/layout.tsx import { Metadata } from 'next'\n \nexport const metadata: Metadata = {\n title: {\n template: '%s | Acme',\n },\n}\napp/about/page.tsx import { Metadata } from 'next'\n \nexport const metadata: Metadata = {\n title: {\n absolute: 'About',\n },\n}\n \n// Output: About\nGood to know:\nlayout.js\ntitle (string) and title.default define the default title for child segments (that do not define their own title). It will augment title.template from the closest parent segment if it exists.\ntitle.absolute defines the default title for child segments. It ignores title.template from parent segments.", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-8", "text": "title.absolute defines the default title for child segments. It ignores title.template from parent segments.\ntitle.template defines a new title template for child segments.\npage.js\nIf a page does not define its own title the closest parents resolved title will be used.\ntitle (string) defines the routes title. It will augment title.template from the closest parent segment if it exists.\ntitle.absolute defines the route title. It ignores title.template from parent segments.\ntitle.template has no effect in page.js because a page is always the terminating segment of a route.\ndescription\nlayout.js / page.js export const metadata = {\n description: 'The React Framework for the Web',\n}\n output \nBasic Fields\nlayout.js / page.js export const metadata = {\n generator: 'Next.js',\n applicationName: 'Next.js',", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-9", "text": "generator: 'Next.js',\n applicationName: 'Next.js',\n referrer: 'origin-when-cross-origin',\n keywords: ['Next.js', 'React', 'JavaScript'],\n authors: [{ name: 'Seb' }, { name: 'Josh', url: 'https://nextjs.org' }],\n colorScheme: 'dark',\n creator: 'Jiachi Liu',\n publisher: 'Sebastian Markb\u00e5ge',\n formatDetection: {\n email: false,\n address: false,\n telephone: false,\n },\n}\n output \n\n\n\n", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-10", "text": "\n\n\n\n\n\n\nmetadataBase\nmetadataBase is a convenience option to set a base URL prefix for metadata fields that require a fully qualified URL.\nmetadataBase allows URL-based metadata fields defined in the current route segment and below to use a relative path instead of an otherwise required absolute URL.\nThe field's relative path will be composed with metadataBase to form a fully qualified URL.\nIf not configured, metadataBase is automatically populated with a default value.", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-11", "text": "If not configured, metadataBase is automatically populated with a default value.\nlayout.js / page.js export const metadata = {\n metadataBase: new URL('https://acme.com'),\n alternates: {\n canonical: '/',\n languages: {\n 'en-US': '/en-US',\n 'de-DE': '/de-DE',\n },\n },\n openGraph: {\n images: '/og-image.png',\n },\n}\n output \n\n\n\nGood to know:", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-12", "text": "Good to know:\nmetadataBase is typically set in root app/layout.js to apply to URL-based metadata fields across all routes.\nAll URL-based metadata fields that require absolute URLs can be configured with a metadataBase option.\nmetadataBase can contain a subdomain e.g. https://app.acme.com or base path e.g. https://acme.com/start/from/here\nIf a metadata field provides an absolute URL, metadataBase will be ignored.\nUsing a relative path in a URL-based metadata field without configuring a metadataBase will cause a build error.\nNext.js will normalize duplicate slashes between metadataBase (e.g. https://acme.com/) and a relative field (e.g. /path) to a single slash (e.g. https://acme.com/path)\nDefault value\nIf not configured, metadataBase has a default value", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-13", "text": "Default value\nIf not configured, metadataBase has a default value\nWhen VERCEL_URL is detected: https://${process.env.VERCEL_URL} otherwise it falls back to http://localhost:${process.env.PORT || 3000}.\nWhen overriding the default, we recommend using environment variables to compute the URL. This allows configuring a URL for local development, staging, and production environments.\nURL Composition\nURL composition favors developer intent over default directory traversal semantics.\nTrailing slashes between metadataBase and metadata fields are normalized.\nAn \"absolute\" path in a metadata field (that typically would replace the whole URL path) is treated as a \"relative\" path (starting from the end of metadataBase).\nFor example, given the following metadataBase:\napp/layout.tsx import { Metadata } from 'next'\n \nexport const metadata: Metadata = {\n metadataBase: new URL('https://acme.com'),\n}", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-14", "text": "metadataBase: new URL('https://acme.com'),\n}\nAny metadata fields that inherit the above metadataBase and set their own value will be resolved as follows:\nmetadata fieldResolved URL/https://acme.com./https://acme.compaymentshttps://acme.com/payments/paymentshttps://acme.com/payments./paymentshttps://acme.com/payments../paymentshttps://acme.com/paymentshttps://beta.acme.com/paymentshttps://beta.acme.com/payments\nopenGraph\nlayout.js / page.js export const metadata = {\n openGraph: {\n title: 'Next.js',\n description: 'The React Framework for the Web',\n url: 'https://nextjs.org',\n siteName: 'Next.js',\n images: [\n {\n url: 'https://nextjs.org/og.png',\n width: 800,", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-15", "text": "width: 800,\n height: 600,\n },\n {\n url: 'https://nextjs.org/og-alt.png',\n width: 1800,\n height: 1600,\n alt: 'My custom alt',\n },\n ],\n locale: 'en_US',\n type: 'website',\n },\n}\n output \n\n\n\n\n\n", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-16", "text": "\n\n\n\n\n\n\nlayout.js / page.js export const metadata = {\n openGraph: {\n title: 'Next.js',\n description: 'The React Framework for the Web',\n type: 'article',\n publishedTime: '2023-01-01T00:00:00.000Z',\n authors: ['Seb', 'Josh'],\n },\n}", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-17", "text": "authors: ['Seb', 'Josh'],\n },\n}\n output \n\n\n\n\n\nGood to know:\nIt may be more convenient to use the file-based Metadata API for Open Graph images. Rather than having to sync the config export with actual files, the file-based API will automatically generate the correct metadata for you.\nrobots\n import type { Metadata } from 'next'\n \nexport const metadata: Metadata = {\n robots: {\n index: false,", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-18", "text": "export const metadata: Metadata = {\n robots: {\n index: false,\n follow: true,\n nocache: true,\n googleBot: {\n index: true,\n follow: false,\n noimageindex: true,\n 'max-video-preview': -1,\n 'max-image-preview': 'large',\n 'max-snippet': -1,\n },\n },\n}\n output \n\nicons", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-19", "text": "/>\nicons\nGood 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.\nlayout.js / page.js export const metadata = {\n icons: {\n icon: '/icon.png',\n shortcut: '/shortcut-icon.png',\n apple: '/apple-icon.png',\n other: {\n rel: 'apple-touch-icon-precomposed',\n url: '/apple-touch-icon-precomposed.png',\n },\n },\n}\n output \n\n\n", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-20", "text": "href=\"/apple-touch-icon-precomposed.png\"\n/>\nlayout.js / page.js export const metadata = {\n icons: {\n icon: [{ url: '/icon.png' }, new URL('/icon.png', 'https://example.com')],\n shortcut: ['/shortcut-icon.png'],\n apple: [\n { url: '/apple-icon.png' },\n { url: '/apple-icon-x3.png', sizes: '180x180', type: 'image/png' },\n ],\n other: [\n {\n rel: 'apple-touch-icon-precomposed',\n url: '/apple-touch-icon-precomposed.png',\n },\n ],\n },\n}\n output \n\n\n\n\n\n\nGood to know: The msapplication-* meta tags are no longer supported in Chromium builds of Microsoft Edge, and thus no longer needed.\nthemeColor\nLearn more about theme-color.\nSimple theme color\nlayout.js / page.js export const metadata = {\n themeColor: 'black',\n}\n output \nWith media attribute\nlayout.js / page.js export const metadata = {\n themeColor: [", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-22", "text": "layout.js / page.js export const metadata = {\n themeColor: [\n { media: '(prefers-color-scheme: light)', color: 'cyan' },\n { media: '(prefers-color-scheme: dark)', color: 'black' },\n ],\n}\n output \n\nmanifest\nA web application manifest, as defined in the Web Application Manifest specification.\nlayout.js / page.js export const metadata = {\n manifest: 'https://nextjs.org/manifest.json',\n}\n output \ntwitter\nLearn more about the Twitter Card markup reference.\nlayout.js / page.js export const metadata = {", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-23", "text": "layout.js / page.js export const metadata = {\n twitter: {\n card: 'summary_large_image',\n title: 'Next.js',\n description: 'The React Framework for the Web',\n siteId: '1467726470533754880',\n creator: '@nextjs',\n creatorId: '1467726470533754880',\n images: ['https://nextjs.org/og.png'],\n },\n}\n output \n\n\n\n", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-24", "text": "\n\n\nlayout.js / page.js export const metadata = {\n twitter: {\n card: 'app',\n title: 'Next.js',\n description: 'The React Framework for the Web',\n siteId: '1467726470533754880',\n creator: '@nextjs',\n creatorId: '1467726470533754880',\n images: {\n url: 'https://nextjs.org/og.png',\n alt: 'Next.js Logo',\n },\n app: {\n name: 'twitter_app',\n id: {\n iphone: 'twitter_app://iphone',\n ipad: 'twitter_app://ipad',", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-25", "text": "ipad: 'twitter_app://ipad',\n googleplay: 'twitter_app://googleplay',\n },\n url: {\n iphone: 'https://iphone_url',\n ipad: 'https://ipad_url',\n },\n },\n },\n}\n output \n\n\n\n\n\n\n", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-26", "text": "\n\n\n\n\n\n\n\n\nviewport", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-27", "text": "\nviewport\nGood to know: The viewport meta tag is automatically set with the following default values. Usually, manual configuration is unnecessary as the default is sufficient. However, the information is provided for completeness.\nlayout.js / page.js export const metadata = {\n viewport: {\n width: 'device-width',\n initialScale: 1,\n maximumScale: 1,\n },\n}\n output \nverification\nlayout.js / page.js export const metadata = {\n verification: {\n google: 'google',\n yandex: 'yandex',\n yahoo: 'yahoo',\n other: {\n me: ['my-email', 'my-link'],\n },\n },", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-28", "text": "me: ['my-email', 'my-link'],\n },\n },\n}\n output \n\n\n\n\nappleWebApp\nlayout.js / page.js export const metadata = {\n itunes: {\n appId: 'myAppStoreID',\n appArgument: 'myAppArgument',\n },\n appleWebApp: {\n title: 'Apple Web App',\n statusBarStyle: 'black-translucent',\n startupImage: [\n '/assets/startup/apple-touch-startup-image-768x1004.png',\n {", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-29", "text": "{\n url: '/assets/startup/apple-touch-startup-image-1536x2008.png',\n media: '(device-width: 768px) and (device-height: 1024px)',\n },\n ],\n },\n}\n output \n\n\n\n\n\nalternates\nlayout.js / page.js export const metadata = {\n alternates: {\n canonical: 'https://nextjs.org',\n languages: {\n 'en-US': 'https://nextjs.org/en-US',\n 'de-DE': 'https://nextjs.org/de-DE',\n },\n media: {\n 'only screen and (max-width: 600px)': 'https://nextjs.org/mobile',\n },\n types: {\n 'application/rss+xml': 'https://nextjs.org/rss',", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-31", "text": "types: {\n 'application/rss+xml': 'https://nextjs.org/rss',\n },\n },\n}\n output \n\n\n\n\nappLinks\nlayout.js / page.js export const metadata = {\n appLinks: {\n ios: {\n url: 'https://nextjs.org/ios',", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-32", "text": "ios: {\n url: 'https://nextjs.org/ios',\n app_store_id: 'app_store_id',\n },\n android: {\n package: 'com.example.android/package',\n app_name: 'app_name_android',\n },\n web: {\n url: 'https://nextjs.org/web',\n should_fallback: true,\n },\n },\n}\n output \n\n\n\n", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-33", "text": "\n\narchives\nDescribes a collection of records, documents, or other materials of historical interest (source).\nlayout.js / page.js export const metadata = {\n archives: ['https://nextjs.org/13'],\n}\n output \nassets\nlayout.js / page.js export const metadata = {\n assets: ['https://nextjs.org/assets'],\n}\n output \nbookmarks\nlayout.js / page.js export const metadata = {\n bookmarks: ['https://nextjs.org/13'],\n}", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-34", "text": "bookmarks: ['https://nextjs.org/13'],\n}\n output \ncategory\nlayout.js / page.js export const metadata = {\n category: 'technology',\n}\n output \nother\nAll metadata options should be covered using the built-in support. However, there may be custom metadata tags specific to your site, or brand new metadata tags just released. You can use the other option to render any custom metadata tag.\nlayout.js / page.js export const metadata = {\n other: {\n custom: 'meta',\n },\n}\n output \nUnsupported Metadata\nThe following metadata types do not currently have built-in support. However, they can still be rendered in the layout or page itself.", "source": "https://nextjs.org/docs/app/api-reference/functions/generate-metadata"} {"id": "196df85b10c4-35", "text": "MetadataRecommendationUse appropriate HTTP Headers via redirect(), Middleware, Security HeadersRender the tag in the layout or page itself.