Routing
Client-side routing with React Router and file-based routing concepts in Next.js applications.
SPA Routing Concepts
Single-page applications update the URL without full page reloads. The router maps URL paths to components, preserving application state and enabling shareable links. History API (`pushState`) drives URL changes.
Routes define parameters (`:id`), nested layouts, and index routes. Route configuration can be declarative (JSX routes) or data-driven (route objects).
- URL maps to components without reload
- Path params, nested routes, layouts
- Shareable deep links
React Router Basics
React Router v6 uses `<BrowserRouter>`, `<Routes>`, and `<Route element={}>` with nested routes via `<Outlet />`. Navigate programmatically with `useNavigate`. Read params with `useParams`, query strings with `useSearchParams`.
Layout routes wrap child routes without remounting shared UI. Index routes render at parent path. Error boundaries per route isolate failures.
- Routes, Route, Outlet for nesting
- useNavigate, useParams, useSearchParams
- Layout routes preserve shared UI
<Route path="/users" element={<UsersLayout />}>
<Route index element={<UserList />} />
<Route path=":id" element={<UserDetail />} />
</Route>Data Loading and Routing
React Router v6.4+ loaders fetch data before route renders — colocate data requirements with routes. Actions handle mutations. Deferred data with `<Await>` streams slow promises while showing fallbacks.
Next.js App Router replaces client routing with file-system routes — understand both models when maintaining legacy SPAs or building new Next apps.
- Loaders prefetch route data
- Actions for route mutations
- Next.js uses file-system routing
Protected Routes and Auth Guards
Wrap routes requiring authentication in guard components that redirect unauthenticated users to login. Store return URL in query params for post-login redirect.
Avoid flashing protected content before auth check completes — show loading skeleton until session resolves. Server-side middleware (Next.js) enforces auth before render for stronger security than client-only guards.
- Guard components redirect unauthenticated users
- Loading state during auth check
- Server middleware for real security
Navigation UX
Use `<Link>` instead of `<a>` for internal navigation to avoid full reloads. Prefetch linked routes when they enter viewport (Next.js Link default). Highlight active routes with NavLink or usePathname.
Scroll restoration, focus management on route change, and announcing page titles to screen readers improve accessibility across navigations.
- Link for internal navigation
- Prefetch for perceived speed
- Focus and announce route changes