new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Next.js · API reference · all subjects

components

51 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Form component import

The Form component is imported from 'next/form'. It extends the HTML form element to provide client-side navigation on submission, progressive enhancement, and prefetching of loading UI.

Form component with string action behavior

When the action prop is a string, the Form component behaves like a native HTML form using the GET method. Form data is encoded into the URL as search params. Next.js performs client-side navigation instead of a full page reload, retains shared UI and client-side state, and prefetches the path when the form becomes visible to preload shared UI like layout.js and loading.js.

Form component with function action behavior

When the action prop is a function (Server Action), the Form component behaves like a React form, executing the Server Action when the form is submitted.

Form component string action props

When action is a string, the Form component supports these props: action (string, URL or relative path, required) - the URL or path to navigate to when submitted, where an empty string navigates to the same route with updated search params; replace (boolean, optional, defaults to false) - replaces current history state instead of pushing a new one to the browser history stack; scroll (boolean, optional, defaults to true) - controls scroll behavior, scrolls to top of new route and maintains scroll position for backwards/forwards navigation; prefetch (boolean, optional, defaults to true) - controls whether the path should be prefetched when the form becomes visible in the user's viewport.

Form component function action props

When action is a function, the Form component supports only the action prop (function, Server Action, required). The replace and scroll props are ignored when action is a function.

Form component formAction caveat

The formAction attribute can be used in a button or input type submit field to override the action prop. Next.js will perform client-side navigation but this approach does not support prefetching. When using basePath, the basePath must be included in the formAction path, for example formAction="/base-path/search".

Form component key prop caveat

Passing a key prop to a string action Form is not supported. If you want to trigger a re-render or perform a mutation, use a function action instead.

Form component onSubmit caveat

The onSubmit handler can be used to handle form submission logic. However, calling event.preventDefault() will override Form behavior such as navigating to the specified URL.

Form component unsupported HTML attributes

The method, encType, and target HTML form attributes are not supported as they override Form behavior. Similarly, formMethod, formEncType, and formTarget are not supported and using them will fallback to native browser behavior. If you need to use these attributes, use the HTML form element instead.

Form component file input caveat

When using input type="file" with a string action, it matches browser behavior by submitting the filename instead of the file object.

Form component search example with string action

Example: import Form from 'next/form'; export default function Page() { return (<Form action="/search"><input name="query" /><button type="submit">Submit</button></Form>); } When the user updates the query input and submits, form data is encoded as search params, e.g. /search?query=abc. An empty string action navigates to the same route with updated search params. On the results page, access the query using the searchParams page prop.

Form component mutations example with Server Action

Example: import Form from 'next/form'; import { createPost } from '@/posts/actions'; export default function Page() { return (<Form action={createPost}><input name="title" /><button type="submit">Create Post</button></Form>); } The createPost Server Action receives FormData and can use the redirect function from 'next/navigation' to navigate to the new resource after mutation.

Components API Reference documentation structure

The Next.js Components documentation is part of the App Router API Reference section. Content is shared between the App Router and Pages Router. Content specific to the Pages Router should be wrapped in a `<PagesOnly>` component. Shared content should not be wrapped in any router-specific component.

Script component import and basic usage

The Script component is imported from 'next/script'. It is used to optimize third-party scripts in Next.js applications. Basic usage: import Script from 'next/script' and then use <Script src="https://example.com/script.js" /> in your component.

Script component props table

The Script component accepts the following props: src (String, required unless inline script is used), strategy (String, optional), onLoad (Function, optional), onReady (Function, optional), onError (Function, optional).

src prop - Script component

The src prop is a path string specifying the URL of an external script. This can be either an absolute external URL or an internal path. The src property is required unless an inline script is used.

strategy prop - Script component strategies

The strategy prop controls the loading strategy of the script. Four strategies are available: beforeInteractive (load before any Next.js code and before page hydration), afterInteractive (default - load early but after some hydration), lazyOnload (load during browser idle time), worker (experimental - load in a web worker).

beforeInteractive strategy - placement and behavior

Scripts with beforeInteractive strategy must be placed inside the root layout (app/layout.tsx in App Router) or the Document component (pages/_document.js in Pages Router). They are injected into the initial HTML from the server, preloaded and fetched before any first-party code, but their execution does not block page hydration. These scripts are designed to load scripts needed by the entire site and should only be used for critical scripts that need to be fetched as soon as possible. beforeInteractive scripts are always injected inside the head of the HTML document regardless of where they are placed in the component.

beforeInteractive strategy - example use cases

Examples of scripts that should be fetched as soon as possible with beforeInteractive include: bot detectors and cookie consent managers.

afterInteractive strategy - placement and behavior

Scripts that use the afterInteractive strategy are injected into the HTML client-side and load after some (or all) hydration occurs on the page. This is the default strategy of the Script component. afterInteractive should be used for any script that needs to load as soon as possible but not before any first-party Next.js code. These scripts can be placed inside any page or layout and will only load and execute when that page (or group of pages) is opened in the browser.

afterInteractive strategy - example use cases

Examples of scripts that are good candidates for afterInteractive include: tag managers and analytics.

lazyOnload strategy - placement and behavior

Scripts that use the lazyOnload strategy are injected into the HTML client-side during browser idle time and load after all resources on the page have been fetched. This strategy should be used for any background or low priority scripts that do not need to load early. lazyOnload scripts can be placed inside any page or layout and will only load and execute when that page (or group of pages) is opened in the browser.

lazyOnload strategy - example use cases

Examples of scripts that do not need to load immediately and can be fetched with lazyOnload include: chat support plugins and social media widgets.

worker strategy - configuration and limitations

Scripts that use the worker strategy are off-loaded to a web worker to free up the main thread. The worker strategy is not yet stable and does not yet work with the App Router. To use worker as a strategy, the nextScriptWorkers flag must be enabled in next.config.js: module.exports = { experimental: { nextScriptWorkers: true } }. worker scripts can only currently be used in the pages/ directory.

onLoad prop - Script component

The onLoad prop accepts a function that runs once after the script has finished loading. onLoad does not yet work with Server Components and can only be used in Client Components. onLoad cannot be used with beforeInteractive strategy—consider using onReady instead. onLoad can be used with afterInteractive or lazyOnload strategies.

onLoad prop - example with lodash

Example of using onLoad to execute code after a script loads. In an App Router Client Component: import Script from 'next/script'; add 'use client' directive; use <Script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" onLoad={() => { console.log(_.sample([1, 2, 3, 4])) }} />

onReady prop - Script component

The onReady prop accepts a function that runs after the script has finished loading and every time the component is mounted. This is useful for re-instantiating content after route navigation. onReady does not yet work with Server Components and can only be used in Client Components.

onReady prop - example with Google Maps

Example of using onReady with Google Maps API. In an App Router Client Component: import { useRef } from 'react' and Script from 'next/script'; add 'use client' directive; create mapRef with useRef(); use <Script id="google-maps" src="https://maps.googleapis.com/maps/api/js" onReady={() => { new google.maps.Map(mapRef.current, { center: { lat: -34.397, lng: 150.644 }, zoom: 8 }) }} />

onError prop - Script component

The onError prop accepts a function that handles errors when a script fails to load. The function receives an Error object as a parameter. onError does not yet work with Server Components and can only be used in Client Components. onError cannot be used with the beforeInteractive loading strategy.

onError prop - example error handling

Example of using onError to handle script loading failures. In an App Router Client Component: import Script from 'next/script'; add 'use client' directive; use <Script src="https://example.com/script.js" onError={(e) => { console.error('Script failed to load', e) }} />

Script component version history

Script component version history: v13.0.0 - beforeInteractive and afterInteractive modified to support app router; v12.2.4 - onReady prop added; v12.2.2 - allow next/script with beforeInteractive to be placed in _document; v11.0.0 - next/script introduced.

Link component import and basic usage

The Link component is imported from 'next/link' and is a React component that extends the HTML <a> element to provide prefetching and client-side navigation between routes. It is the primary way to navigate between routes in Next.js. Basic usage: <Link href="/dashboard">Dashboard</Link>

Link props for App Router

The Link component in the App Router accepts the following props: href (String or Object, required), replace (Boolean), scroll (Boolean), prefetch (Boolean or null), onNavigate (Function), transitionTypes (string[]).

Link href prop

The href prop is required and specifies the path or URL to navigate to. It can be a string or an object with pathname and query properties. Example with object: href={{ pathname: '/about', query: { name: 'test' } }}

Link replace prop default behavior

The replace prop defaults to false. When true, next/link will replace the current history state instead of adding a new URL into the browser's history stack.

Link scroll prop default behavior

The scroll prop defaults to true. The default scrolling behavior of Link in Next.js is to maintain scroll position, similar to how browsers handle back and forwards navigation. When you navigate to a new Page, scroll position will stay the same as long as the Page is visible in the viewport. If the Page is not visible in the viewport, Next.js will scroll to the top of the first Page element. When scroll={false}, Next.js will not attempt to scroll to the first Page element.

Link scroll prop implementation details

Next.js checks if scroll: false before managing scroll behavior. If scrolling is enabled, it identifies the relevant DOM node for navigation and inspects each top-level element. All non-scrollable elements and those without rendered HTML are bypassed, including sticky or fixed positioned elements, and non-visible elements such as those calculated with getBoundingClientRect. Next.js then continues through siblings until it identifies a scrollable element that is visible in the viewport.

Link prefetch behavior in App Router

In the App Router, prefetching happens when a Link component enters the user's viewport (initially or through scroll). Next.js prefetches and loads the linked route and its data in the background to improve the performance of client-side navigations. If the prefetched data has expired by the time the user hovers over a Link, Next.js will attempt to prefetch it again. Prefetching is only enabled in production.

Link prefetch prop values in App Router

In the App Router, the prefetch prop accepts: 'auto' or null (default) - prefetch behavior depends on whether the route is static or dynamic. For static routes, the full route will be prefetched (including all its data). For dynamic routes, the partial route down to the nearest segment with a loading.js boundary will be prefetched. true - the full route is prefetched for both static and dynamic routes. With Partial Prefetching enabled, the prefetch includes the App Shell and cached content that depends on the link's URL data. false - prefetching will never happen both on entering the viewport and on hover.

Link prefetch with Partial Prefetching enabled

When Partial Prefetching is enabled (partialPrefetching: true in next.config.js), the default prefetch behavior changes. 'auto' prefetches the per-route App Shell (the route's static and cached content) instead of the full page.

Link onNavigate prop

The onNavigate prop is an event handler called during client-side navigation. The handler receives an event object that includes a preventDefault() method, allowing you to cancel the navigation if needed. onNavigate only executes during SPA navigation and only for client-side and same-origin navigations. With modifier keys (Ctrl/Cmd + Click), onClick executes but onNavigate doesn't since Next.js prevents default navigation for new tabs. External URLs won't trigger onNavigate. Links with the download attribute will work with onClick but not onNavigate since the browser will treat the linked URL as a download.

Link transitionTypes prop

The transitionTypes prop (App Router only) is a list of transition types to apply to the navigation. These types are passed to React.addTransitionType inside the navigation transition, enabling ViewTransition components to apply different animations based on the type of navigation. Example: transitionTypes={['slide-in']}

Link component HTML attributes

HTML tag attributes such as className or target="_blank" can be added to Link as props and will be passed to the underlying <a> element.

Link hash fragment navigation

If you'd like to scroll to a specific id on navigation, you can append your URL with a # hash link or just pass a hash link to the href prop. This is possible since Link renders to an <a> element. Example: <Link href="/dashboard#settings">Settings</Link> outputs <a href="/dashboard#settings">Settings</a>. Next.js will scroll to the Page if it is not visible in the viewport upon navigation.

Link with scroll-padding-top for sticky headers

Because Next.js skips sticky and fixed positioned elements when finding the scroll target, content may end up behind a sticky header after navigation. You can account for a sticky header's height using scroll-padding-top on the scroll container. This is a browser CSS property that offsets scroll-based positioning and applies whenever Next.js uses the native scrollIntoView() API, including hash fragment (#id) navigation. Alternatively, you can use scroll-margin-top on individual target elements instead of setting a global offset.

Link prefetching with Proxy rewrites

When using Proxy for authentication or rewriting, the Link component needs to know both the URL to display and the URL to prefetch to avoid unnecessary fetches to proxy. Use the as prop to specify the displayed URL and href prop for the prefetch URL. Example: <Link as="/dashboard" href={path}>Dashboard</Link>

Link with dynamic route segments example

When linking to dynamic segments, you can use template literals and interpolation to generate a list of links. Example: <Link href={`/blog/${post.slug}`}>{post.title}</Link>

usePathname hook for checking active links

You can use the usePathname() hook to determine if a link is active. For example, to add a class to the active link, you can check if the current pathname matches the href of the link: className={`link ${pathname === '/' ? 'active' : ''}`}

Link component version history

v16.2.0: Add transitionTypes prop. v15.4.0: Add 'auto' as an alias to the default prefetch behavior. v15.3.0: Add onNavigate API. v13.0.0: No longer requires a child <a> tag. v10.0.0: href props pointing to a dynamic route are automatically resolved and no longer require an as prop. v8.0.0: Improved prefetching performance. v1.0.0: next/link introduced.

onNavigate vs onClick handlers

While onClick and onNavigate may seem similar, they serve different purposes. onClick executes for all click events, while onNavigate only runs during client-side navigation. With modifier keys (Ctrl/Cmd + Click), onClick executes but onNavigate doesn't since Next.js prevents default navigation for new tabs. External URLs won't trigger onNavigate since it's only for client-side and same-origin navigations. Links with the download attribute will work with onClick but not onNavigate since the browser will treat the linked URL as a download.

Link blocking navigation with onNavigate example

You can use the onNavigate prop to block navigation when certain conditions are met, such as when a form has unsaved changes. When you need to block navigation across multiple components, React Context provides a clean way to share this blocking state. Use e.preventDefault() to cancel navigation if a condition is met.

Give your agent this brain