Client-side routing
How single-page apps navigate without loading documents — the History API and link interception, server fallbacks for deep links, route matching and nesting, then data loading, code splitting, guards, scroll and focus after navigation.
Reading level
Shows sections up to the selected level.
Before you start
No prerequisites.
This topic starts at Junior level.
MPA and SPA navigation
Multi-page tətbiqdə (MPA) hər link klikləməsi sənəd naviqasiyasıdır. Brauzer yeni URL-i sorğulayır, server tam HTML sənədi qaytarır, köhnə səhifə boşaldılır, yenisi isə sıfırdan parse olunur, stillənir və render edilir. Bu yolda brauzer çox işi pulsuz görür: ünvan sətrini və sessiya tarixçəsini yeniləyir, Back və Forward düymələrini işlədir, scroll mövqeyini bərpa edir, yükləmə göstəricisini göstərir, fokusu yeni sənədin əvvəlinə qaytarır, screen reader-lər də yeni səhifənin başlığını elan edir.
Single-page tətbiq (SPA) bir HTML sənədi yükləyir, sonra isə naviqasiyanı JavaScript-də idarə edir. O, kliki tutur, sənəd yükləmədən History API ilə URL-i dəyişir və yeni ekranı komponentlərdən və adətən JSON kimi gələn datadan render edir. Klient tərəfində routing budur.
MPA: click → GET /products/42 → HTML → unload old page → parse, CSS, JS → render
SPA: click → preventDefault() → history.pushState(…, "/products/42") → load data → render routeBu niyə lazımdır
- State naviqasiyadan sonra da yaşayır. Audio pleyer çalmağa davam edir, yarımçıq yazılmış şərh öz sahəsində qalır, sidebar scroll mövqeyini saxlayır.
- Yalnız dəyişən hissə yenidən render olunur. Header, naviqasiya və layout yerində qalır, yalnız məzmun hissəsi əvəzlənir.
- Naviqasiya ani ola bilər. Route-un kodu və datası artıq yüklənibsə və ya prefetch olunubsa, şəbəkəyə ümumiyyətlə müraciət edilmir.
Bunun qiyməti
Router brauzerin əvvəllər gördüyü bütün işləri öz üzərinə götürür və unutduğu hər birini istifadəçi hiss edir: Back heç nə etmir, paylaşılan link 404 göstərir, səhifə yarıya qədər scroll olunmuş halda açılır, klikdən sonra screen reader susur. İlk ziyarət də yavaşlayır: server render olmadan heç nə görünməzdən əvvəl JavaScript bundle-ı yüklənib icra olunmalıdır, bu da -ni və -ni gecikdirir.
Bu gün vəziyyət necədir
İki model arasındakı sərhəd bulanıqlaşıb. Next.js, framework rejimində React Router, Nuxt və SvelteKit ilk səhifəni serverdə render edir, event handler-ləri ilə qoşur, ondan sonra isə klient tərəfində naviqasiyaya keçir. Brauzerlər adi sənəd naviqasiyasını da yaxşılaşdırmağa davam edir: back/forward cache bütöv səhifələri dərhal bərpa edir, növbəti səhifənin prefetch və ya prerender olunması (Speculation Rules API; MDN onu limited availability kimi göstərir, əsasən Chromium əsaslı brauzerlər dəstəkləyir) şəbəkə vaxtını gizlədir.
Ona görə əsl sual "SPA, yoxsa MPA" deyil: məhsulunda hansı naviqasiyalar klient tərəfində routing-dən fayda görür və onlar üçün brauzerin gördüyü işi yenidən qurmağa hazırsanmı? Bu mövzunun qalan hissəsi həmin siyahıdır.
In a multi-page app (MPA) every link click is a document navigation. The browser requests the new URL, the server returns a complete HTML document, the old page is unloaded, and the new one is parsed, styled and rendered from scratch. Along the way the browser does a lot for free: it updates the address bar and the session history, makes Back and Forward work, restores the scroll position, shows a loading indicator, resets focus to the top of the new document, and screen readers announce the new page's title.
A single-page app (SPA) loads one HTML document and then handles navigation in JavaScript. It intercepts the click, changes the URL with the History API without loading a document, and renders the new screen from components and data, usually fetched as JSON. That is client-side routing.
MPA: click → GET /products/42 → HTML → unload old page → parse, CSS, JS → render
SPA: click → preventDefault() → history.pushState(…, "/products/42") → load data → render routeWhy do it
- State survives navigation. An audio player keeps playing, a half-written comment stays in its box, a sidebar keeps its scroll position.
- Only what changed re-renders. The header, navigation and layout stay mounted; only the content area is replaced.
- Navigations can be instant. When the route's code and data are already loaded or prefetched, there is no network round trip at all.
What it costs
The router takes over every job the browser used to do, and users notice each one it forgets: Back does nothing, a shared link shows a 404, the page opens scrolled halfway down, a screen reader stays silent after a click. The first visit also gets slower: without server rendering, the JavaScript bundle must download and run before anything appears, which delays and .
Where things stand
The line between the two models has blurred. Next.js, React Router in framework mode, Nuxt and SvelteKit render the first page on the server, attach event handlers with , and switch to client-side navigation after that. Browsers keep improving plain document navigations too: the back/forward cache restores whole pages instantly, and prefetching or prerendering the next page (the Speculation Rules API; MDN lists it as limited availability, supported mainly in Chromium-based browsers) hides network time.
So the real question is not "SPA or MPA" but which navigations in your product benefit from client-side routing, and whether you are ready to rebuild what the browser did for them. The rest of this topic is that list.
The History API: pushState, replaceState, popstate
Klient tərəfində routing History API-nin üç hissəsinə söykənir:
history.pushState({ page: 2 }, "", "/products?page=2");
history.replaceState({ page: 3 }, "", "/products?page=3");
window.addEventListener("popstate", (event) => {
render(location.pathname, event.state);
});pushState(state, unused, url)sessiya tarixçəsinə yeni yazı əlavə edir və ünvan sətrini dəyişir. Brauzer URL-i yükləmir və heç bir hadisə işə salmır. URL cari URL ilə eyni origin-də olmalıdır, əks haldaSecurityErroratılır.stateyazı ilə birlikdə structured clone kimi saxlanır (funksiya və DOM node olmaz, onlarDataCloneErroratır) vəhistory.statevəevent.statekimi geri qayıdır. İkinci arqument tarixi səbəblərdən qalıb;""ötür.replaceState()yeni yazı əlavə etmək əvəzinə cari yazını dəyişir. Onu redirect-lər, URL-in normallaşdırılması (/Products/→/products) və daim dəyişən state üçün işlət, məsələn axtarış sahəsinin mətni üçün: hər düymə basışına bir yazı Back düyməsini yararsız edərdi.popstateaktiv yazı traversal ilə dəyişəndə işə düşür: Back və Forward düymələri,history.back(),history.forward(),history.go(-2).pushState()və yareplaceState()çağırışı onu heç vaxt işə salmır.
Bundan çıxan iki nəticə hər router-in quruluşunu müəyyən edir:
pushState()-dən sonra router özü render etməlidir. URL-in dəyişdiyini ona heç kim xəbər verməyəcək.history.back()asinxrondur. Növbəti sətirdəlocationvəhistory.statehələ köhnə yazını göstərir; dəyişiklik sonra,popstateilə gəlir.back()-i çağırıb dərhal URL-i oxuyan kod keçmişi oxuyur.
Hash routing
History API-dən əvvəl SPA-lar route-u fragment-də saxlayırdı: /#/products/42. location.hash-i dəyişmək sənəd yükləmir; tarixçəyə yazı əlavə edir və hashchange (ondan əvvəl isə popstate) hadisəsini işə salır. Fragment heç vaxt serverə göndərilmir, ona görə bütün route-lara eyni / cavab verir və deep link-lər istənilən statik hostda işləyir.
Bunun qiyməti: qəribə görünən URL-lər, fragment-dən eyni zamanda səhifədaxili anchor-lar üçün istifadə etmək olmur, server route-u heç vaxt render edə bilmir, çünki onu görmür, iki mexanizm isə bir-birinə qarışmır: pushState() yalnız hash dəyişəndə belə hashchange-i işə salmır. Hash routing başqasının səhifəsinə yerləşdirilən widget-lər, file://-dan açılan tətbiqlər və ya rewrite qaydalarını tənzimləyə bilmədiyin hostlar üçün hələ də normal seçimdir.
State harada yaşayır
history.state bir yazıya aid olan və URL-də olmamalı şeylər üçün yaxşıdır, məsələn siyahının scroll mövqeyi və ya hansı accordion-un açıq olduğu. Bəzi brauzerlər state-i diskə yazır və ölçüsünü məhdudlaşdırır, ona görə onu kiçik saxla; istifadəçinin paylaşa və ya bookmark edə bilməli olduğu hər şey URL-in özündə olmalıdır.
Client-side routing rests on three pieces of the History API:
history.pushState({ page: 2 }, "", "/products?page=2");
history.replaceState({ page: 3 }, "", "/products?page=3");
window.addEventListener("popstate", (event) => {
render(location.pathname, event.state);
});pushState(state, unused, url)adds a new entry to the session history and changes the address bar. The browser does not load the URL and fires no event. The URL must have the same origin as the current one, otherwise aSecurityErroris thrown.stateis stored with the entry as a structured clone (no functions or DOM nodes; those throw aDataCloneError) and comes back ashistory.stateandevent.state. The second argument exists for historical reasons; pass"".replaceState()changes the current entry instead of adding one. Use it for redirects, for normalizing a URL (/Products/→/products), and for state that changes continuously, like the text of a search box, where one entry per keystroke would make Back useless.popstatefires when the active entry changes through traversal: the Back and Forward buttons,history.back(),history.forward(),history.go(-2). CallingpushState()orreplaceState()never fires it.
Two consequences shape every router:
- After
pushState()the router must render by itself. Nothing will tell it that the URL changed. history.back()is asynchronous. On the next linelocationandhistory.statestill show the old entry; the change arrives later withpopstate. Code that callsback()and immediately reads the URL is reading the past.
Hash routing
Before the History API, SPAs kept the route in the fragment: /#/products/42. Changing location.hash does not load a document; it adds a history entry and fires hashchange (and popstate before it). The fragment is never sent to the server, so every route is served by the same / and deep links work on any static host.
The price: URLs that look odd, the fragment cannot also be used for in-page anchors, a server can never render the route because it never sees it, and the two mechanisms do not mix: pushState() never fires hashchange, even when only the hash changes. Hash routing is still a fair choice for widgets embedded in someone else's page, for apps opened from file://, or for hosts where you cannot configure rewrites.
Where state lives
history.state is good for things that belong to one entry and should not be in the URL, such as the scroll position of a list or which accordion was open. Some browsers persist state to disk and limit its size, so keep it small; anything a user should be able to share or bookmark belongs in the URL itself.
A router: intercepting links, rendering, Back and Forward
Ən sadə history router-in dörd hissəsi var: link kliklərini tutmaq, URL-i push etmək, uyğun route-u render etmək və popstate-də yenidən render etmək.
function shouldIntercept(event, link) {
return (
!event.defaultPrevented &&
event.button === 0 &&
!event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey &&
(!link.target || link.target === "_self") &&
!link.hasAttribute("download") &&
link.origin === location.origin
);
}
document.addEventListener("click", (event) => {
const link = event.target.closest("a[href]");
if (!link || !shouldIntercept(event, link)) return;
event.preventDefault();
navigate(link.pathname + link.search + link.hash);
});
function navigate(to, { replace = false } = {}) {
if (replace) history.replaceState(null, "", to);
else history.pushState(null, "", to);
render();
}
window.addEventListener("popstate", render);
function render() {
const match = matchRoute(routes, location.pathname);
app.replaceChildren(match ? match.route.view(match.params) : notFoundView());
}
render();Hər yoxlama niyə lazımdır
- Modifikator düymələr və digər siçan düymələri. Ctrl/⌘+klik yeni tab, Shift+klik yeni pəncərə açır. Router bu kliklərin qarşısını alsa, təcrübəli istifadəçilər brauzerin əsas imkanlarını itirir.
target="_blank"vədownload. İstifadəçi tətbiqdaxili keçid yox, yeni tab və ya fayl istəyib.- Başqa origin-lər. Başqa sayta (və ya origin-i sənin olmayan
mailto:-ya) aparan link tətbiqdən çıxmalıdır. Başqa origin üçünpushState()onsuz da xəta atardı. defaultPrevented. Bu klik artıq başqa handler tərəfindən emal olunub.
Nəzərə almağa dəyən daha bir hal: cari səhifədə yalnız #hash-i dəyişən link. Onu brauzerin öhdəsinə buraxsan, anchor-a native scroll saxlanılır.
Naviqasiya üçün əsl <a href> elementlərindən istifadə et. Onlar JavaScript yüklənməzdən əvvəl də işləyir, üzərinə gələndə URL-i göstərir, "Open in new tab" və "Copy link"-i dəstəkləyir, crawler-lər onları izləyir, screen reader isə onları link kimi elan edir. <div onClick={() => navigate("/settings")}>-də bunların heç biri yoxdur. React Router-in <Link> komponenti <a> render edir və eyni filtri tətbiq edir: yalnız əsas düymə ilə, modifikatorsuz və _self-dən başqa target olmadan edilən klik.
Bu platformadakı Mini Router build layihəsi məhz bu dövrəni qurur, sonra ona uyğunlaşdırma və sıralama, iç-içə route-lar, guard-lar və loader-lər əlavə edir. Layihə eyni API-yə malik memory history işlədir (React Router-in createMemoryRouter-i kimi), çünki laboratoriyanın sandbox iframe-ində pushState() SecurityError atır.
Navigation API
Navigation API klik listener-ini və popstate-i router üçün vacib olan naviqasiyalarda işə düşən vahid navigate hadisəsi ilə əvəz edir: link klikləri, form göndərişləri, location-a mənimsətmələr, həmçinin tətbiqin öz yazıları arasında Back və Forward.
navigation.addEventListener("navigate", (event) => {
if (!event.canIntercept || event.hashChange || event.downloadRequest !== null) return;
const url = new URL(event.destination.url);
event.intercept({
async handler() {
await renderRoute(url);
},
});
});O, Baseline 2026-dır (yanvar 2026-dan yeni əlçatandır), yəni köhnə brauzerlər üçün History API fallback-i ilə bu gün istifadə oluna bilər. intercept() həm də handler bitdikdən sonra fokus və scroll üçün default davranış gətirir (focusReset, scroll).
A minimal history router has four parts: intercept link clicks, push the URL, render the matching route, and render again on popstate.
function shouldIntercept(event, link) {
return (
!event.defaultPrevented &&
event.button === 0 &&
!event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey &&
(!link.target || link.target === "_self") &&
!link.hasAttribute("download") &&
link.origin === location.origin
);
}
document.addEventListener("click", (event) => {
const link = event.target.closest("a[href]");
if (!link || !shouldIntercept(event, link)) return;
event.preventDefault();
navigate(link.pathname + link.search + link.hash);
});
function navigate(to, { replace = false } = {}) {
if (replace) history.replaceState(null, "", to);
else history.pushState(null, "", to);
render();
}
window.addEventListener("popstate", render);
function render() {
const match = matchRoute(routes, location.pathname);
app.replaceChildren(match ? match.route.view(match.params) : notFoundView());
}
render();Why each check is there
- Modifier keys and other buttons. Ctrl/⌘+click opens a new tab, Shift+click a new window. If the router swallows these clicks, power users lose basic browser features.
target="_blank"anddownload. The user asked for a new tab or a file, not an in-app navigation.- Other origins. A link to another site (or
mailto:, whose origin is not yours) must leave the app.pushState()would throw for another origin anyway. defaultPrevented. Some other handler already took care of this click.
One more case worth handling: a link that changes only the #hash on the current page. Letting the browser handle it keeps its native scroll to the anchor.
Use real <a href> elements for navigation. They work before JavaScript loads, show the URL on hover, support "Open in new tab" and "Copy link", are followed by crawlers, and are announced as links. <div onClick={() => navigate("/settings")}> has none of that. React Router's <Link> renders an <a> and applies the same filter: only a primary-button click with no modifier keys and no target other than _self.
The Mini Router build project on this platform builds exactly this loop, then adds matching and ranking, nested routes, guards and loaders. It uses a memory history with the same API (as React Router's createMemoryRouter does), because pushState() throws a SecurityError in the lab's sandboxed iframe.
The Navigation API
The Navigation API replaces the click listener and popstate with one navigate event that fires for the navigations a router cares about: link clicks, form submissions, location assignments, and Back and Forward between the app's own entries.
navigation.addEventListener("navigate", (event) => {
if (!event.canIntercept || event.hashChange || event.downloadRequest !== null) return;
const url = new URL(event.destination.url);
event.intercept({
async handler() {
await renderRoute(url);
},
});
});It is Baseline 2026 (newly available since January 2026), so it is usable today with a History API fallback for older browsers. intercept() also brings default focus and scroll handling after the handler finishes (focusReset, scroll).
Deep links and the server fallback
History routing-də /products/42 yalnız klient router-inin içində mövcuddur. Tətbiqin içindən ora klikləmək işləyir. Səhifəni yeniləmək, bookmark-ı açmaq və ya paylaşılan linkə keçmək isə router-dən keçmir: brauzer /products/42-ni serverdən istəyir, yalnız index.html-i olan statik host da 404 qaytarır.
Həll fallback-dir (rewrite): real fayl olmayan hər URL-ə tətbiqin HTML-i ilə cavab verilir, JavaScript, CSS və şəkil kimi fayllar isə olduğu kimi göndərilir.
# nginx
location / {
try_files $uri $uri/ /index.html;
}
# Netlify, in _redirects
/* /index.html 200Development server adətən bunu sənin yerinə edir, "lokalda işləyir" deyib ilk deploy-dan sonra sınmasının səbəbi də budur.
Ağrı verən detallar
- Nisbi asset URL-ləri.
/products/42-dən yüklənən<script type="module" src="assets/app.js">/products/assets/app.jskimi həll olunur. Belə fayl yoxdur, fallbackindex.htmlilə cavab verir, brauzer isə HTML-i module skript kimi icra etməkdən imtina edir: boş səhifə, həm də yalnız deep link-lərdə. Kökdən başlayan URL-lərdən (/assets/app.js) istifadə et və ya bundler-in base path-ini tənzimlə. - Status kodu. Fallback hər URL-ə, o cümlədən
/no-such-page-ə200ilə cavab verir. İstifadəçilər klient tərəfindəki "Not found" görünüşünü görür, crawler-lər isə uğurlu səhifə görür, yəni "soft 404". Server render varsa, əsl404qaytar. Tam statik hostda Google-un SPA-lar üçün tövsiyəsi həqiqətən 404 qaytaran URL-ə redirect etmək və ya not-found görünüşünə<meta name="robots" content="noindex">əlavə etməkdir. - Eyni hostdakı API-lər.
/api/*dəindex.html-ə düşürsə, endpoint adındakı hərf səhvi status 200 ilə HTML qaytarır və klient<!doctype html>-inJSON.parse-ında yıxılır. API yollarını fallback-dən çıxar. - Base path. Tətbiq
/admin/altında yaşayırsa, onu həm server qaydası, həm də router bilməlidir (React Router-inbasename-i və bundler-in base path-i, məsələn Vite-inbase-i). - Cache.
index.htmluzun müddət cache-lənməməlidir, yoxsa istifadəçilərdə silinmiş, hash-li bundle-lara istinad edən köhnə HTML qalır. Hash-li asset-ləri uzun müddət cache-lə, HTML-i isə revalidate et.
Çıxış yolu kimi hash routing
/#/products/42 olanda server yalnız /-i görür, ona görə bunların heç biri aktual deyil. Hash routing-in yerləşdirilən widget-lərdə və rewrite qaydası olmayan hostlarda yaşamağa davam etməsinin səbəbi budur. Əvəzində təmiz URL-lərdən, crawler-lərin görə bildiyi route-lardan (Google fərqli məzmunu fragment ilə yükləməməyi tövsiyə edir) və route-u serverdə render etmək imkanından imtina edirsən.
Server render ilə
Serverdə render edən framework-lərdə (Next.js, React Router-in framework rejimi, Nuxt, SvelteKit) fallback problemi yoxdur: hər route-un HTML render edən, düzgün status kodu qaytaran və redirect edə bilən əsl server handler-i var. Klient tərəfində routing yalnız ilk səhifə hydrate olunandan sonra işə qoşulur.
With history routing, /products/42 exists only inside the client router. Clicking there from inside the app works. Reloading the page, opening a bookmark or following a shared link does not go through the router: the browser asks the server for /products/42, and a static host that only has index.html answers 404.
The fix is a fallback (a rewrite): every URL that is not a real file is answered with the app's HTML, and files such as JavaScript, CSS and images are served as they are.
# nginx
location / {
try_files $uri $uri/ /index.html;
}
# Netlify, in _redirects
/* /index.html 200The development server usually does this for you, which is why "it works locally" and breaks after the first deploy.
Details that bite
- Relative asset URLs.
<script type="module" src="assets/app.js">loaded from/products/42resolves to/products/assets/app.js. That file does not exist, the fallback answers withindex.html, and the browser refuses to run HTML as a module script: a blank page, but only on deep links. Use root-relative URLs (/assets/app.js) or configure the bundler's base path. - The status code. The fallback answers
200for every URL, including/no-such-page. Users see your client-side "Not found" view, while crawlers see a successful page, a "soft 404". With server rendering, return a real404. On a purely static host, Google's guidance for SPAs is to redirect to a URL that does return 404, or to add<meta name="robots" content="noindex">to the not-found view. - APIs behind the same host. If
/api/*falls through toindex.html, a typo in an endpoint returns HTML with status 200, and the client fails onJSON.parseof<!doctype html>. Exclude API paths from the fallback. - A base path. When the app lives under
/admin/, both the server rule and the router need it (React Router'sbasename, and the bundler's base path, such as Vite'sbase). - Caching.
index.htmlmust not be cached for long, or users keep an old HTML file that points to deleted, content-hashed bundles. Cache the hashed assets for a long time and revalidate the HTML.
Hash routing as the escape hatch
With /#/products/42 the server only ever sees /, so none of this applies. That is why hash routing survives in embedded widgets and on hosts without rewrite rules. You give up clean URLs, crawlable routes (Google advises against loading different content by fragment) and any chance of server rendering the route.
With server rendering
Frameworks that render on the server (Next.js, React Router's framework mode, Nuxt, SvelteKit) have no fallback problem: every route has a real server handler that renders HTML, returns the right status code and can redirect. Client-side routing takes over only after the first page has been hydrated.
Route matching, ranking, params and nested routes
Route şablonu statik seqmentlərdən (users), dinamik seqmentlərdən (:id) və bəzən splat, yəni catch-all seqmentdən (*) ibarət yoldur. Uyğunlaşdırma pathname-i / üzrə bölür və seqment-seqment müqayisə edir; dinamik seqmentlər parametrləri tutur.
Sıralama
Çox vaxt eyni URL-ə bir neçə şablon uyğun gəlir: /users/new həm /users/new, həm də /users/:id şablonuna uyğundur. Elan sırasında birincini seçmək kövrəkdir, çünki bir sətrin yerini dəyişmək davranışı dəyişir. Müasir router-lər bunun əvəzinə şablonları dəqiqliyinə görə sıralayır: statik dinamikdən, dinamik splat-dan üstündür. React Router hər route üçün bal hesablayır: hər statik seqment 10, hər dinamik seqment 3 əlavə edir, splat route isə cərimə alır.
/users/new static + static wins for /users/new
/users/:id static + dynamic /users/42
/users/:id/* + splat /users/42/posts/7
/* splat only everything else (the 404 view)Beləliklə, route-lar hansı sırada elan olunmasından asılı olmayaraq /users/new heç vaxt id-si "new" olan istifadəçi kimi tutulmur.
Bug-a səbəb olan detallar:
- Parametrlər sətirdir.
/users/42"42"verir,/users/abcdə uyğun gəlir. Çevir və yoxla, səhv id-lər üçün "not found" göstər. - Parametrlər percent-decode olunur.
/tags/c%23"c#"verir; URL-ləriencodeURIComponent()ilə qur. - Query və hash uyğunlaşdırmaya daxil deyil.
/products?page=2/products-a uyğun gəlir; query-ni ayrıca oxu. - Sondakı slash və hərf registri.
/About/-un/about-a bərabər olub-olmadığına bir dəfə qərar ver və bir kanonik formaya redirect et.
İç-içə route-lar və layout-lar
URL-lər iyerarxikdir, interfeyslər də: /settings/profile tətbiqin qabığını, onun içində sidebar-lı settings layout-unu, onun da içində profil formasını göstərir. İç-içə route-lar bu ağacı təsvir edir, uyğunluq isə kökdən yarpağa qədər route-ların siyahısıdır. Hər biri öz hissəsini və uşağın yerləşəcəyi outlet-i render edir:
const router = createBrowserRouter([
{
path: "/",
element: <AppShell />,
children: [
{ index: true, element: <Home /> },
{
path: "settings",
element: <SettingsLayout />,
children: [
{ path: "profile", element: <Profile /> },
{ path: "billing", element: <Billing /> },
],
},
{ path: "*", element: <NotFound /> },
],
},
]);/settings/profile-dan /settings/billing-ə keçəndə AppShell və SettingsLayout state-ləri və scroll mövqeləri ilə birlikdə yerində qalır, yalnız yarpaq əvəzlənir. Router-in hər səviyyə üçün datanı eyni anda yükləməsinə və bir səviyyədəki xətanı ətrafdakı layout-ları saxlayaraq göstərməsinə imkan verən də bu uyğunluq siyahısıdır. Next.js eyni ağacı qovluqlar və layout.js faylları ilə ifadə edir.
URLPattern
Platformanın artıq öz matcher-i var: new URLPattern({ pathname: "/users/:id" }).exec(url)?.pathname.groups.id. O, Baseline 2025-dir (sentyabr 2025-dən yeni əlçatandır) və Node-da da mövcuddur. Bir dəfəyə bir şablonu yoxlayır və sıralama aparmır, yəni sıra yenə sənin üzərinə düşür.
A route pattern is a path made of static segments (users), dynamic segments (:id) and possibly a splat, or catch-all (*). Matching splits the pathname at / and compares segment by segment; dynamic segments capture params.
Ranking
Several patterns often match the same URL: /users/new matches both /users/new and /users/:id. Picking the first one in declaration order is fragile, because moving one line changes behaviour. Modern routers rank patterns by specificity instead: static beats dynamic, dynamic beats splat. React Router computes a score per route: each static segment adds 10, each dynamic segment 3, and a splat route gets a penalty.
/users/new static + static wins for /users/new
/users/:id static + dynamic /users/42
/users/:id/* + splat /users/42/posts/7
/* splat only everything else (the 404 view)So /users/new is never captured as a user with the id "new", wherever the routes are declared.
Details that cause bugs:
- Params are strings.
/users/42gives"42", and/users/abcmatches too. Convert and validate, and show "not found" for invalid ids. - Params are percent-decoded.
/tags/c%23gives"c#"; build URLs withencodeURIComponent(). - Query and hash are not part of the match.
/products?page=2matches/products; read the query separately. - Trailing slashes and case. Decide once whether
/About/equals/aboutand redirect to one canonical form.
Nested routes and layouts
URLs are hierarchical and so are interfaces: /settings/profile shows the app shell, inside it the settings layout with its sidebar, inside that the profile form. Nested routes describe this tree, and a match is a list of routes from the root to the leaf. Each one renders its own part and an outlet where the child goes:
const router = createBrowserRouter([
{
path: "/",
element: <AppShell />,
children: [
{ index: true, element: <Home /> },
{
path: "settings",
element: <SettingsLayout />,
children: [
{ path: "profile", element: <Profile /> },
{ path: "billing", element: <Billing /> },
],
},
{ path: "*", element: <NotFound /> },
],
},
]);Going from /settings/profile to /settings/billing keeps AppShell and SettingsLayout mounted, with their state and scroll position, and replaces only the leaf. The match list is also what lets a router load data for every level at once and show an error for one level while keeping the layouts around it. Next.js expresses the same tree with folders and layout.js files.
URLPattern
The platform now has its own matcher: new URLPattern({ pathname: "/users/:id" }).exec(url)?.pathname.groups.id. It is Baseline 2025 (newly available since September 2025) and exists in Node too. It matches one pattern at a time and does not rank, so the order is still up to you.
The URL as state, guards and redirects
State-in bir hissəsi səhifə yenilənəndən sonra da qalmalı, paylaşıla bilməli və ya Back ilə geri qaytarılmalıdırsa, onun yeri URL-dir: filtrlər, sıralama, axtarış sorğusu, səhifə nömrəsi, seçilmiş tab, açıq element. Yalnız komponent state-i bu üçünün hamısını itirir.
function readFilters(search) {
const params = new URLSearchParams(search);
return {
q: params.get("q") ?? "",
tags: params.getAll("tag"),
page: Math.max(1, Number.parseInt(params.get("page") ?? "1", 10) || 1),
};
}
function filtersToSearch({ q, tags, page }) {
const params = new URLSearchParams();
if (q) params.set("q", q);
for (const tag of tags) params.append("tag", tag);
if (page > 1) params.set("page", String(page));
const search = params.toString();
return search ? `?${search}` : "";
}Bunu qaydasında saxlayan prinsiplər:
- Həqiqət mənbəyi URL-dir. Filtrləri hər render-də ondan oxu və UI-ı ondan çıxar; state-də uyğunsuzlaşa biləcək ikinci surət saxlama.
- Push və ya replace-i şüurlu seç. Back ilə geri qaytarılmalı olan ayrı-ayrı seçimlər (filtr tətbiq etmək, 3-cü səhifəyə keçmək) push işlədir. Davamlı daxiletmə (axtarış sahəsində hər düymə basışı) replace işlədir, yoxsa Back hər hərfi bir-bir gəzəcək.
- Default dəyərləri URL-ə yazma.
?page=1&sort=relevancehər paylaşılan linkə səs-küy qatır; default-a bərabər dəyərləri burax. - Yoxla. İnsanlar URL-ləri əl ilə dəyişir:
?page=-1,?page=abc, naməlum tag-lar.readFilterskimi ehtiyatla parse et. - Kodlaşdırmanı bil.
URLSearchParamsboşluğu+kimi seriallaşdırır və siyahılar üçün açarı təkrarlayır (?tag=a&tag=b); siyahılarıgetAll()ilə oxu.
React Router (useSearchParams) və Next.js (useSearchParams, router.replace) eyni modeli verir.
Guard-lar və redirect-lər
Guard render-dən əvvəl naviqasiyanın davam edə bilib-bilməyəcəyinə qərar verir: hesabdan çıxmış istifadəçi /settings-i açanda /login?next=/settings-ə gedir; yadda saxlanmamış dəyişiklikləri olan form təsdiq istəyir.
- Redirect-i replace ilə et.
/settings/login-i push edirsə, login səhifəsindən Back yenidən/settings-ə qaytarır, o da yenidən redirect edir: istifadəçi ilişib qalır. Bunun əvəzinə yazını əvəzlə, daxil olduqdan sonra isə/login-inextyolu ilə replace et. next-i yoxla. Yalnız eyni origin-ə aid yolları (tək/ilə başlayan) qəbul et, yoxsa?next=https://evil.examplelogin səhifəni open redirect-ə çevirir.- Klient guard-ları təhlükəsizlik yox, UX-dir. Hər kəs klient kodunu dəyişə və ya API-ni birbaşa çağıra bilər, ona görə hər sorğunu server avtorizasiya etməlidir. React Router sənədləri loader-lər haqqında eyni şeyi deyir: uyğun gələn loader-lər paralel işləyir, ona görə valideyn loader uşaqlarını qoruya bilmir, hər loader girişi özü yoxlamalıdır (və ya middleware).
- Yadda saxlanmamış dəyişikliklər.
beforeunloadsəhifənin yenilənməsini və tab-ın bağlanmasını əhatə edir; tətbiqdaxili naviqasiyalar üçün router-in blocker-i (React Router-dəuseBlocker) və ya eyni sənəd daxilindəki naviqasiyaları ləğv edə bilən Navigation APInavigatehadisəsi lazımdır.
If a piece of state should survive a reload, be shareable, or be undone with Back, it belongs in the URL: filters, sort order, the search query, the page number, the selected tab, the open item. Component state alone loses all three.
function readFilters(search) {
const params = new URLSearchParams(search);
return {
q: params.get("q") ?? "",
tags: params.getAll("tag"),
page: Math.max(1, Number.parseInt(params.get("page") ?? "1", 10) || 1),
};
}
function filtersToSearch({ q, tags, page }) {
const params = new URLSearchParams();
if (q) params.set("q", q);
for (const tag of tags) params.append("tag", tag);
if (page > 1) params.set("page", String(page));
const search = params.toString();
return search ? `?${search}` : "";
}Rules that keep this sane:
- The URL is the source of truth. Read the filters from it on every render and derive the UI; do not keep a second copy in state that can drift.
- Push or replace on purpose. Discrete choices that Back should undo (apply a filter, go to page 3) use push. Continuous input (each keystroke in a search box) uses replace, otherwise Back walks through every letter.
- Keep defaults out.
?page=1&sort=relevanceadds noise to every shared link; omit values that equal the default. - Validate. People edit URLs by hand:
?page=-1,?page=abc, unknown tags. Parse defensively, asreadFiltersdoes. - Know the encoding.
URLSearchParamsserializes spaces as+and repeats keys for lists (?tag=a&tag=b); read lists withgetAll().
React Router (useSearchParams) and Next.js (useSearchParams, router.replace) give you the same model.
Guards and redirects
A guard decides before rendering whether a navigation may go ahead: a signed-out user opening /settings goes to /login?next=/settings; a form with unsaved changes asks for confirmation.
- Redirect with replace. If
/settingspushes/login, Back from the login page returns to/settings, which redirects again: the user is stuck. Replace the entry instead, and after signing in replace/loginwith thenextpath. - Validate
next. Accept only same-origin paths (starting with a single/), otherwise?next=https://evil.exampleturns your login page into an open redirect. - Client guards are UX, not security. Anyone can change client code or call the API directly, so the server must authorize every request. The React Router docs say the same about loaders: matched loaders run in parallel, so a parent loader cannot protect its children, and each loader must check access itself (or middleware must).
- Unsaved changes.
beforeunloadcovers reloads and closing the tab; in-app navigations need the router's blocker (useBlockerin React Router) or the Navigation API'snavigateevent, which can be cancelled for same-document navigations.
Data loading and code splitting per route
Sadəlövh SPA datanı komponentlərin içində, effektlərdə sorğulayır. /projects/7/tasks ProjectLayout-u render edir, onun effekti layihəni sorğulayır; cavab gələndə TaskList render olunur və onun effekti tapşırıqları sorğulayır; sonra hər tapşırıq sətri öz icraçısını sorğulayır. Hər sorğu yalnız əvvəlki komponent render olunandan sonra başlayır: bu, waterfall-dır. Lazy yüklənən route-da vəziyyət daha da pisləşir, çünki birinci sorğunun başlaya bilməsi üçün əvvəlcə kod gəlməlidir.
effects: [route JS] → [project] → [tasks] → [assignees] → done
loaders: [route JS]
[project]
[tasks] → render once, doneRoute loader-ləri
Router heç nə render olunmazdan əvvəl yalnız URL-ə baxıb hansı route-ların uyğun gəldiyini bilir. Ona görə o, bütün uyğun route-ların data sorğularını naviqasiya anında, hətta link-in üzərinə gəlinəndə daha tez, paralel başlada bilər:
const router = createBrowserRouter([
{
path: "/projects/:projectId",
element: <ProjectLayout />,
loader: async ({ params, request }) => {
const res = await fetch(`/api/projects/${params.projectId}`, { signal: request.signal });
if (!res.ok) throw new Response("Not found", { status: res.status });
return res.json();
},
errorElement: <ProjectError />,
children: [
{
path: "tasks",
lazy: () => import("./routes/tasks.jsx"),
},
],
},
]);Yaxşı qurulmuş loader-lər sənə nə verir:
- Paralel sorğular. Valideynin və uşağın datası eyni vaxtda yüklənir; ekran lazım olan hər şeylə bir dəfə render olunur.
- Ləğvetmə. İstifadəçi yenidən naviqasiya edəndə əvvəlki naviqasiyanın
request.signal-ı abort olunur. Bu olmasa,/projects/1üçün gec gələn cavab/projects/2-nin tez gələn cavabından sonra çatıb daha yeni ekranın üstünə yaza bilər. Router hansı olursa olsun, qayda belədir: "sonuncu naviqasiya qalib gəlir". - Gözləmə UI-ı. Bir anlıq boş səhifə göstərmək əvəzinə köhnə ekranı progress göstəricisi ilə saxla (
useNavigation().state === "loading") və ya yavaş data üçün skeleton göstər. - Seqment üzrə xətalar. Uğursuz loader ən yaxın
errorElement-i render edir; ondan yuxarıdakı layout-lar ekranda qalır.
Loader-lər data cache-ini əvəz etmir. TanStack Query, SWR və ya framework-ün cache-i yenə də təkrar sorğuları birləşdirir və datanı revalidate edir; loader-lər isə yükləmənin nə vaxt başlayacağına qərar verir.
Hər route üçün code splitting
Route-lar təbii bölünmə nöqtələridir: /settings-də olan istifadəçiyə /reports-un qrafik kitabxanası lazım deyil. <Suspense> ilə React.lazy() komponenti bölür, amma import yalnız komponent render olunanda, valideynindən sonra başlayır. Router səviyyəsindəki lazy (yuxarıdakı kimi) route modulunu naviqasiya zamanı, valideynin datası ilə paralel yükləyir. Gecikmənin qalanını prefetch gizlədir: Next.js-in <Link>-i production-da link görünüşə daxil olanda route-u prefetch edir, bir çox router isə üzərinə gəlmə və ya fokus zamanı prefetch edir.
Müsahibədə adını çəkməli olduğun kompromis: hər prefetch trafik və server işi deməkdir, ona görə bütün tətbiqi yox, ehtimal olunan növbəti addımları (görünən linklər, üzərinə gəlmə niyyəti) prefetch et.
The naive SPA fetches inside components, in effects. /projects/7/tasks renders ProjectLayout, whose effect fetches the project; when it arrives, TaskList renders and its effect fetches the tasks; then each task row fetches its assignee. Every request starts only after the previous component has rendered: a waterfall. With a lazily loaded route it gets worse, because the code has to arrive before the first fetch can even start.
effects: [route JS] → [project] → [tasks] → [assignees] → done
loaders: [route JS]
[project]
[tasks] → render once, doneRoute loaders
The router knows from the URL alone which routes match, before anything renders. So it can start the data requests of every matched route in parallel at navigation time, or even earlier when a link is hovered:
const router = createBrowserRouter([
{
path: "/projects/:projectId",
element: <ProjectLayout />,
loader: async ({ params, request }) => {
const res = await fetch(`/api/projects/${params.projectId}`, { signal: request.signal });
if (!res.ok) throw new Response("Not found", { status: res.status });
return res.json();
},
errorElement: <ProjectError />,
children: [
{
path: "tasks",
lazy: () => import("./routes/tasks.jsx"),
},
],
},
]);What a good loader setup gives you:
- Parallel requests. The parent's and the child's data load at the same time; the screen renders once with everything it needs.
- Cancellation. When the user navigates again, the previous navigation's
request.signalis aborted. Without this, a slow response for/projects/1can arrive after the fast one for/projects/2and overwrite the newer screen. Whatever the router, the rule is "the latest navigation wins". - Pending UI. Keep the old screen with a progress indicator (
useNavigation().state === "loading") instead of flashing an empty page, or show a skeleton for slow data. - Errors per segment. A failed loader renders the nearest
errorElement; the layouts above it stay on screen.
Loaders do not replace a data cache. TanStack Query, SWR or the framework's cache still deduplicate and revalidate; loaders decide when loading starts.
Code splitting per route
Routes are natural split points: someone on /settings does not need the chart library of /reports. React.lazy() with <Suspense> splits a component, but the import starts only when it renders, after its parent. A router-level lazy (above) loads the route module during navigation, in parallel with the parent's data. Prefetching hides the rest of the latency: Next.js's <Link> prefetches routes in production when the link scrolls into view, and many routers prefetch on hover or focus.
The trade-off to name in interviews: every prefetch costs bandwidth and server work, so prefetch likely next steps (visible links, hover intent), not the whole app.
After navigation: scroll, focus and announcing the page
Brauzerin hər sənəd naviqasiyasında gördüyü üç iş artıq router-in üzərinə düşür.
Scroll
İstifadəçi gözləyir ki, yeni səhifə yuxarıdan (və ya öz #fragment-indən) başlasın, Back isə onu olduğu yerə qaytarsın. Brauzerin öz bərpası (history.scrollRestoration = "auto", Baseline, yanvar 2020-dən geniş əlçatandır) yazı traversal ilə dəyişəndə işləyir, SPA-da isə bu çox vaxt tezdir: əvvəlki səhifənin datası hələ yüklənir, sənəd çox qısadır və mövqe itir. Ona görə router-lər "manual"-a keçir, scroll mövqeyini hər tarixçə yazısı üçün saxlayır (çox vaxt sessionStorage-da, yazının açarı ilə) və route öz məzmununu render etdikdən sonra bərpa edir. React Router-in <ScrollRestoration /> komponenti məhz bunu edir və scrollRestoration-u "manual" edir. Next.js-in <Link>-i yeni səhifə artıq görünürsə scroll mövqeyini saxlayır, əks halda yeni səhifə seqmentinin əvvəlinə scroll edir. Səhifənin içindəki scroll olunan panellər də eyni yanaşma tələb edir, yoxsa uzun sidebar siyahısı yenidən yuxarı atılır.
Fokus
Linkə klikləyəndən sonra fokus həmin linkdə olur. Sonra router məzmunu əvəz edir:
- link əvəzlənən məzmunun içində idisə, silinir və fokus
<body>-yə düşür; - daimi naviqasiyada idisə, fokus orada qalır və klaviatura istifadəçisi yeni məzmuna çatmaq üçün bütün menyunu yenidən Tab ilə keçməli olur;
- hər iki halda screen reader-ə yeni səhifə haqqında heç nə deyilmir.
Adi həll fokusu yeni səhifənin əsas başlığına köçürməkdir: bu, screen reader-in onu oxumasını təmin edir və növbəti Tab-ı məzmuna yönəldir:
function afterNavigation(title) {
document.title = `${title} · Shop`;
const heading = document.querySelector("main h1");
if (heading) {
heading.setAttribute("tabindex", "-1");
heading.focus({ preventScroll: true });
}
}preventScroll: true scroll-u yuxarıdakı scroll məntiqinin öhdəsinə buraxır. Alternativlər səhifənin yuxarısındakı wrapper-i və ya skip link-i fokuslamaqdır, bu da yeni səhifə yüklənməsini təqlid edir. Səhifə dəyişikliyi olmayan hallarda fokusu köçürmə: ?q=-nu yeniləyən axtarış sahəsinə yazmaq, hash-i yeniləyən tab-lar arasında keçid, modal route-un açılması. İnsan yazarkən fokusun başqa yerə atılması fokus idarəetməsinin olmamasından daha pisdir.
Navigation API-də bunun üçün default davranış var: tutulmuş naviqasiyanın handler-i bitəndə focusReset: "after-transition" autofocus olan birinci elementi və ya <body>-ni fokuslayır. Öz məntiqini işlətmək üçün focusReset: "manual" ötür.
Səhifənin elan olunması
Hər route-da document.title-ı yenilə: brauzer onu tab-larda və tarixçədə göstərir, screen reader-lər isə əsl səhifə yüklənməsində məhz onu elan edir. Klient tərəfində naviqasiya üçün polite live region-da elan ("Order history") əlavə et və ya framework-ə güvən: Next.js-in hazır route announcer-i əvvəlcə document.title-ı, sonra birinci <h1>-i, sonra pathname-i oxuyur. Cari naviqasiya linkini aria-current="page" ilə işarələ.
Yavaş naviqasiyalarda istifadəçiyə nəyinsə baş verdiyini də bildir: görünən progress göstəricisi, uzun gözləmələrdə isə polite status mesajı. Live region-ları ARIA, accessible name və fokus idarəetməsi mövzusu ətraflı izah edir.
Three things the browser does on every document navigation are now the router's job.
Scroll
Users expect a new page to start at the top (or at its #fragment) and Back to return to where they were. The browser's own restoration (history.scrollRestoration = "auto", Baseline widely available since January 2020) runs when the entry is traversed, which in an SPA is often too early: the previous page's data is still loading, the document is too short, and the position is lost. Routers therefore switch to "manual", save the scroll position per history entry (often in sessionStorage, keyed by the entry), and restore it after the route has rendered its content. React Router's <ScrollRestoration /> does this and sets scrollRestoration to "manual". Next.js's <Link> keeps the scroll position when the new page is already visible and otherwise scrolls to the top of the new page segment. Scrollable panels inside the page need the same treatment, or a long sidebar list jumps back to the top.
Focus
After a click on a link, focus is on that link. Then the router replaces the content:
- if the link was inside the replaced content, it is removed and focus falls back to
<body>; - if it was in a persistent navigation, focus stays there, and keyboard users must tab through the whole menu again to reach the new content;
- either way, a screen reader is told nothing about the new page.
The common fix is to move focus to the new page's main heading, which makes the screen reader read it and puts the next Tab into the content:
function afterNavigation(title) {
document.title = `${title} · Shop`;
const heading = document.querySelector("main h1");
if (heading) {
heading.setAttribute("tabindex", "-1");
heading.focus({ preventScroll: true });
}
}preventScroll: true leaves scrolling to the scroll logic above. Alternatives are focusing a wrapper or a skip link at the top of the page, which mimics a fresh page load. Do not move focus for changes that are not page changes: typing in a search box that updates ?q=, switching tabs that update the hash, opening a modal route. Focus jumping away while someone types is worse than no focus management.
The Navigation API has a default for this: after an intercepted navigation's handler finishes, focusReset: "after-transition" focuses the first element with autofocus, or <body>. Pass focusReset: "manual" to use your own logic.
Announcing the page
Update document.title on every route: it is what the browser shows in tabs and history, and what screen readers announce on a real page load. For client-side navigation, add an announcement in a polite live region ("Order history"), or rely on the framework: Next.js's built-in route announcer reads document.title, then the first <h1>, then the pathname. Mark the current navigation link with aria-current="page".
For slow navigations, also tell users something is happening: a visible progress indicator, and for long waits a polite status message. The ARIA, accessible names and focus management topic covers live regions in detail.
Interview tips
30 saniyəlik cavab. "Klient router-i eyni origin-ə aid link kliklərini tutur, sənəd yükləmədən URL-i history.pushState() ilə yeniləyir, yolu sıralanmış route cədvəli ilə müqayisə edir və uyğun gələn route-ları layout-dan səhifəyə qədər iç-içə render edir. popstate-də Back və Forward üçün yenidən render edir. Brauzer artıq naviqasiya etmədiyi üçün onun işlərini router öz üzərinə götürür: deep link-lər üçün serverdə fallback lazımdır, data yükləməni, scroll-u, fokusu və səhifə başlığını isə router idarə edir."
Gözlənilən suallar
- Kiçik bir router yaz.
pushState,popstatelistener-i, parametrləri olan matcher.pushState()-inpopstate-i işə salmadığını açıq de və tutulmamalı olan klikləri sadala. - Hash, yoxsa history routing? Server konfiqurasiyası, server render, crawler-lər üçün görünmə, təmiz URL-lər və hash routing-in hələ də mənalı olduğu yerlər.
/dashboard/settings-i yeniləyəndə production-da 404 alınır, lokalda isə yox. Niyə? Dev server-də fallback var, production hostda yoxdur; həmçinin nisbi asset yolları və hər şeyə 200 verən soft 404.- Router
/users/newilə/users/:idarasında necə seçim edir? Elan sırasına görə yox, dəqiqliyə görə sıralama ilə. - Naviqasiya zamanı səhifə yavaş hiss olunur. Nəyə baxarsan? Effektlərdəki sorğuların waterfall-ı, paralel işləyən loader-lər, route səviyyəsində code splitting, prefetch, boş ekran əvəzinə gözləmə UI-ı.
- İki sürətli klik səhv səhifəni göstərir. Niyə? Race condition: əvvəlki naviqasiyanın sorğularını abort et və ya sonuncu naviqasiyaya aid olmayan nəticələri nəzərə alma.
- Klient tərəfində naviqasiya əlçatandırmı? Fokus, başlıq, elanlar, scroll-un bərpası.
- Filtr state-i harada yaşamalıdır? URL-də; ayrı-ayrı seçimlər üçün push, yazı üçün replace.
Bal itirdən səhvlər
- Əsl
<a href>əvəzinədivvə yabuttonüzərindəonClickilə naviqasiya. pushState()-dən sonrapopstategözləmək və yahistory.back()-dən dərhal sonralocation-u oxumaq.- Klient tərəfindəki guard-ı giriş nəzarəti kimi qəbul etmək.
- Server fallback-i, 404 statusunu və ya nisbi asset URL-lərini unutmaq.
- Hər düymə basışına bir tarixçə yazısı.
Senior səviyyəni göstərən məqamlar
Alətlərdən yox, kompromislərdən danış. Server render ilə MPA nə vaxt daha yaxşı məhsuldur? Navigation API-yə (Baseline 2026) keçid nə qazandırır və hələ hansı fallback lazımdır? Prefetch trafik və server yükü baxımından nəyə başa gəlir? URL-lərə public API kimi bax: sabit, paylaşıla bilən, dəyişəndə redirect-lərlə. Və yalnız ilk yüklənməni yox, naviqasiyaları da ölç: route keçidləri qarşılıqlı əlaqədir, ona görə INP-yə və klik → məzmun üçün öz zaman nişanlarına bax.
A 30-second answer. "A client-side router intercepts same-origin link clicks, updates the URL with history.pushState() without loading a document, matches the path against a ranked route table and renders the matched routes, nested from layout to page. On popstate it renders again for Back and Forward. Because the browser no longer navigates, the router takes over its jobs: the server needs a fallback for deep links, and the router handles data loading, scroll, focus and the page title."
Questions you are likely to get
- Implement a tiny router.
pushState, apopstatelistener, a matcher with params. Say out loud thatpushState()does not firepopstate, and list the clicks you must not intercept. - Hash or history routing? Server configuration, server rendering, crawlability, clean URLs, and where hash routing still makes sense.
- Refreshing
/dashboard/settingsgives a 404 in production but not locally. Why? The dev server has a fallback, the production host does not; also relative asset paths and the 200-for-everything soft 404. - How does the router choose between
/users/newand/users/:id? Ranking by specificity, not declaration order. - The page feels slow on navigation. What do you look at? Waterfalls of effect-based fetches, loaders in parallel, route-level code splitting, prefetching, pending UI instead of blank screens.
- Two quick clicks show the wrong page. Why? A race: abort the previous navigation's requests, or ignore results that are not from the latest navigation.
- Is client-side navigation accessible? Focus, title, announcements, scroll restoration.
- Where should filter state live? In the URL; push for discrete choices, replace for typing.
Mistakes that cost points
- Navigating with
onClickon adivor abuttoninstead of a real<a href>. - Expecting
popstateafterpushState(), or readinglocationright afterhistory.back(). - Treating a client-side guard as access control.
- Forgetting the server fallback, the 404 status, or relative asset URLs.
- One history entry per keystroke.
Senior signal
Discuss trade-offs instead of tools. When is an MPA with server rendering the better product? What does adopting the Navigation API (Baseline 2026) buy you, and what fallback does it still need? What does prefetching cost in bandwidth and server load? Treat URLs as a public API: stable, shareable, with redirects when they change. And measure navigations, not just the first load: route transitions are interactions, so watch INP and your own timing marks for click → content.
What to check when reviewing client-side routing
Bu siyahını özün yazmadığın routing kodunu review edəndə işlət: komanda yoldaşının, kitabxananın və ya AI assistentin kodunu. Hər bənd brauzerin sənəd naviqasiyasında özü gördüyü bir işdir; birini buraxsan, Back işləmir, paylaşılan link 404 göstərir və ya screen reader susur.
- Naviqasiya əsl
<a href>ilə edilirmi və router-in tutmamalı olduğu kliklər brauzerə buraxılırmı?onClick-lidiv"Open in new tab"-ı və crawler-ləri itirir. Ctrl/⌘+klik, Shift+klik,target="_blank",downloadvə başqa origin-lərə aparan linklər brauzerə toxunulmadan çatmalıdır. - Kod
pushState()-dən dərhal sonra, bir dəpopstate-də render edirmi?pushState()heç bir hadisə işə salmır. Linkə kliklə, sonra Back və Forward düymələrini bas: ekran URL-in ardınca dəyişməlidir. - Deep link production build-də işləyirmi?
/products/42səhifəsini dev server-də yox, deploy olunmuş build-də yenilə. Hostda real faylları və/api/*yollarını kənarda saxlayan, qalan URL-lərəindex.htmlqaytaran fallback olmalıdır; Network panelində skriptlər kökdən başlayan URL-lərdən yüklənməli, HTML kimi qayıtmamalıdır. - Guard-lar redirect-i replace ilə edirmi və
next-i yoxlayırmı? Push ilə edilən redirect Back düyməsini redirect dövrəsinə salır. Yalnız tək/ilə başlayan və ardınca\gəlməyənnext-i qəbul et://evil.examplevə/\evil.examplebaşqa saytdır. Klient guard-ları UX-dir: girişi API də yoxlamalıdır. - URL state-i şüurlu şəkildə push və ya replace olunurmu, yoxlanılırmı? Axtarış sahəsinə yazmaq replace etməlidir, yoxsa Back hər hərfi bir-bir gəzəcək. Parametrlər sətirdir:
?page=abcvə/users/abcünvanlarını sına, kodun yıxılmasını yox, defolt dəyəri və ya "not found" görünüşünü gözlə. - Naviqasiyadan sonra səhifə başlığı, fokus və scroll idarə olunurmu?
document.titledəyişməli, fokus əsas başlığa keçməli (tabindex="-1"), yeni səhifələr yuxarıdan başlamalı, Back isə köhnə mövqeyi bərpa etməlidir. Növbəti Tab yeni məzmuna düşməlidir.
Use this list for routing code you did not write: a teammate's, a library's or an AI assistant's. Each check is a job the browser does on a document navigation; skip one and Back breaks, shared links show a 404, or screen readers stay silent.
- Is every navigation a real
<a href>, and are the clicks the router must not take left alone? AdivwithonClickloses "Open in new tab" and crawlers. Ctrl/⌘+click, Shift+click,target="_blank",downloadand links to other origins must reach the browser untouched. - Does the code render right after
pushState(), and again onpopstate?pushState()fires no event. Click a link, then press Back and Forward: the screen must follow the URL. - Does a deep link work in the production build? Reload
/products/42on the deployed build, not the dev server. The host needs a fallback toindex.htmlthat skips real files and/api/*; in the Network panel, scripts must load from root-relative URLs, not come back as HTML. - Do guards redirect with replace and validate
next? A pushed redirect sends Back into a redirect loop. Accept only anextthat starts with a single/and no\after it://evil.exampleand/\evil.exampleare another site. Client guards are UX: the API must check access too. - Is URL state pushed or replaced on purpose, and validated? Typing in a search box should replace, or Back walks through every letter. Params are strings: try
?page=abcand/users/abc, and expect a default or "not found", not a crash. - After a navigation, are the title, focus and scroll handled?
document.titlechanges, focus moves to the main heading (tabindex="-1"), new pages start at the top, and Back restores the old position. The next Tab should land in the new content.
Check your understanding
Practise this
Hands-on work that uses this topic.