gavmac00/nextjs-app-docs huggingface dataset:
Font Module
This API reference will help you understand how to use next/font/google and next/font/local. For features and usage, please see the Optimizing Fonts page.
Font Function Arguments
For usage, review Google Fonts and Local Fonts.
Keyfont/googlefont/localTypeRequiredsrcString or Array of ObjectsYesweightString or ArrayRequired/OptionalstyleString or Array-subsetsArray of Strings-axesArray of Strings-displayString-preloadBoolean-fallbackArray of Strings-adjustFontFallbackBoolean or String-variableString-declarationsArray of Objects-
src
The path of the font file as a string or an array of objects (with type Array<{path: string, weight?: string, style?: string}>) relative to the directory where the font loader function is called.
Used in next/font/local
Required
Examples:
src:'./fonts/my-font.woff2' where my-font.woff2 is placed in a directory named fonts inside the app directory
src:[{path: './inter/Inter-Thin.ttf', weight: '100',},{path: './inter/Inter-Regular.ttf',weight: '400',},{path: './inter/Inter-Bold-Italic.ttf', weight: '700',style: 'italic',},]
if the font loader function is called in app/page.tsx using src:'../styles/fonts/my-font.ttf', then my-font.ttf is placed in styles/fonts at the root of the project
weight
The font weight with the following possibilities:
A string with possible values of the weights available for the specific font or a range of values if it's a variable font
An array of weight values if the font is not a variable google font. It applies to next/font/google only.
Used in next/font/google and next/font/local
Required if the font being used is not variable
Examples:
Required if the font being used is not variable
Examples:
weight: '400': A string for a single weight value - for the font Inter, the possible values are '100', '200', '300', '400', '500', '600', '700', '800', '900' or 'variable' where 'variable' is the default)
weight: '100 900': A string for the range between 100 and 900 for a variable font
weight: ['100','400','900']: An array of 3 possible values for a non variable font
style
The font style with the following possibilities:
A string value with default value of 'normal'
An array of style values if the font is not a variable google font. It applies to next/font/google only.
Used in next/font/google and next/font/local
Optional
Examples:
style: 'italic': A string - it can be normal or italic for next/font/google
style: 'italic': A string - it can be normal or italic for next/font/google
style: 'oblique': A string - it can take any value for next/font/local but is expected to come from standard font styles
style: ['italic','normal']: An array of 2 values for next/font/google - the values are from normal and italic
subsets
The font subsets defined by an array of string values with the names of each subset you would like to be preloaded. Fonts specified via subsets will have a link preload tag injected into the head when the preload option is true, which is the default.
Used in next/font/google
Optional
Examples:
subsets: ['latin']: An array with the subset latin
You can find a list of all subsets on the Google Fonts page for your font.
axes
You can find a list of all subsets on the Google Fonts page for your font.
axes
Some variable fonts have extra axes that can be included. By default, only the font weight is included to keep the file size down. The possible values of axes depend on the specific font.
Used in next/font/google
Optional
Examples:
axes: ['slnt']: An array with value slnt for the Inter variable font which has slnt as additional axes as shown here. You can find the possible axes values for your font by using the filter on the Google variable fonts page and looking for axes other than wght
display
The font display with possible string values of 'auto', 'block', 'swap', 'fallback' or 'optional' with default value of 'swap'.
Used in next/font/google and next/font/local
Optional
Examples:
display: 'optional': A string assigned to the optional value
preload
Optional
Examples:
display: 'optional': A string assigned to the optional value
preload
A boolean value that specifies whether the font should be preloaded or not. The default is true.
Used in next/font/google and next/font/local
Optional
Examples:
preload: false
fallback
The fallback font to use if the font cannot be loaded. An array of strings of fallback fonts with no default.
Optional
Used in next/font/google and next/font/local
Examples:
fallback: ['system-ui', 'arial']: An array setting the fallback fonts to system-ui or arial
adjustFontFallback
For next/font/google: A boolean value that sets whether an automatic fallback font should be used to reduce Cumulative Layout Shift. The default is true.
For next/font/local: A string or boolean false value that sets whether an automatic fallback font should be used to reduce Cumulative Layout Shift. The possible values are 'Arial', 'Times New Roman' or false. The default is 'Arial'.
Used in next/font/google and next/font/local
Optional
Examples:
adjustFontFallback: false: for ``next/font/google`
adjustFontFallback: 'Times New Roman': for next/font/local
variable
A string value to define the CSS variable name to be used if the style is applied with the CSS variable method.
Used in next/font/google and next/font/local
Optional
Examples:
variable: '--my-font': The CSS variable --my-font is declared
declarations
An array of font face descriptor key-value pairs that define the generated @font-face further.
Used in next/font/local
Optional
Examples:
declarations: [{ prop: 'ascent-override', value: '90%' }]
declarations: [{ prop: 'ascent-override', value: '90%' }]
Applying Styles
You can apply the font styles in three ways:
className
style
CSS Variables
className
Returns a read-only CSS className for the loaded font to be passed to an HTML element.
 <p className={inter.className}>Hello, Next.js!</p>
style
Returns a read-only CSS style object for the loaded font to be passed to an HTML element, including style.fontFamily to access the font family name and fallback fonts.
 <p style={inter.style}>Hello World</p>
CSS Variables
If you would like to set your styles in an external style sheet and specify additional options there, use the CSS variable method.
In addition to importing the font, also import the CSS file where the CSS variable is defined and set the variable option of the font loader object as follows:
app/page.tsx import { Inter } from 'next/font/google'
import styles from '../styles/component.module.css'
 
const inter = Inter({
  variable: '--font-inter',
})
To use the font, set the className of the parent container of the text you would like to style to the font loader's variable value and the className of the text to the styles property from the external CSS file.
app/page.tsx <main className={inter.variable}>
  <p className={styles.text}>Hello World</p>
</main>
Define the text selector class in the component.module.css CSS file as follows:
styles/component.module.css .text {
  font-family: var(--font-inter);
  font-weight: 200;
  font-style: italic;
}
font-weight: 200;
  font-style: italic;
}
In the example above, the text Hello World is styled using the Inter font and the generated font fallback with font-weight: 200 and font-style: italic.
Using a font definitions file
Every time you call the localFont or Google font function, that font will be hosted as one instance in your application. Therefore, if you need to use the same font in multiple places, you should load it in one place and import the related font object where you need it. This is done using a font definitions file.
For example, create a fonts.ts file in a styles folder at the root of your app directory.
Then, specify your font definitions as follows:
styles/fonts.ts import { Inter, Lora, Source_Sans_Pro } from 'next/font/google'
import localFont from 'next/font/local'
 
// define your variable fonts
const inter = Inter()
// define your variable fonts
const inter = Inter()
const lora = Lora()
// define 2 weights of a non-variable font
const sourceCodePro400 = Source_Sans_Pro({ weight: '400' })
const sourceCodePro700 = Source_Sans_Pro({ weight: '700' })
// define a custom local font where GreatVibes-Regular.ttf is stored in the styles folder
const greatVibes = localFont({ src: './GreatVibes-Regular.ttf' })
 
export { inter, lora, sourceCodePro400, sourceCodePro700, greatVibes }
You can now use these definitions in your code as follows:
app/page.tsx import { inter, lora, sourceCodePro700, greatVibes } from '../styles/fonts'
 
export default function Page() {
  return (
    <div>
export default function Page() {
  return (
    <div>
      <p className={inter.className}>Hello world using Inter font</p>
      <p style={lora.style}>Hello world using Lora font</p>
      <p className={sourceCodePro700.className}>
        Hello world using Source_Sans_Pro font with weight 700
      </p>
      <p className={greatVibes.className}>My title in Great Vibes font</p>
    </div>
  )
}
To make it easier to access the font definitions in your code, you can define a path alias in your tsconfig.json or jsconfig.json files as follows:
tsconfig.json {
  "compilerOptions": {
    "paths": {
      "@/fonts": ["./styles/fonts"]
    }
  }
}
You can now import any font definition as follows:
}
  }
}
You can now import any font definition as follows:
app/about/page.tsx import { greatVibes, sourceCodePro400 } from '@/fonts'
Version Changes
VersionChangesv13.2.0@next/font renamed to next/font. Installation no longer required.v13.0.0@next/font was added.
loading.jsA loading file can create instant loading states built on Suspense.
By default, this file is a Server Component - but can also be used as a Client Component through the "use client" directive.
app/feed/loading.tsx export default function Loading() {
  // Or a custom loading skeleton component
  return <p>'Loading...'</p>
}
Loading UI components do not accept any parameters.
Good to know
While designing loading UI, you may find it helpful to use the React Developer Tools to manually toggle Suspense boundaries.
Version History
VersionChangesv13.0.0loading introduced.
page.jsA page is UI that is unique to a route.
app/blog/[slug]/page.tsx export default function Page({
  params,
  searchParams,
}: {
  params: { slug: string }
  searchParams: { [key: string]: string | string[] | undefined }
}) {
  return <h1>My Page</h1>
}
Props
params (optional)
An object containing the dynamic route parameters from the root segment down to that page. For example:
ExampleURLparamsapp/shop/[slug]/page.js/shop/1{ slug: '1' }app/shop/[category]/[item]/page.js/shop/1/2{ category: '1', item: '2' }app/shop/[...slug]/page.js/shop/1/2{ slug: ['1', '2'] }
searchParams (optional)
searchParams (optional)
An object containing the search parameters of the current URL. For example:
URLsearchParams/shop?a=1{ a: '1' }/shop?a=1&b=2{ a: '1', b: '2' }/shop?a=1&a=2{ a: ['1', '2'] }
Good to know:
searchParams is a Dynamic API whose values cannot be known ahead of time. Using it will opt the page into dynamic rendering at request time.
searchParams returns a plain JavaScript object and not a URLSearchParams instance.
Version History
VersionChangesv13.0.0page introduced.
Route Segment ConfigThe Route Segment options allows you configure the behavior of a Page, Layout, or Route Handler by directly exporting the following variables:
OptionTypeDefaultdynamic'auto' | 'force-dynamic' | 'error' | 'force-static''auto'dynamicParamsbooleantruerevalidatefalse | 'force-cache' | 0 | numberfalsefetchCache'auto' | 'default-cache' | 'only-cache' | 'force-cache' | 'force-no-store' | 'default-no-store' | 'only-no-store''auto'runtime'nodejs' | 'edge''nodejs'preferredRegion'auto' | 'global' | 'home' | string | string[]'auto'maxDurationnumberSet by deployment platform
layout.tsx / page.tsx / route.ts export const dynamic = 'auto'
export const dynamicParams = true
export const revalidate = false
export const fetchCache = 'auto'
export const revalidate = false
export const fetchCache = 'auto'
export const runtime = 'nodejs'
export const preferredRegion = 'auto'
export const maxDuration = 5
 
export default function MyComponent() {}
Good to know:
The values of the config options currently need be statically analyzable. For example revalidate = 600 is valid, but revalidate = 60 * 10 is not.
Options
dynamic
Change the dynamic behavior of a layout or page to fully static or fully dynamic.
layout.tsx / page.tsx / route.ts export const dynamic = 'auto'
// 'auto' | 'force-dynamic' | 'error' | 'force-static'
// 'auto' | 'force-dynamic' | 'error' | 'force-static'
Good to know: The new model in the app directory favors granular caching control at the fetch request level over the binary all-or-nothing model of getServerSideProps and getStaticProps at the page-level in the pages directory. The dynamic option is a way to opt back in to the previous model as a convenience and provides a simpler migration path.
'auto' (default): The default option to cache as much as possible without preventing any components from opting into dynamic behavior.
'force-dynamic': Force dynamic rendering and dynamic data fetching of a layout or page by disabling all caching of fetch requests and always revalidating. This option is equivalent to:
getServerSideProps() in the pages directory.
Setting the option of every fetch() request in a layout or page to { cache: 'no-store', next: { revalidate: 0 } }.
Setting the segment config to export const fetchCache = 'force-no-store'
'error': Force static rendering and static data fetching of a layout or page by causing an error if any components use dynamic functions or dynamic fetches. This option is equivalent to:
getStaticProps() in the pages directory.
Setting the option of every fetch() request in a layout or page to { cache: 'force-cache' }.
Setting the segment config to fetchCache = 'only-cache', dynamicParams = false.
dynamic = 'error' changes the default of dynamicParams from true to false. You can opt back into dynamically rendering pages for dynamic params not generated by generateStaticParams by manually setting dynamicParams = true.
'force-static': Force static rendering and static data fetching of a layout or page by forcing cookies(), headers() and useSearchParams() to return empty values.
Good to know:
Good to know:
Instructions on how to migrate from getServerSideProps and getStaticProps to dynamic: 'force-dynamic' and dynamic: 'error' can be found in the upgrade guide.
dynamicParams
Control what happens when a dynamic segment is visited that was not generated with generateStaticParams.
layout.tsx / page.tsx export const dynamicParams = true // true | false,
true (default): Dynamic segments not included in generateStaticParams are generated on demand.
false: Dynamic segments not included in generateStaticParams will return a 404.
Good to know:
This option replaces the fallback: true | false | blocking option of getStaticPaths in the pages directory.
When dynamicParams = true, the segment uses Streaming Server Rendering.
If the dynamic = 'error' and dynamic = 'force-static' are used, it'll change the default of dynamicParams to false.
revalidate
revalidate
Set the default revalidation time for a layout or page. This option does not override the revalidate value set by individual fetch requests.
layout.tsx / page.tsx / route.ts export const revalidate = false
// false | 'force-cache' | 0 | number
false: (default) The default heuristic to cache any fetch requests that set their cache option to 'force-cache' or are discovered before a dynamic function is used. Semantically equivalent to revalidate: Infinity which effectively means the resource should be cached indefinitely. It is still possible for individual fetch requests to use cache: 'no-store' or revalidate: 0 to avoid being cached and make the route dynamically rendered. Or set revalidate to a positive number lower than the route default to increase the revalidation frequency of a route.
0: Ensure a layout or page is always dynamically rendered even if no dynamic functions or dynamic data fetches are discovered. This option changes the default of fetch requests that do not set a cache option to 'no-store' but leaves fetch requests that opt into 'force-cache' or use a positive revalidate as is.
number: (in seconds) Set the default revalidation frequency of a layout or page to n seconds.
Revalidation Frequency
The lowest revalidate across each layout and page of a single route will determine the revalidation frequency of the entire route. This ensures that child pages are revalidated as frequently as their parent layouts.
Individual fetch requests can set a lower revalidate than the route's default revalidate to increase the revalidation frequency of the entire route. This allows you to dynamically opt-in to more frequent revalidation for certain routes based on some criteria.
fetchCache
fetchCache
This is an advanced option that should only be used if you specifically need to override the default behavior.By default, Next.js will cache any fetch() requests that are reachable before any dynamic functions are used and will not cache fetch requests that are discovered after dynamic functions are used.fetchCache allows you to override the default cache option of all fetch requests in a layout or page.layout.tsx / page.tsx / route.ts export const fetchCache = 'auto'
// 'auto' | 'default-cache' | 'only-cache'
// 'force-cache' | 'force-no-store' | 'default-no-store' | 'only-no-store'
'auto' (default)- The default option to cache fetch requests before dynamic functions with the cache option they provide and not cache fetch requests after dynamic functions.
'default-cache': Allow any cache option to be passed to fetch but if no option is provided then set the cache option to 'force-cache'. This means that even fetch requests after dynamic functions are considered static.
'only-cache': Ensure all fetch requests opt into caching by changing the default to cache: 'force-cache' if no option is provided and causing an error if any fetch requests use cache: 'no-store'.
'force-cache': Ensure all fetch requests opt into caching by setting the cache option of all fetch requests to 'force-cache'.
'default-no-store': Allow any cache option to be passed to fetch but if no option is provided then set the cache option to 'no-store'. This means that even fetch requests before dynamic functions are considered dynamic.
'only-no-store': Ensure all fetch requests opt out of caching by changing the default to cache: 'no-store' if no option is provided and causing an error if any fetch requests use cache: 'force-cache'
'force-no-store': Ensure all fetch requests opt out of caching by setting the cache option of all fetch requests to 'no-store'. This forces all fetch requests to be re-fetched every request even if they provide a 'force-cache' option.
Cross-route segment behavior
Any options set across each layout and page of a single route need to be compatible with each other.
If both the 'only-cache' and 'force-cache' are provided, then 'force-cache' wins. If both 'only-no-store' and 'force-no-store' are provided, then 'force-no-store' wins. The force option changes the behavior across the route so a single segment with 'force-*' would prevent any errors caused by 'only-*'.
The intention of the 'only-*' and force-*' options is to guarantee the whole route is either fully static or fully dynamic. This means:
A combination of 'only-cache' and 'only-no-store' in a single route is not allowed.
A combination of 'force-cache' and 'force-no-store' in a single route is not allowed.
A parent cannot provide 'default-no-store' if a child provides 'auto' or '*-cache' since that could make the same fetch have different behavior.
It is generally recommended to leave shared parent layouts as 'auto' and customize the options where child segments diverge.
runtime
layout.tsx / page.tsx / route.ts export const runtime = 'nodejs'
// 'edge' | 'nodejs'
nodejs (default)
edge
Learn more about the Edge and Node.js runtimes.
preferredRegion
edge
Learn more about the Edge and Node.js runtimes.
preferredRegion
layout.tsx / page.tsx / route.ts export const preferredRegion = 'auto'
// 'auto' | 'global' | 'home' | ['iad1', 'sfo1']
Support for preferredRegion, and regions supported, is dependent on your deployment platform.
Good to know:
If a preferredRegion is not specified, it will inherit the option of the nearest parent layout.
The root layout defaults to all regions.
maxDuration
Based on your deployment platform, you may be able to use a higher default execution time for your function.
This setting allows you to opt into a higher execution time within your plans limit.
Note: This settings requires Next.js 13.4.10 or higher.
layout.tsx / page.tsx / route.ts export const maxDuration = 5
Good to know:
Good to know:
If a maxDuration is not specified, the default value is dependent on your deployment platform and plan.
generateStaticParams
The generateStaticParams function can be used in combination with dynamic route segments to define the list of route segment parameters that will be statically generated at build time instead of on-demand at request time.
See the API reference for more details.
not-found.jsThe not-found file is used to render UI when the notFound function is thrown within a route segment. Along with serving a custom UI, Next.js will also return a 404 HTTP status code.
app/blog/not-found.tsx import Link from 'next/link'
 
export default function NotFound() {
  return (
    <div>
      <h2>Not Found</h2>
      <p>Could not find requested resource</p>
      <p>
        View <Link href="/blog">all posts</Link>
      </p>
    </div>
  )
}
Good to know: In addition to catching expected notFound() errors, the root app/not-found.js file also handles any unmatched URLs for your whole application. This means users that visit a URL that is not handled by your app will be shown the UI exported by the app/not-found.js file.
Props
Props
not-found.js components do not accept any props.
Version History
VersionChangesv13.3.0Root app/not-found handles global unmatched URLs.v13.0.0not-found introduced.
default.jsThis documentation is still being written. Please check back later.
layout.jsA layout is UI that is shared between routes.
app/dashboard/layout.tsx export default function DashboardLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return <section>{children}</section>
}
A root layout is the top-most layout in the root app directory. It is used to define the <html> and <body> tags and other globally shared UI.
app/layout.tsx export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  )
}
Props
children (required)
</html>
  )
}
Props
children (required)
Layout components should accept and use a children prop. During rendering, children will be populated with the route segments the layout is wrapping. These will primarily be the component of a child Layout (if it exists) or Page, but could also be other special files like Loading or Error when applicable.
params (optional)
The dynamic route parameters object from the root segment down to that layout.
ExampleURLparamsapp/dashboard/[team]/layout.js/dashboard/1{ team: '1' }app/shop/[tag]/[item]/layout.js/shop/1/2{ tag: '1', item: '2' }app/blog/[...slug]/layout.js/blog/1/2{ slug: ['1', '2'] }
For example:
app/shop/[tag]/[item]/layout.tsx export default function ShopLayout({
  children,
  params,
}: {
children,
  params,
}: {
  children: React.ReactNode
  params: {
    tag: string
    item: string
  }
}) {
  // URL -> /shop/shoes/nike-air-max-97
  // `params` -> { tag: 'shoes', item: 'nike-air-max-97' }
  return <section>{children}</section>
}
Good to know
Layout's do not receive searchParams
Unlike Pages, Layout 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.
When using client-side navigation, Next.js automatically only renders the part of the page below the common layout between two routes.
For example, in the following directory structure, dashboard/layout.tsx is the common layout for both /dashboard/settings and /dashboard/analytics:
 app