id stringlengths 14 15 | text stringlengths 49 1.09k | source stringlengths 46 101 |
|---|---|---|
47cb3dfffc9e-0 | Defining Routes
We recommend reading the Routing Fundamentals page before continuing.
This page will guide you through how to define and organize routes in your Next.js application.
Creating Routes
Next.js uses a file-system based router where folders are used to define routes.
Each folder represents a route segment th... | https://nextjs.org/docs/app/building-your-application/routing/defining-routes |
47cb3dfffc9e-1 | Creating UI
Special file conventions are used to create UI for each route segment. The most common are pages to show UI unique to a route, and layouts to show UI that is shared across multiple routes.
For example, to create your first page, add a page.js file inside the app directory and export a React component:
app/p... | https://nextjs.org/docs/app/building-your-application/routing/defining-routes |
53efeaec8ff7-0 | Pages and Layouts
We recommend reading the Routing Fundamentals and Defining Routes pages before continuing.
The App Router inside Next.js 13 introduced new file conventions to easily create pages, shared layouts, and templates. This page will guide you through how to use these special files in your Next.js application... | https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts |
53efeaec8ff7-1 | export default function Page() {
return <h1>Hello, Dashboard Page!</h1>
}
Good to know:
A page is always the leaf of the route subtree.
.js, .jsx, or .tsx file extensions can be used for Pages.
A page.js file is required to make a route segment publicly accessible.
Pages are Server Components by default but can be se... | https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts |
53efeaec8ff7-2 | app/dashboard/layout.tsx export default function DashboardLayout({
children, // will be a page or nested layout
}: {
children: React.ReactNode
}) {
return (
<section>
{/* Include shared UI here e.g. a header or sidebar */}
<nav></nav>
{children}
</section>
)
}
Good to know:
The top-m... | https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts |
53efeaec8ff7-3 | You can use Route Groups to opt specific route segments in and out of shared layouts.
Layouts are Server Components by default but can be set to a Client Component.
Layouts can fetch data. View the Data Fetching section for more information.
Passing data between a parent layout and its children is not possible. However... | https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts |
53efeaec8ff7-4 | Root Layout (Required)
The root layout is defined at the top level of the app directory and applies to all routes. This layout enables you to modify the initial HTML returned from the server.
app/layout.tsx export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang=... | https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts |
53efeaec8ff7-5 | The root layout is a Server Component by default and can not be set to a Client Component.
Migrating from the pages directory: The root layout replaces the _app.js and _document.js files. View the migration guide.
Nesting Layouts
Layouts defined inside a folder (e.g. app/dashboard/layout.js) apply to specific route seg... | https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts |
53efeaec8ff7-6 | Only the root layout can contain <html> and <body> tags.
If you were to combine the two layouts above, the root layout (app/layout.js) would wrap the dashboard layout (app/dashboard/layout.js), which would wrap route segments inside app/dashboard/*.
The two layouts would be nested as such:
You can use Route Groups to o... | https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts |
53efeaec8ff7-7 | Enter/exit animations using CSS or animation libraries.
Features that rely on useEffect (e.g logging page views) and useState (e.g a per-page feedback form).
To change the default framework behavior. For example, Suspense Boundaries inside layouts only show the fallback the first time the Layout is loaded and not when ... | https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts |
53efeaec8ff7-8 | Output <Layout>
{/* Note that the template is given a unique key. */}
<Template key={routeParam}>{children}</Template>
</Layout>
Modifying <head>
In the app directory, you can modify the <head> HTML elements such as title and meta using the built-in SEO support.
Metadata can be defined by exporting a metadata objec... | https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts |
53efeaec8ff7-9 | Learn more about available metadata options in the API reference. | https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts |
7259cc670011-0 | Linking and NavigatingThe Next.js router uses server-centric routing with client-side navigation. It supports instant loading states and concurrent rendering. This means navigation maintains client-side state, avoids expensive re-renders, is interruptible, and doesn't cause race conditions.
There are two ways to naviga... | https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating |
7259cc670011-1 | return <Link href="/dashboard">Dashboard</Link>
}
There are optional props you can pass to <Link>. See the API reference for more information.
Examples
Linking to Dynamic Segments
When linking to dynamic segments, you can use template literals and interpolation to generate a list of links. For example, to generate a li... | https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating |
7259cc670011-2 | ))}
</ul>
)
}
Checking Active Links
You can use usePathname() 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:
app/ui/Navigation.js 'use client'
import { usePathname } from 'next/navigation'
import Link from 'ne... | https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating |
7259cc670011-3 | >
{link.name}
</Link>
)
})}
</>
)
}
Scrolling to an id
The default behavior of <Link> is to scroll to the top of the route segment that has changed. When there is an id defined in href, it will scroll to the specific id, similarly to a normal <a> tag.
useRouter() Hook
The useRo... | https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating |
7259cc670011-4 | Dashboard
</button>
)
}
The useRouter provides methods such as push(), refresh(), and more. See the API reference for more information.
Recommendation: Use the <Link> component to navigate between routes unless you have a specific requirement for using useRouter.
How Navigation Works
A route transition is initiat... | https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating |
7259cc670011-5 | If created, loading UI is shown from the server while the payload is being fetched.
The router uses the cached or fresh payload to render the new segments on the client.
Client-side Caching of Rendered Server Components
Good to know: This client-side cache is different from the server-side Next.js HTTP cache.
The new r... | https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating |
7259cc670011-6 | Invalidating the Cache
Server Actions can be used to revalidate data on-demand by path (revalidatePath) or by cache tag (revalidateTag).
Prefetching
Prefetching is a way to preload a route in the background before it's visited. The rendered result of prefetched routes is added to the router's client-side cache. This ma... | https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating |
7259cc670011-7 | If the route is dynamic, the payload from the first shared layout down until the first loading.js file is prefetched. This reduces the cost of prefetching the whole route dynamically and allows instant loading states for dynamic routes.
Good to know:
Prefetching is only enabled in production.
Prefetching can be disable... | https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating |
7259cc670011-8 | Navigating from /dashboard/team-red/* to /dashboard/team-red/* will be a soft navigation.
Navigating from /dashboard/team-red/* to /dashboard/team-blue/* will be a hard navigation.
Hard Navigation
On navigation, the cache is invalidated and the server refetches data and re-renders the changed segments.
Back/Forward Nav... | https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating |
34bf98e60183-0 | Route GroupsIn the app directory, nested folders are normally mapped to URL paths. However, you can mark a folder as a Route Group to prevent the folder from being included in the route's URL path.
This allows you to organize your route segments and project files into logical groups without affecting the URL path struc... | https://nextjs.org/docs/app/building-your-application/routing/route-groups |
34bf98e60183-1 | Even though routes inside (marketing) and (shop) share the same URL hierarchy, you can create a different layout for each group by adding a layout.js file inside their folders.
Opting specific segments into a layout
To opt specific routes into a layout, create a new route group (e.g. (shop)) and move the routes that sh... | https://nextjs.org/docs/app/building-your-application/routing/route-groups |
34bf98e60183-2 | Good to know:
The naming of route groups has no special significance other than for organization. They do not affect the URL path.
Routes that include a route group should not resolve to the same URL path as other routes. For example, since route groups don't affect URL structure, (marketing)/about/page.js and (shop)/a... | https://nextjs.org/docs/app/building-your-application/routing/route-groups |
45cae5895537-0 | Dynamic RoutesWhen you don't know the exact segment names ahead of time and want to create routes from dynamic data, you can use Dynamic Segments that are filled in at request time or prerendered at build time.
Convention
A Dynamic Segment can be created by wrapping a folder's name in square brackets: [folderName]. For... | https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes |
45cae5895537-1 | return <div>My Post: {params.slug}</div>
}
RouteExample URLparamsapp/blog/[slug]/page.js/blog/a{ slug: 'a' }app/blog/[slug]/page.js/blog/b{ slug: 'b' }app/blog/[slug]/page.js/blog/c{ slug: 'c' }
See the generateStaticParams() page to learn how to generate the params for the segment.
Good to know: Dynamic Segments are e... | https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes |
45cae5895537-2 | return posts.map((post) => ({
slug: post.slug,
}))
}
The primary benefit of the generateStaticParams function is its smart retrieval of data. If content is fetched within the generateStaticParams function using a fetch request, the requests are automatically deduplicated. This means a fetch request with the same ... | https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes |
45cae5895537-3 | RouteExample URLparamsapp/shop/[...slug]/page.js/shop/a{ slug: ['a'] }app/shop/[...slug]/page.js/shop/a/b{ slug: ['a', 'b'] }app/shop/[...slug]/page.js/shop/a/b/c{ slug: ['a', 'b', 'c'] }
Optional Catch-all Segments
Catch-all Segments can be made optional by including the parameter in double square brackets: [[...folde... | https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes |
45cae5895537-4 | RouteExample URLparamsapp/shop/[[...slug]]/page.js/shop{}app/shop/[[...slug]]/page.js/shop/a{ slug: ['a'] }app/shop/[[...slug]]/page.js/shop/a/b{ slug: ['a', 'b'] }app/shop/[[...slug]]/page.js/shop/a/b/c{ slug: ['a', 'b', 'c'] }
TypeScript
When using TypeScript, you can add types for params depending on your configured... | https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes |
45cae5895537-5 | Good to know: This may be done automatically by the TypeScript plugin in the future. | https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes |
4cb9ccf64b03-0 | Loading UI and StreamingThe special file loading.js helps you create meaningful Loading UI with React Suspense. With this convention, you can show an instant loading state from the server while the content of a route segment loads. The new content is automatically swapped in once rendering is complete.
Instant Loading ... | https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming |
4cb9ccf64b03-1 | return <LoadingSkeleton />
}
In the same folder, loading.js will be nested inside layout.js. It will automatically wrap the page.js file and any children below in a <Suspense> boundary.
Good to know:
Navigation is immediate, even with server-centric routing.
Navigation is interruptible, meaning changing routes does not... | https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming |
4cb9ccf64b03-2 | What is Streaming?
To learn how Streaming works in React and Next.js, it's helpful to understand Server-Side Rendering (SSR) and its limitations.
With SSR, there's a series of steps that need to be completed before a user can see and interact with a page:
First, all data for a given page is fetched on the server.
The s... | https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming |
4cb9ccf64b03-3 | SSR with React and Next.js helps improve the perceived loading performance by showing a non-interactive page to the user as soon as possible.
However, it can still be slow as all data fetching on server needs to be completed before the page can be shown to the user.
Streaming allows you to break down the page's HTML in... | https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming |
4cb9ccf64b03-4 | Streaming is particularly beneficial when you want to prevent long data requests from blocking the page from rendering as it can reduce the Time To First Byte (TTFB) and First Contentful Paint (FCP). It also helps improve Time to Interactive (TTI), especially on slower devices.
Example
<Suspense> works by wrapping a co... | https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming |
4cb9ccf64b03-5 | <Suspense fallback={<p>Loading weather...</p>}>
<Weather />
</Suspense>
</section>
)
}
By using Suspense, you get the benefits of:
Streaming Server Rendering - Progressively rendering HTML from the server to the client.
Selective Hydration - React prioritizes what components to make interactive firs... | https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming |
5829a47ac78e-0 | Error HandlingThe error.js file convention allows you to gracefully handle unexpected runtime errors in nested routes.
Automatically wrap a route segment and its nested children in a React Error Boundary.
Create error UI tailored to specific segments using the file-system hierarchy to adjust granularity.
Isolate errors... | https://nextjs.org/docs/app/building-your-application/routing/error-handling |
5829a47ac78e-1 | console.error(error)
}, [error])
return (
<div>
<h2>Something went wrong!</h2>
<button
onClick={
// Attempt to recover by trying to re-render the segment
() => reset()
}
>
Try again
</button>
</div>
)
}
How error.js Works
error.js autom... | https://nextjs.org/docs/app/building-your-application/routing/error-handling |
5829a47ac78e-2 | Recovering From Errors
The cause of an error can sometimes be temporary. In these cases, simply trying again might resolve the issue.
An error component can use the reset() function to prompt the user to attempt to recover from the error. When executed, the function will try to re-render the Error boundary's contents. ... | https://nextjs.org/docs/app/building-your-application/routing/error-handling |
5829a47ac78e-3 | }
Nested Routes
React components created through special files are rendered in a specific nested hierarchy.
For example, a nested route with two segments that both include layout.js and error.js files are rendered in the following simplified component hierarchy:
The nested component hierarchy has implications for the b... | https://nextjs.org/docs/app/building-your-application/routing/error-handling |
5829a47ac78e-4 | Handling Errors in Layouts
error.js boundaries do not catch errors thrown in layout.js or template.js components of the same segment. This intentional hierarchy keeps important UI that is shared between sibling routes (such as navigation) visible and functional when an error occurs.
To handle errors within a specific l... | https://nextjs.org/docs/app/building-your-application/routing/error-handling |
5829a47ac78e-5 | Unlike the root error.js, the global-error.js error boundary wraps the entire application, and its fallback component replaces the root layout when active. Because of this, it is important to note that global-error.js must define its own <html> and <body> tags.
global-error.js is the least granular error UI and can be ... | https://nextjs.org/docs/app/building-your-application/routing/error-handling |
5829a47ac78e-6 | reset: () => void
}) {
return (
<html>
<body>
<h2>Something went wrong!</h2>
<button onClick={() => reset()}>Try again</button>
</body>
</html>
)
}
Handling Server Errors
If an error is thrown inside a Server Component, Next.js will forward an Error object (stripped of sensitive ... | https://nextjs.org/docs/app/building-your-application/routing/error-handling |
5829a47ac78e-7 | During development, the Error object forwarded to the client will be serialized and include the message of the original error for easier debugging. | https://nextjs.org/docs/app/building-your-application/routing/error-handling |
04c394e53e49-0 | Parallel RoutesParallel Routing allows you to simultaneously or conditionally render one or more pages in the same layout. For highly dynamic sections of an app, such as dashboards and feeds on social sites, Parallel Routing can be used to implement complex routing patterns.
For example, you can simultaneously render t... | https://nextjs.org/docs/app/building-your-application/routing/parallel-routes |
04c394e53e49-1 | For example, the following file structure defines two explicit slots: @analytics and @team.
The folder structure above means that the component in app/layout.js now accepts the @analytics and @team slots props, and can render them in parallel alongside the children prop:
app/layout.tsx export default function Layout(pr... | https://nextjs.org/docs/app/building-your-application/routing/parallel-routes |
04c394e53e49-2 | Unmatched Routes
By default, the content rendered within a slot will match the current URL.
In the case of an unmatched slot, the content that Next.js renders differs based on the routing technique and folder structure.
default.js
You can define a default.js file to render as a fallback when Next.js cannot recover a sl... | https://nextjs.org/docs/app/building-your-application/routing/parallel-routes |
04c394e53e49-3 | Soft Navigation
On a soft navigation - Next.js will render the slot's previously active state, even if it doesn't match the current URL.
Hard Navigation
On a hard navigation - a navigation that requires a full page reload - Next.js will first try to render the unmatched slot's default.js file. If that's not available, ... | https://nextjs.org/docs/app/building-your-application/routing/parallel-routes |
04c394e53e49-4 | }) {
const loginSegments = useSelectedLayoutSegment('authModal')
// ...
}
When a user navigates to @authModal/login, or /login in the URL bar, loginSegments will be equal to the string "login".
Examples
Modals
Parallel Routing can be used to render modals.
The @authModal slot renders a <Modal> component that can be... | https://nextjs.org/docs/app/building-your-application/routing/parallel-routes |
04c394e53e49-5 | return (
<Modal>
<h1>Login</h1>
{/* ... */}
</Modal>
)
}
To ensure that the contents of the modal don't get rendered when it's not active, you can create a default.js file that returns null.
app/@authModal/default.tsx export default function Default() {
return null
}
Dismissing a modal
If a moda... | https://nextjs.org/docs/app/building-your-application/routing/parallel-routes |
04c394e53e49-6 | const router = useRouter()
return (
<Modal>
<span onClick={() => router.back()}>Close modal</span>
<h1>Login</h1>
...
</Modal>
)
}
More information on modals is covered in the Intercepting Routes section.
If you want to navigate elsewhere and dismiss a modal, you can also use a catch-all r... | https://nextjs.org/docs/app/building-your-application/routing/parallel-routes |
04c394e53e49-7 | dashboard,
login,
}: {
dashboard: React.ReactNode
login: React.ReactNode
}) {
const isLoggedIn = getUser()
return isLoggedIn ? dashboard : login
} | https://nextjs.org/docs/app/building-your-application/routing/parallel-routes |
01dc1cccd23e-0 | Intercepting RoutesIntercepting routes allows you to load a route within the current layout while keeping the context for the current page. This routing paradigm can be useful when you want to "intercept" a certain route to show a different route.
For example, when clicking on a photo from within a feed, a modal overla... | https://nextjs.org/docs/app/building-your-application/routing/intercepting-routes |
01dc1cccd23e-1 | (.) to match segments on the same level
(..) to match segments one level above
(..)(..) to match segments two levels above
(...) to match segments from the root app directory
For example, you can intercept the photo segment from within the feed segment by creating a (..)photo directory.
Note that the (..) convention is... | https://nextjs.org/docs/app/building-your-application/routing/intercepting-routes |
01dc1cccd23e-2 | Reopen the modal on forwards navigation
In the above example, the path to the photo segment can use the (..) matcher since @modal is a slot and not a segment. This means that the photo route is only one segment level higher, despite being two file-system levels higher.
Other examples could include opening a login modal... | https://nextjs.org/docs/app/building-your-application/routing/intercepting-routes |
e771e7a1daa6-0 | Route HandlersRoute Handlers allow you to create custom request handlers for a given route using the Web Request and Response APIs.
Good to know: Route Handlers are only available inside the app directory. They are the equivalent of API Routes inside the pages directory meaning you do not need to use API Routes and Rou... | https://nextjs.org/docs/app/building-your-application/routing/router-handlers |
e771e7a1daa6-1 | Extended NextRequest and NextResponse APIs
In addition to supporting native Request and Response. Next.js extends them with
NextRequest and NextResponse to provide convenient helpers for advanced use cases.
Behavior
Static Route Handlers
Route Handlers are statically evaluated by default when using the GET method with ... | https://nextjs.org/docs/app/building-your-application/routing/router-handlers |
e771e7a1daa6-2 | Dynamic Route Handlers
Route handlers are evaluated dynamically when:
Using the Request object with the GET method.
Using any of the other HTTP methods.
Using Dynamic Functions like cookies and headers.
The Segment Config Options manually specifies dynamic mode.
For example:
app/products/api/route.ts import { NextRespo... | https://nextjs.org/docs/app/building-your-application/routing/router-handlers |
e771e7a1daa6-3 | }
Similarly, the POST method will cause the Route Handler to be evaluated dynamically.
app/items/route.ts import { NextResponse } from 'next/server'
export async function POST() {
const res = await fetch('https://data.mongodb-api.com/...', {
method: 'POST',
headers: {
'Content-Type': 'application/json... | https://nextjs.org/docs/app/building-your-application/routing/router-handlers |
e771e7a1daa6-4 | Route Resolution
You can consider a route the lowest level routing primitive.
They do not participate in layouts or client-side navigations like page.
There cannot be a route.js file at the same route as page.js.
PageRouteResultapp/page.jsapp/route.js Conflictapp/page.jsapp/api/route.js Validapp/[user]/page.jsapp/api/r... | https://nextjs.org/docs/app/building-your-application/routing/router-handlers |
e771e7a1daa6-5 | You can revalidate static data fetches using the next.revalidate option:
app/items/route.ts import { NextResponse } from 'next/server'
export async function GET() {
const res = await fetch('https://data.mongodb-api.com/...', {
next: { revalidate: 60 }, // Revalidate every 60 seconds
})
const data = await re... | https://nextjs.org/docs/app/building-your-application/routing/router-handlers |
e771e7a1daa6-6 | This cookies instance is read-only. To set cookies, you need to return a new Response using the Set-Cookie header.
app/api/route.ts import { cookies } from 'next/headers'
export async function GET(request: Request) {
const cookieStore = cookies()
const token = cookieStore.get('token')
return new Response('Hel... | https://nextjs.org/docs/app/building-your-application/routing/router-handlers |
e771e7a1daa6-7 | const token = request.cookies.get('token')
}
Headers
You can read headers with headers from next/headers. This server function can be called directly in a Route Handler, or nested inside of another function.
This headers instance is read-only. To set headers, you need to return a new Response with new headers.
app/api/... | https://nextjs.org/docs/app/building-your-application/routing/router-handlers |
e771e7a1daa6-8 | app/api/route.ts import { type NextRequest } from 'next/server'
export async function GET(request: NextRequest) {
const requestHeaders = new Headers(request.headers)
}
Redirects
app/api/route.ts import { redirect } from 'next/navigation'
export async function GET(request: Request) {
redirect('https://nextjs.org... | https://nextjs.org/docs/app/building-your-application/routing/router-handlers |
e771e7a1daa6-9 | const slug = params.slug // 'a', 'b', or 'c'
}
RouteExample URLparamsapp/items/[slug]/route.js/items/a{ slug: 'a' }app/items/[slug]/route.js/items/b{ slug: 'b' }app/items/[slug]/route.js/items/c{ slug: 'c' }
Streaming
Streaming is commonly used in combination with Large Language Models (LLMs), such an OpenAI, for AI-ge... | https://nextjs.org/docs/app/building-your-application/routing/router-handlers |
e771e7a1daa6-10 | export const runtime = 'edge'
export async function POST(req: Request) {
const { prompt } = await req.json()
const response = await openai.createCompletion({
model: 'text-davinci-003',
stream: true,
temperature: 0.6,
prompt: 'What is Next.js?',
})
const stream = OpenAIStream(response)
retu... | https://nextjs.org/docs/app/building-your-application/routing/router-handlers |
e771e7a1daa6-11 | const { value, done } = await iterator.next()
if (done) {
controller.close()
} else {
controller.enqueue(value)
}
},
})
}
function sleep(time: number) {
return new Promise((resolve) => {
setTimeout(resolve, time)
})
}
const encoder = new TextEncoder()
async functi... | https://nextjs.org/docs/app/building-your-application/routing/router-handlers |
e771e7a1daa6-12 | return new Response(stream)
}
Request Body
You can read the Request body using the standard Web API methods:
app/items/route.ts import { NextResponse } from 'next/server'
export async function POST(request: Request) {
const res = await request.json()
return NextResponse.json({ res })
}
Request Body FormData
You c... | https://nextjs.org/docs/app/building-your-application/routing/router-handlers |
e771e7a1daa6-13 | CORS
You can set CORS headers on a Response using the standard Web API methods:
app/api/route.ts export async function GET(request: Request) {
return new Response('Hello, Next.js!', {
status: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELET... | https://nextjs.org/docs/app/building-your-application/routing/router-handlers |
e771e7a1daa6-14 | export const runtime = 'edge' // 'nodejs' is the default
Non-UI Responses
You can use Route Handlers to return non-UI content. Note that sitemap.xml, robots.txt, app icons, and open graph images all have built-in support.
app/rss.xml/route.ts export async function GET() {
return new Response(`<?xml version="1.0" enco... | https://nextjs.org/docs/app/building-your-application/routing/router-handlers |
e771e7a1daa6-15 | app/items/route.ts export const dynamic = 'auto'
export const dynamicParams = true
export const revalidate = false
export const fetchCache = 'auto'
export const runtime = 'nodejs'
export const preferredRegion = 'auto'
See the API reference for more details. | https://nextjs.org/docs/app/building-your-application/routing/router-handlers |
baccacb331d2-0 | Middleware
Middleware allows you to run code before a request is completed. Then, based on the incoming request, you can modify the response by rewriting, redirecting, modifying the request or response headers, or responding directly.
Middleware runs before cached content and routes are matched. See Matching Paths for ... | https://nextjs.org/docs/app/building-your-application/routing/middleware |
baccacb331d2-1 | // See "Matching Paths" below to learn more
export const config = {
matcher: '/about/:path*',
}
Matching Paths
Middleware will be invoked for every route in your project. The following is the execution order:
headers from next.config.js
redirects from next.config.js
Middleware (rewrites, redirects, etc.)
beforeFiles ... | https://nextjs.org/docs/app/building-your-application/routing/middleware |
baccacb331d2-2 | middleware.js export const config = {
matcher: '/about/:path*',
}
You can match a single path or multiple paths with an array syntax:
middleware.js export const config = {
matcher: ['/about/:path*', '/dashboard/:path*'],
}
The matcher config allows full regex so matching like negative lookaheads or character matchi... | https://nextjs.org/docs/app/building-your-application/routing/middleware |
baccacb331d2-3 | ],
}
Good to know: The matcher values need to be constants so they can be statically analyzed at build-time. Dynamic values such as variables will be ignored.
Configured matchers:
MUST start with /
Can include named parameters: /about/:path matches /about/a and /about/b but not /about/a/c
Can have modifiers on named pa... | https://nextjs.org/docs/app/building-your-application/routing/middleware |
baccacb331d2-4 | Conditional Statements
middleware.ts import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
if (request.nextUrl.pathname.startsWith('/about')) {
return NextResponse.rewrite(new URL('/about-2', request.url))
}
if (request... | https://nextjs.org/docs/app/building-your-application/routing/middleware |
baccacb331d2-5 | rewrite to a route (Page or Route Handler) that produces a response
return a NextResponse directly. See Producing a Response
Using Cookies
Cookies are regular headers. On a Request, they are stored in the Cookie header. On a Response they are in the Set-Cookie header. Next.js provides a convenient way to access and man... | https://nextjs.org/docs/app/building-your-application/routing/middleware |
baccacb331d2-6 | // Getting cookies from the request using the `RequestCookies` API
let cookie = request.cookies.get('nextjs')
console.log(cookie) // => { name: 'nextjs', value: 'fast', Path: '/' }
const allCookies = request.cookies.getAll()
console.log(allCookies) // => [{ name: 'nextjs', value: 'fast' }]
request.cookies.h... | https://nextjs.org/docs/app/building-your-application/routing/middleware |
baccacb331d2-7 | path: '/',
})
cookie = response.cookies.get('vercel')
console.log(cookie) // => { name: 'vercel', value: 'fast', Path: '/' }
// The outgoing response will have a `Set-Cookie:vercel=fast;path=/test` header.
return response
}
Setting Headers
You can set request and response headers using the NextResponse API ... | https://nextjs.org/docs/app/building-your-application/routing/middleware |
baccacb331d2-8 | requestHeaders.set('x-hello-from-middleware1', 'hello')
// You can also set request headers in NextResponse.rewrite
const response = NextResponse.next({
request: {
// New request headers
headers: requestHeaders,
},
})
// Set a new response header `x-hello-from-middleware2`
response.hea... | https://nextjs.org/docs/app/building-your-application/routing/middleware |
baccacb331d2-9 | import { isAuthenticated } from '@lib/auth'
// Limit the middleware to paths starting with `/api/`
export const config = {
matcher: '/api/:function*',
}
export function middleware(request: NextRequest) {
// Call our authentication function to check the request
if (!isAuthenticated(request)) {
// Respond w... | https://nextjs.org/docs/app/building-your-application/routing/middleware |
baccacb331d2-10 | skipTrailingSlashRedirect allows disabling Next.js default redirects for adding or removing trailing slashes allowing custom handling inside middleware which can allow maintaining the trailing slash for some paths but not others allowing easier incremental migrations.
next.config.js module.exports = {
skipTrailingSla... | https://nextjs.org/docs/app/building-your-application/routing/middleware |
baccacb331d2-11 | return NextResponse.redirect(req.nextUrl)
}
}
skipMiddlewareUrlNormalize allows disabling the URL normalizing Next.js does to make handling direct visits and client-transitions the same. There are some advanced cases where you need full control using the original URL which this unlocks.
next.config.js module.exports ... | https://nextjs.org/docs/app/building-your-application/routing/middleware |
baccacb331d2-12 | // without the flag this would be normalized to /hello
}
Version History
VersionChangesv13.1.0Advanced Middleware flags addedv13.0.0Middleware can modify request headers, response headers, and send responsesv12.2.0Middleware is stable, please see the upgrade guidev12.0.9Enforce absolute URLs in Edge Runtime (PR)v12.0.0... | https://nextjs.org/docs/app/building-your-application/routing/middleware |
51e8ce814bef-0 | Project Organization and File ColocationApart from routing folder and file conventions, Next.js is unopinionated about how you organize and colocate your project files.
This page shares default behavior and features you can use to organize your project.
Safe colocation by default
Project organization features
Project o... | https://nextjs.org/docs/app/building-your-application/routing/colocation |
51e8ce814bef-1 | Good to know:
This is different from the pages directory, where any file in pages is considered a route.
While you can colocate your project files in app you don't have to. If you prefer, you can keep them outside the app directory.
Project organization features
Next.js provides several features to help you organize yo... | https://nextjs.org/docs/app/building-your-application/routing/colocation |
51e8ce814bef-2 | Sorting and grouping files in code editors.
Avoiding potential naming conflicts with future Next.js file conventions.
Good to know
While not a framework convention, you might also consider marking files outside private folders as "private" using the same underscore pattern.
You can create URL segments that start with a... | https://nextjs.org/docs/app/building-your-application/routing/colocation |
51e8ce814bef-3 | Enabling nested layouts in the same route segment level:
Creating multiple nested layouts in the same segment, including multiple root layouts
Adding a layout to a subset of routes in a common segment
src Directory
Next.js supports storing application code (including app) inside an optional src directory. This separate... | https://nextjs.org/docs/app/building-your-application/routing/colocation |
51e8ce814bef-4 | The following section lists a very high-level overview of common strategies. The simplest takeaway is to choose a strategy that works for you and your team and be consistent across the project.
Good to know: In our examples below, we're using components and lib folders as generalized placeholders, their naming has no s... | https://nextjs.org/docs/app/building-your-application/routing/colocation |
7159bd219a09-0 | InternationalizationNext.js enables you to configure the routing and rendering of content to support multiple languages. Making your site adaptive to different locales includes translated content (localization) and internationalized routes.
Terminology
Locale: An identifier for a set of language and formatting preferen... | https://nextjs.org/docs/app/building-your-application/routing/internationalization |
7159bd219a09-1 | middleware.js import { match } from '@formatjs/intl-localematcher'
import Negotiator from 'negotiator'
let headers = { 'accept-language': 'en-US,en;q=0.5' }
let languages = new Negotiator({ headers }).languages()
let locales = ['en-US', 'nl-NL', 'nl']
let defaultLocale = 'en-US'
match(languages, locales, defaultLoc... | https://nextjs.org/docs/app/building-your-application/routing/internationalization |
7159bd219a09-2 | function getLocale(request) { ... }
export function middleware(request) {
// Check if there is any supported locale in the pathname
const pathname = request.nextUrl.pathname
const pathnameIsMissingLocale = locales.every(
(locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
)
//... | https://nextjs.org/docs/app/building-your-application/routing/internationalization |
7159bd219a09-3 | // Skip all internal paths (_next)
'/((?!_next).*)',
// Optional: only run on root (/) URL
// '/'
],
}
Finally, ensure all special files inside app/ are nested under app/[lang]. This enables the Next.js router to dynamically handle different locales in the route, and forward the lang parameter to every la... | https://nextjs.org/docs/app/building-your-application/routing/internationalization |
7159bd219a09-4 | Localization
Changing displayed content based on the user’s preferred locale, or localization, is not something specific to Next.js. The patterns described below would work the same with any web application.
Let’s assume we want to support both English and Dutch content inside our application. We might maintain two dif... | https://nextjs.org/docs/app/building-your-application/routing/internationalization |
7159bd219a09-5 | app/[lang]/dictionaries.js import 'server-only'
const dictionaries = {
en: () => import('./dictionaries/en.json').then((module) => module.default),
nl: () => import('./dictionaries/nl.json').then((module) => module.default),
}
export const getDictionary = async (locale) => dictionaries[locale]()
Given the curre... | https://nextjs.org/docs/app/building-your-application/routing/internationalization |
7159bd219a09-6 | return <button>{dict.products.cart}</button> // Add to Cart
}
Because all layouts and pages in the app/ directory default to Server Components, we do not need to worry about the size of the translation files affecting our client-side JavaScript bundle size. This code will only run on the server, and only the resulting ... | https://nextjs.org/docs/app/building-your-application/routing/internationalization |
7159bd219a09-7 | </html>
)
}
Examples
Minimal i18n routing and translations
next-intl | https://nextjs.org/docs/app/building-your-application/routing/internationalization |
092d651651e2-0 | Static and Dynamic RenderingIn Next.js, a route can be statically or dynamically rendered.
In a static route, components are rendered on the server at build time. The result of the work is cached and reused on subsequent requests.
In a dynamic route, components are rendered on the server at request time.
Static Renderi... | https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic-rendering |
092d651651e2-1 | To learn more about caching data fetching requests, see the Caching and Revalidating page.
Dynamic Rendering
During static rendering, if a dynamic function or a dynamic fetch() request (no caching) is discovered, Next.js will switch to dynamically rendering the whole route at request time. Any cached data requests can ... | https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic-rendering |
092d651651e2-2 | Good to know: In the future, Next.js will introduce hybrid server-side rendering where layouts and pages in a route can be independently statically or dynamically rendered, instead of the whole route.
Dynamic Functions
Dynamic functions rely on information that can only be known at request time such as a user's cookies... | https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic-rendering |
End of preview. Expand in Data Studio
No dataset card yet
- Downloads last month
- 5