useSelectedLayoutSegment return values table
useSelectedLayoutSegment return values by layout and URL:
| Layout | Visited URL | Returned Segment |
| --- | --- | --- |
| app/layout.js | / | null |
| app/layout.js | /dashboard | 'dashboard' |
| app/dashboard/layout.js | /dashboard | null |
| app/dashboard/layout.js | /dashboard/settings | 'settings' |
| app/dashboard/layout.js | /dashboard/analytics | 'analytics' |
| app/dashboard/layout.js | /dashboard/analytics/monthly | 'analytics' |
For catch-all routes:
| Layout | Visited URL | Returned Segment |
| --- | --- | --- |
| app/blog/layout.js | /blog/a/b/c | 'a/b/c' |
useSelectedLayoutSegment with cacheComponents and dynamic routes
When cacheComponents is enabled and you have routes with dynamic params not covered by generateStaticParams, the param is a fallback param not known until request time. The active segment cannot be resolved during prerendering, so useSelectedLayoutSegment suspends. You must wrap the component (or a parent) in a Suspense boundary so its fallback can be rendered during prerendering; otherwise, the build fails. This applies even when the component that calls useSelectedLayoutSegment is itself static.
useSelectedLayoutSegment example - active link component
'use client'
import Link from 'next/link'
import { useSelectedLayoutSegment } from 'next/navigation'
export default function BlogNavLink({
slug,
children,
}: {
slug: string
children: React.ReactNode
}) {
// Navigating to `/blog/hello-world` will return 'hello-world'
// for the selected layout segment
const segment = useSelectedLayoutSegment()
const isActive = slug === segment
return (
<Link
href={`/blog/${slug}`}
// Change style depending on whether the link is active
style={{ fontWeight: isActive ? 'bold' : 'normal' }}
>
{children}
</Link>
)
}
This example shows how to create an active link component that changes style depending on whether the link matches the active segment. The component is imported into a parent Layout (Server Component).
useSelectedLayoutSegment hook
useSelectedLayoutSegment is a Client Component hook imported from 'next/navigation' that lets you read the active route segment one level below the Layout it is called from. It returns a string of the active segment or null if one doesn't exist. It is useful for navigation UI, such as tabs inside a parent layout that change style depending on the active child segment.
useSelectedLayoutSegment is a Client Component hook
useSelectedLayoutSegment is a Client Component hook, not a Server Component hook. Since Layouts are Server Components by default, useSelectedLayoutSegment is usually called via a Client Component that is imported into a Layout, not directly in the Layout itself.
useSelectedLayoutSegment only returns one level down
useSelectedLayoutSegment returns only the segment one level down from the Layout it is called from. To return all active segments, use useSelectedLayoutSegments instead.
userAgent isBot property
The isBot property is a boolean indicating whether the request comes from a known bot.
userAgent browser object
The browser object contains: name (string representing browser name, or undefined if not identifiable) and version (string representing browser version, or undefined).
userAgent TypeScript example with device detection
Example showing how to use userAgent to detect device type and set a viewport parameter: import { NextRequest, NextResponse, userAgent } from 'next/server'; export function proxy(request: NextRequest) { const url = request.nextUrl; const { device } = userAgent(request); const viewport = device.type || 'desktop'; url.searchParams.set('viewport', viewport); return NextResponse.rewrite(url); }
userAgent device object
The device object contains: model (string representing device model, or undefined), type (string representing device type such as console, mobile, tablet, smarttv, wearable, embedded, or undefined), and vendor (string representing device vendor, or undefined).
userAgent engine object
The engine object contains: name (string representing engine name with possible values: Amaya, Blink, EdgeHTML, Flow, Gecko, Goanna, iCab, KHTML, Links, Lynx, NetFront, NetSurf, Presto, Tasman, Trident, w3m, WebKit, or undefined) and version (string representing engine version, or undefined).
userAgent cpu object
The cpu object contains: architecture (string representing CPU architecture with possible values: 68k, amd64, arm, arm64, armhf, avr, ia32, ia64, irix, irix64, mips, mips64, pa-risc, ppc, sparc, sparc64, or undefined).
userAgent function import and basic usage
The userAgent helper is imported from 'next/server' and extends the Web Request API with additional properties and methods. It accepts a NextRequest object and returns an object with properties for device, browser, engine, os, cpu, and isBot.
userAgent device types
The device.type property returned by userAgent can be: 'mobile', 'tablet', 'console', 'smarttv', 'wearable', 'embedded', or undefined for desktop browsers.
userAgent os object
The os object contains: name (string representing OS name, or undefined) and version (string representing OS version, or undefined).
useSelectedLayoutSegments with cacheComponents enabled
When cacheComponents is enabled, useSelectedLayoutSegments may require a Suspense boundary depending on whether the active segments can be resolved during prerendering. For static routes and routes with generateStaticParams, all route segments are known at build time and useSelectedLayoutSegments resolves on the server without requiring a Suspense boundary. For routes with dynamic params not covered by generateStaticParams, the param is a fallback param not known until request time, so useSelectedLayoutSegments suspends and requires a Suspense boundary.
useSelectedLayoutSegments hook overview
useSelectedLayoutSegments is a Client Component hook that lets you read the active route segments below the Layout it is called from. It is useful for creating UI in parent Layouts that need knowledge of active child segments such as breadcrumbs.
useSelectedLayoutSegments version history
useSelectedLayoutSegments was introduced in v13.0.0.
useSelectedLayoutSegments import and basic usage
Import useSelectedLayoutSegments from 'next/navigation'. Call it in a Client Component to get an array of active segments: const segments = useSelectedLayoutSegments(). Since it is a Client Component hook and Layouts are Server Components by default, it is usually called via a Client Component that is imported into a Layout.
useSelectedLayoutSegments example
'use client'
import { useSelectedLayoutSegments } from 'next/navigation'
export default function ExampleClientComponent() {
const segments = useSelectedLayoutSegments()
return (
<ul>
{segments.map((segment, index) => (
<li key={index}>{segment}</li>
))}
</ul>
)
}
This example shows a Client Component that reads active segments below its layout and renders them in a list.
useSelectedLayoutSegments return value
useSelectedLayoutSegments returns an array of strings containing the active segments one level down from the layout the hook was called from. It returns an empty array if no segments exist below the layout.
useSelectedLayoutSegments with parallelRoutesKey parameter
useSelectedLayoutSegments optionally accepts a parallelRoutesKey parameter, which allows you to read the active route segment within that slot.
useSelectedLayoutSegments return values by route
The returned segments depend on which layout the hook is called from and the current URL. From app/layout.js at /, returns []. From app/layout.js at /dashboard, returns ['dashboard']. From app/layout.js at /dashboard/settings, returns ['dashboard', 'settings']. From app/dashboard/layout.js at /dashboard, returns []. From app/dashboard/layout.js at /dashboard/settings, returns ['settings'].
useSelectedLayoutSegments with catch-all routes
For catch-all routes ([...slug]), all matched path segments are returned as a single joined string within the array. From app/layout.js at /blog/a/b/c, returns ['blog', 'a/b/c']. From app/blog/layout.js at /blog/a/b/c, returns ['a/b/c'].
useSelectedLayoutSegments includes Route Groups in returned segments
The returned segments include Route Groups, which you might not want to include in your UI. You can use the filter array method to remove items that start with a bracket to exclude Route Groups.
useSelectedLayoutSegments suspends on unknown dynamic params
This applies even when the component that calls useSelectedLayoutSegments is itself static. For example, a breadcrumb component rendered in a parent layout suspends on any page below it that has an unknown dynamic param. To keep the rest of the layout prerendered, wrap the component that calls useSelectedLayoutSegments (or a parent) in a Suspense boundary with a fallback.
NextRequest.cookies.clear()
Remove all cookies from the request. Example: request.cookies.clear().
NextRequest.cookies.delete(name)
Delete a cookie from the request by name. Returns true if the cookie was deleted, false if nothing was deleted. Example: request.cookies.delete('experiments').
NextRequest.cookies.has(name)
Check if a cookie exists on the request by name. Returns true if the cookie exists, false if it does not. Example: request.cookies.has('experiments').
NextRequest.nextUrl extends URL API
NextRequest.nextUrl extends the native URL API with additional convenience methods and Next.js specific properties. It provides access to pathname, searchParams, and other URL-related information.
NextRequest.nextUrl properties in App Router
In the App Router, NextRequest.nextUrl has the following properties: basePath (string) - the base path of the URL; buildId (string | undefined) - the build identifier, can be customized; pathname (string) - the pathname of the URL; searchParams (Object) - the search parameters of the URL.
NextRequest.nextUrl properties in Pages Router
In the Pages Router, NextRequest.nextUrl has the following properties: basePath (string) - the base path of the URL; buildId (string | undefined) - the build identifier, can be customized; defaultLocale (string | undefined) - the default locale for internationalization; domainLocale (object) with defaultLocale (string) - default locale within a domain, domain (string) - domain associated with a specific locale, http (boolean | undefined) - indicates if domain uses HTTP; locales (string[] | undefined) - array of available locales; locale (string | undefined) - the currently active locale; url (URL) - the URL object.
NextRequest.nextUrl.pathname example
Given a request to /home, request.nextUrl.pathname returns /home.
NextRequest.nextUrl.searchParams example
Given a request to /home?name=lee, request.nextUrl.searchParams returns { 'name': 'lee' }.
NextRequest v15.0.0 ip and geo removed
In Next.js v15.0.0, the ip and geo properties were removed from NextRequest.
App Router internationalization not in nextUrl
Internationalization properties from the Pages Router (defaultLocale, domainLocale, locales, locale) are not available in the App Router's NextRequest.nextUrl. The App Router uses a different internationalization approach.
NextRequest extends Web Request API
NextRequest extends the Web Request API with additional convenience methods for handling HTTP requests in Next.js.
NextRequest.cookies.set(name, value)
Set a cookie on the request with a given name and value. This sets a Set-Cookie header on the request. Example: request.cookies.set('show-banner', 'false') sets a cookie named show-banner with value false.
NextRequest.cookies.get(name)
Get a cookie by name from the request. Returns the cookie value if found, or undefined if not found. If multiple cookies with the same name exist, returns the first one. Example: request.cookies.get('show-banner') returns { name: 'show-banner', value: 'false', Path: '/home' }.
NextRequest.cookies.getAll()
Get all cookie values from the request. Can be called with a cookie name to return all values of that cookie, or without arguments to return all cookies on the request. Example: request.cookies.getAll('experiments') returns an array of all cookies named experiments, or request.cookies.getAll() returns all cookies.
headers is a request-time API that opts into dynamic rendering
headers is a request-time API whose returned values cannot be known ahead of time. Using it in a route will opt that route into dynamic rendering.
headers returns read-only Web Headers object
The headers function returns a read-only Web Headers object with the following methods: Headers.entries() returns an iterator of all key/value pairs; Headers.forEach() executes a function for each key/value pair; Headers.get() returns a string of all values for a header with a given name; Headers.has() returns a boolean stating whether the object contains a certain header; Headers.keys() returns an iterator of all keys; Headers.values() returns an iterator of all values of the key/value pairs.
headers is async and requires await or React use
headers is an asynchronous function that returns a promise. You must use async/await or React's use function to access the headers. In Next.js 14 and earlier, headers was synchronous, and while you can still access it synchronously in Next.js 15 for backwards compatibility, this behavior will be deprecated in the future.
headers with Cache Components prevents prerendering outside Suspense
With Cache Components, calling headers() outside of a Suspense boundary prevents the route from being prerendered. See the 'Next.js encountered runtime data during prerendering' message for fix options.
headers function example with authorization
import { headers } from 'next/headers'
export default async function Page() {
const authorization = (await headers()).get('authorization')
const res = await fetch('...', {
headers: { authorization }, // Forward the authorization header
})
const user = await res.json()
return <h1>{user.name}</h1>
}
This example shows how to read the authorization header and forward it in a fetch request.
headers basic usage example
import { headers } from 'next/headers'
export default async function Page() {
const headersList = await headers()
const userAgent = headersList.get('user-agent')
}
This example shows the basic usage of the headers function to read the user-agent header.
headers version history
headers was introduced in v13.0.0. In v15.0.0-RC, headers became an async function, and a codemod is available to help with upgrading.
headers is read-only and cannot set or delete
Since headers is read-only, you cannot set or delete the outgoing request headers.
headers function overview
headers is an async function that allows you to read HTTP incoming request headers from a Server Component. It must be imported from 'next/headers'. The function does not take any parameters.
generateStaticParams placeholder param for Cache Components
If you don't know the actual param values at build time when using Cache Components, you can return a placeholder param (e.g., [{ slug: '__placeholder__' }]) for validation, then handle it in your page with notFound(). However, this prevents build time validation from working effectively and may cause runtime errors.
generateStaticParams function purpose
The generateStaticParams function statically generates routes at build time instead of on-demand at request time, in combination with dynamic route segments.
generateStaticParams compatible file types
generateStaticParams can be used in Pages (page.tsx/page.js), Layouts (layout.tsx/layout.js), and Route Handlers (route.ts/route.js).
generateStaticParams return type for multiple dynamic segments
For a route like /products/[category]/[product], generateStaticParams should return an array of objects with type { category: string, product: string }[].
generateStaticParams return type for catch-all segment
For a route like /products/[...slug], generateStaticParams should return an array of objects with type { slug: string[] }[].
generateStaticParams parameters
generateStaticParams accepts an optional params argument containing the populated params from the parent generateStaticParams, which can be used to generate the params in a child segment.
generateStaticParams behavior during next dev
During next dev, generateStaticParams will be called when you navigate to a route.
generateStaticParams behavior during next build
During next build, generateStaticParams runs before the corresponding Layouts or Pages are generated.
generateStaticParams behavior during revalidation (ISR)
During revalidation (ISR), generateStaticParams will not be called again.
generateStaticParams replaces getStaticPaths
generateStaticParams replaces the getStaticPaths function from the Pages Router in the App Router.
dynamicParams segment config option
The dynamicParams segment config option controls what happens when a dynamic segment is visited that was not generated with generateStaticParams. When set to false, only paths provided by generateStaticParams will be served, and unspecified routes will 404.