routing: linking and navigating | next.js


本站和网页 https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating#how-routing-and-navigation-works 的作者无关,不对其内容负责。快照谨为网络故障时之索引,不代表被搜索网站的即时页面。

Routing: Linking and Navigating | Next.js
Skip to content
Search documentation...
Search... ⌘K Showcase Docs Blog Analytics Templates Enterprise Feedback Learn Menu
Using App Router
Features available in /app
Getting Started
Installation
Project Structure
Building Your Application
Routing
Defining Routes
Pages
Layouts and Templates
Linking and Navigating
Error Handling
Loading UI and Streaming
Redirecting
Route Groups
Project Organization
Dynamic Routes
Parallel Routes
Intercepting Routes
Route Handlers
Middleware
Internationalization
Data Fetching
Fetching, Caching, and Revalidating
Server Actions and Mutations
Data Fetching Patterns and Best Practices
Rendering
Server Components
Client Components
Composition Patterns
Runtimes
Caching
Styling
CSS Modules
Tailwind CSS
CSS-in-JS
Sass
Optimizing
Images
Videos
Fonts
Metadata
Scripts
Bundle Analyzer
Lazy Loading
Instrumentation
OpenTelemetry
Static Assets
Third Party Libraries
Memory Usage
Configuring
TypeScript
ESLint
Environment Variables
Absolute Imports and Module Path Aliases
MDX
src Directory
Draft Mode
Content Security Policy
Testing
Vitest
Jest
Playwright
Cypress
Authentication
Deploying
Production Checklist
Static Exports
Upgrading
Codemods
App Router Migration
Version 14
Migrating from Vite
Migrating from Create React App
API Reference
Components
Font
<Image>
<Link>
<Script>
File Conventions
default.js
error.js
instrumentation.js
layout.js
loading.js
mdx-components.js
middleware.js
not-found.js
page.js
route.js
Route Segment Config
template.js
Metadata Files
favicon, icon, and apple-icon
manifest.json
opengraph-image and twitter-image
robots.txt
sitemap.xml
Functions
cookies
draftMode
fetch
generateImageMetadata
generateMetadata
generateSitemaps
generateStaticParams
generateViewport
headers
ImageResponse
NextRequest
NextResponse
notFound
permanentRedirect
redirect
revalidatePath
revalidateTag
unstable_cache
unstable_noStore
useParams
usePathname
useReportWebVitals
useRouter
useSearchParams
useSelectedLayoutSegment
useSelectedLayoutSegments
userAgent
next.config.js Options
appDir
assetPrefix
basePath
compress
crossOrigin
devIndicators
distDir
env
eslint
exportPathMap
generateBuildId
generateEtags
httpAgentOptions
images
cacheHandler
instrumentationHook
logging
mdxRs
onDemandEntries
optimizePackageImports
output
pageExtensions
Partial Prerendering (experimental)
poweredByHeader
productionBrowserSourceMaps
reactStrictMode
redirects
rewrites
serverActions
serverComponentsExternalPackages
StaleTimes (experimental)
trailingSlash
transpilePackages
turbo
typedRoutes
typescript
urlImports
webpack
webVitalsAttribution
create-next-app
Edge Runtime
Next.js CLI
Pages and Layouts
Custom App
Custom Document
API Routes
Custom Errors
Server-side Rendering (SSR)
Static Site Generation (SSG)
Automatic Static Optimization
Client-side Rendering (CSR)
Edge and Node.js Runtimes
getStaticProps
getStaticPaths
Forms and Mutations
getServerSideProps
Incremental Static Regeneration (ISR)
Client-side Fetching
AMP
Babel
PostCSS
Custom Server
Debugging
Preview Mode
Multi Zones
Continuous Integration (CI) Build Caching
From Pages to App
Version 13
Version 12
Version 11
Version 10
Version 9
<Head>
<Image> (Legacy)
getInitialProps
useAmp
Runtime Config
Architecture
Accessibility
Fast Refresh
Next.js Compiler
Supported Browsers
Turbopack
Community
Contribution Guide
On this page
<Link> Component
Examples
Linking to Dynamic Segments
Checking Active Links
Scrolling to an id
Disabling scroll restoration
useRouter() hook
redirect function
Using the native History API
window.history.pushState
window.history.replaceState
How Routing and Navigation Works
1. Code Splitting
2. Prefetching
3. Caching
4. Partial Rendering
5. Soft Navigation
6. Back and Forward Navigation
7. Routing between pages/ and app/
Next Steps
Edit this page on GitHub
Managed Next.js (Vercel)
Scroll to top
App Router
...
There are four ways to navigate between routes in Next.js:
Using the
Component
hook
function
Using the native
History API
This page will go through how to use each of these options, and dive deeper into how navigation works.
is a built-in component that extends the HTML
<a>
tag to provide
prefetching
and client-side navigation between routes. It is the primary and recommended way to navigate between routes in Next.js.
You can use it by importing it from
next/link
, and passing a
href
prop to the component:
app/page.tsx
JavaScript
import
Link
from
'next/link'
export
default
Page
() {
return
<
"/dashboard"
>Dashboard</
>
There are other optional props you can pass to
. See the
API reference
for more.
When linking to
dynamic segments
, you can use
template literals and interpolation
to generate a list of links. For example, to generate a list of blog posts:
app/blog/PostList.js
PostList
({ posts }) {
ul
posts
.map
((post)
=>
li
key
post
.id}>
`/
blog
${
.slug
}>{
.title}</
</
))}
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
of the link:
@/app/ui/nav-links.tsx
'use client'
{ usePathname }
'next/navigation'
Links
const
()
nav
className
`link
===
'/'
'active'
''
"/"
Home
'/about'
"/about"
About
Scrolling to an
id
The default behavior of the Next.js App Router is to
scroll to the top of a new route or to maintain the scroll position for backwards and forwards navigation.
If you'd like to scroll to a specific
on navigation, you can append your URL with a
hash link or just pass a hash link to the
prop. This is possible since
renders to an
element.
"/dashboard#settings"
>Settings</
// Output
Good to know
Next.js will scroll to the
if it is not visible in the viewport upon navigation.
If you'd like to disable this behavior, you can pass
scroll={false}
to the
component, or
scroll: false
to
router.push()
or
router.replace()
// next/link
scroll
false
}>
Dashboard
// useRouter
{ useRouter }
router
.push
'/dashboard'
{ scroll
})
useRouter()
The
hook allows you to programmatically change routes from
app/page.js
button
type
"button"
onClick
{()
)}>
For a full list of
methods, see the
Recommendation:
Use the
component to navigate between routes unless you have a specific requirement for using
For
, use the
function instead.
app/team/[id]/page.tsx
{ redirect }
async
fetchTeam
(id
string
) {
res
await
'https://...'
if
.ok)
undefined
.json
Profile
({ params }
{ params
{ id
} }) {
team
params
.id)
'/login'
// ...
returns a 307 (Temporary Redirect) status code by default. When used in a Server Action, it returns a 303 (See Other), which is commonly used for redirecting to a success page as a result of a POST request.
internally throws an error so it should be called outside of
try/catch
blocks.
can be called in Client Components during the rendering process but not in event handlers. You can use the
instead.
also accepts absolute URLs and can be used to redirect to external links.
If you'd like to redirect before the render process, use
next.config.js
See the
for more information.
Next.js allows you to use the native
and
methods to update the browser's history stack without reloading the page.
pushState
replaceState
calls integrate into the Next.js Router, allowing you to sync with
Use it to add a new entry to the browser's history stack. The user can navigate back to the previous state. For example, to sort a list of products:
{ useSearchParams }
SortProducts
searchParams
updateSorting
(sortOrder
new
URLSearchParams
.toString
())
.set
'sort'
sortOrder)
window
history
.pushState
null
`?
<>
'asc'
)}>Sort Ascending</
'desc'
)}>Sort Descending</
</>
Use it to replace the current entry on the browser's history stack. The user is not able to navigate back to the previous state. For example, to switch the application's locale:
LocaleSwitcher
switchLocale
(locale
// e.g. '/en/about' or '/fr/contact'
newPath
locale
}${
.replaceState
newPath)
'en'
)}>English</
'fr'
)}>French</
The App Router uses a hybrid approach for routing and navigation. On the server, your application code is automatically
code-split
by route segments. And on the client, Next.js
prefetches
caches
the route segments. This means, when a user navigates to a new route, the browser doesn't reload the page, and only the route segments that change re-render - improving the navigation experience and performance.
Code splitting allows you to split your application code into smaller bundles to be downloaded and executed by the browser. This reduces the amount of data transferred and execution time for each request, leading to improved performance.
allow your application code to be automatically code-split by route segments. This means only the code needed for the current route is loaded on navigation.
Prefetching is a way to preload a route in the background before the user visits it.
There are two ways routes are prefetched in Next.js:
component
: Routes are automatically prefetched as they become visible in the user's viewport. Prefetching happens when the page first loads or when it comes into view through scrolling.
router.prefetch()
: The
hook can be used to prefetch routes programmatically.
's default prefetching behavior (i.e. when the
prefetch
prop is left unspecified or set to
) is different depending on your usage of
. Only the shared layout, down the rendered "tree" of components until the first
file, is prefetched and cached for
30s
. This reduces the cost of fetching an entire dynamic route, and it means you can show an
instant loading state
for better visual feedback to users.
You can disable prefetching by setting the
prop to
. Alternatively, you can prefetch the full page data beyond the loading boundaries by setting the
true
Prefetching is not enabled in development, only in production.
Next.js has an
in-memory client-side cache
called the
Router Cache
. As users navigate around the app, the React Server Component Payload of
prefetched
route segments and visited routes are stored in the cache.
This means on navigation, the cache is reused as much as possible, instead of making a new request to the server - improving performance by reducing the number of requests and data transferred.
Learn more about how the
works and how to configure it.
Partial rendering means only the route segments that change on navigation re-render on the client, and any shared segments are preserved.
For example, when navigating between two sibling routes,
/dashboard/settings
/dashboard/analytics
, the
settings
analytics
pages will be rendered, and the shared
dashboard
layout will be preserved.
Without partial rendering, each navigation would cause the full page to re-render on the client. Rendering only the segment that changes reduces the amount of data transferred and execution time, leading to improved performance.
Browsers perform a "hard navigation" when navigating between pages. The Next.js App Router enables "soft navigation" between pages, ensuring only the route segments that have changed are re-rendered (partial rendering). This enables client React state to be preserved during navigation.
By default, Next.js will maintain the scroll position for backwards and forwards navigation, and re-use route segments in the
7. Routing between
pages/
app/
When incrementally migrating from
, the Next.js router will automatically handle hard navigation between the two. To detect transitions from
, there is a client router filter that leverages probabilistic checking of app routes, which can occasionally result in false positives. By default, such occurrences should be very rare, as we configure the false positive likelihood to be 0.01%. This likelihood can be customized via the
experimental.clientRouterFilterAllowedRate
option in
. It's important to note that lowering the false positive rate will increase the size of the generated filter in the client bundle.
Alternatively, if you prefer to disable this handling completely and manage the routing between
manually, you can set
experimental.clientRouterFilter
to false in
. When this feature is disabled, any dynamic routes in pages that overlap with app routes won't be navigated to properly by default.
An overview of caching mechanisms in Next.js.
Next.js provides a TypeScript-first development experience for building your React application.
Previous
Next
Was this helpful?
supported.
Send
Resources
Next.js Conf
DX Platform
More
Next.js Commerce
Contact Sales
GitHub
Releases
Telemetry
Governance
About Vercel
Next.js + Vercel
Open Source Software
Legal
Privacy Policy
Cookie Preferences
Subscribe to our newsletter
Stay updated on new releases and features, guides, and case studies.
Subscribe
2024
Vercel, Inc.