gavmac00/nextjs-app-docs huggingface dataset:
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 existing applications, you can incrementally migrate to the App Router.
This section of the documentation includes the features available in the App Router:
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>
 
Available commands
  build, start, export, dev, lint, telemetry, info
 
Options
  --version, -v   Version number
  --help, -h      Displays this message
 
For more information run a command with the --help flag
  $ next build --help
You can pass any node arguments to next commands:
Terminal NODE_OPTIONS='--throw-deprecation' next
NODE_OPTIONS='-r esm' next
NODE_OPTIONS='--inspect' next
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 the page client-side. The size for each route only includes its dependencies.
First Load JS – 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.
Both of these values are compressed with gzip. The first load is indicated by green, yellow, or red. Aim for green for performant applications.
You can enable production profiling for React with the --profile flag in next build. This requires Next.js 9.5:
Terminal next build --profile
After that, you can use the profiler in the same way as you would in development.
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.
Development
next dev starts the application in development mode with hot-code reloading, error reporting, and more:
The application will start at http://localhost:3000 by default. The default port can be changed with -p, like so:
Terminal npx next dev -p 4000
Or using the PORT environment variable:
Terminal PORT=4000 npx next dev
Good to know: PORT cannot be set in .env as booting up the HTTP server happens before any other code is initialized.
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. The application should be compiled with next build first.
The application will start at http://localhost:3000 by default. The default port can be changed with -p, like so:
Terminal npx next start -p 4000
Or using the PORT environment variable:
Terminal PORT=4000 npx next start
Good to know:
-PORT cannot be set in .env as booting up the HTTP server happens before any other code is initialized.
next start cannot be used with output: 'standalone' or output: 'export'.
Keep Alive Timeout
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, 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.
To configure the timeout values for the production Next.js server, pass --keepAliveTimeout (in milliseconds) to next start, like so:
Terminal npx next start --keepAliveTimeout 70000
Lint
next lint runs ESLint for all files in the pages/, app/, components/, lib/, and src/ directories. It also
provides a guided setup to install any required dependencies if ESLint is not already configured in
your application.
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 like to share any information.
To learn more about Telemetry, please read this document.
Next Info
next info prints relevant details about the current system which can be used to report Next.js bugs.
This information includes Operating System platform/arch/version, Binaries (Node.js, npm, Yarn, pnpm) and npm package versions (next, react, react-dom).
Running the following in your project's root directory:
Terminal next info
will give you information like this example:
Terminal  
    Operating System:
      Platform: linux
      Arch: x64
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 information should then be pasted into GitHub Issues.
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.
Interactive
You can create a new project interactively by running:
Terminal npx create-next-app@latest
Terminal yarn create next-app
Terminal pnpm create next-app
You will then be asked the following prompts:
Terminal What is your project named?  my-app
Would you like to use TypeScript?  No / Yes
Would you like to use ESLint?  No / Yes
Would you like to use Tailwind CSS?  No / Yes
Would you like to use `src/` directory?  No / Yes
Would you like to use App Router? (recommended)  No / Yes
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 project non-interactively.
Further, you can negate default options by prefixing them with --no- (e.g. --no-eslint).
See create-next-app --help:
Terminal Usage: create-next-app <project-directory> [options]
 
Options:
  -V, --version                        output the version number
  --ts, --typescript
 
    Initialize as a TypeScript project. (default)
 
  --js, --javascript
 
    Initialize as a JavaScript project.
 
  --tailwind
 
    Initialize with Tailwind CSS config. (default)
--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 "@/*").
 
  --use-npm
 
    Explicitly tell the CLI to bootstrap the app using npm
 
  --use-pnpm
 
    Explicitly tell the CLI to bootstrap the app using pnpm
 
  --use-yarn
 
    Explicitly tell the CLI to bootstrap the app using Yarn
 
  -e, --example [name]|[github-url]
-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 with
    a slash (e.g. bug/fix-1) and the path to the example (e.g. foo/bar).
    In this case, you must specify the path to the example separately:
    --example-path foo/bar
 
  --reset-preferences
 
    Explicitly tell the CLI to reset any stored preferences
 
  -h, --help                           output usage information
Why use Create Next App?
-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 arguments) launches an interactive experience that guides you through setting up a project.
Zero Dependencies: Initializing a project is as quick as one second. Create Next App has zero dependencies.
Offline Support: Create Next App will automatically detect if you're offline and bootstrap your project using your local package cache.
Support 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.
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.
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 requestResponseRepresents an HTTP responseURLSearchParamsRepresents URL search parametersWebSocketRepresents a websocket connection
Encoding APIs
APIDescriptionatobDecodes 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
Stream APIs
Stream APIs
APIDescriptionReadableStreamRepresents a readable streamReadableStreamBYOBReaderRepresents a reader of a ReadableStreamReadableStreamDefaultReaderRepresents a reader of a ReadableStreamTransformStreamRepresents a transform streamWritableStreamRepresents a writable streamWritableStreamDefaultWriterRepresents a writer of a WritableStream
Crypto APIs
APIDescriptioncryptoProvides access to the cryptographic functionality of the platformCryptoKeyRepresents a cryptographic keySubtleCryptoProvides access to common cryptographic primitives, like hashing, signing, encryption or decryption
Web Standard APIs
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
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
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
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
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
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.
node_modules can be used, as long as they implement ES Modules and do not use native Node.js APIs.
Calling require directly is not allowed. Use ES Modules instead.
The following JavaScript language features are disabled, and will not work:
APIDescriptionevalEvaluates 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
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: 'edge', // for Edge API Routes only
  unstable_allowDynamic: [
    // allows a single file
    '/lib/utilities.js',
    // use a glob to allow anything in the function-bind 3rd party module
    '/node_modules/function-bind/**',
  ],
}
unstable_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.
Be warned that if these statements are executed on the Edge, they will throw and cause a runtime error.
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 with the framework's persistent HTTP cache.
You can call fetch with async and await directly within Server Components.
app/page.tsx export default async function Page() {
  // This request should be cached until manually invalidated.
  // Similar to `getStaticProps`.
  // `force-cache` is the default and can be omitted.
  const staticData = await fetch(`https://...`, { cache: 'force-cache' })
 
  // This request should be refetched on every request.
  // Similar to `getServerSideProps`.
  const dynamicData = await fetch(`https://...`, { cache: 'no-store' })
// 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 any of the native options available.
Further, Next.js polyfills fetch on both the client and the server, so you can use fetch in both Server and Client Components.
options.cache
Configure how the request should interact with Next.js HTTP cache.
 fetch(`https://...`, { cache: 'force-cache' | 'no-store' })
force-cache (default) - Next.js looks for a matching request in its HTTP cache.
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 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.
Good to know:
If 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.
The no-cache option behaves the same way as no-store in Next.js.
options.next.revalidate
 fetch(`https://...`, { next: { revalidate: false | 0 | number } })
Set the cache lifetime of a resource (in seconds).
false - Cache the resource indefinitely. Semantically equivalent to revalidate: Infinity. The HTTP cache may evict older resources over time.
0 - Prevent the resource from being cached.
number - (in seconds) Specify the resource should have a cache lifetime of at most n seconds.
Good to know:
If an individual fetch() request sets a revalidate number lower than the default revalidate of a route, the whole route revalidation interval will be decreased.
If two fetch requests with the same URL in the same route have different revalidate values, the lower value will be used.
As 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'.
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.
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, type)
ParameterTypeDescriptionpathstringThe 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.
By 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.
The type parameter has no effect when used in Server Components.
Returns
redirect does not return any value.
Example
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://...')
  if (!res.ok) return undefined
  return res.json()
}
 
export default async function Profile({ params }) {
  const team = await fetchTeam(params.id)
  if (!team) {
    redirect('/login')
  }
 
  // ...
}
Good to know: redirect does not require you to use return redirect() as it uses the TypeScript never type.
VersionChangesv13.0.0redirect introduced.
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 generateStaticParams() {
  const posts = await fetch('https://.../posts').then((res) => res.json())
 
  return posts.map((post) => ({
    slug: post.slug,
  }))
}
 
// Multiple versions of this page will be statically generated
// using the `params` returned by `generateStaticParams`
export default function Page({ params }) {
  const { slug } = params
  // ...
}
Good to know
You can use the dynamicParams segment config option to control what happens when a dynamic segment is visited that was not generated with generateStaticParams.