Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 87 ยท Routing and Navigation

Routing Concepts

Understand how single-page apps route without page reloads - route tables, dynamic params, hash versus history mode - and try a runnable route matcher.

In a traditional website, every URL is a separate request: you click a link, the browser asks the server for /users/42, and the server sends back a new HTML page. A single-page application (SPA) works differently. The server sends one HTML page and one JavaScript bundle. After that, your code decides what to show when the URL changes, and the page never fully reloads. That job is called client-side routing.

Vue's core library has no router, because it is a view library first. Routing is a concept you can learn independent of any tool, and once you understand it, Vue Router is easy to read. This lesson covers the ideas and builds a working route matcher. The next lesson, Build a Tiny Hash Router, wires it to the real browser URL.

What a client-side router does

Every router, in any framework, performs the same four jobs:

  1. Read the current location (the path, the query string and the hash).
  2. Match that location against a list of routes and pull out parameters, such as the 42 in /users/42.
  3. Render the component that belongs to the matched route.
  4. Navigate: change the location without a reload, and keep the back and forward buttons working.
flowchart LR
  A["User clicks a link"] --> B["Router intercepts<br/>the click"]
  B --> C["URL changes<br/>(no page reload)"]
  C --> D["Match URL against<br/>the route table"]
  D --> E["Render the matched<br/>component with params"]
  F["Back / forward button"] --> C

Navigation always flows through the same path: change the URL, match, render. The back button joins at the same place.

The route table

The heart of a router is a route table: a list of patterns, each tied to something to render. In Vue Router these entries are called route records. A plain version looks like this:

JavaScript
const routes = [
  { name: "home",        path: "/" },
  { name: "users",       path: "/users" },
  { name: "user-detail", path: "/users/:id" },
  { name: "not-found",   path: "*" }
];

A segment that starts with a colon, like :id, is a dynamic parameter: it matches any single segment and hands you its value. /users/42 matches user-detail with id = "42", and /users/ada matches it with id = "ada". Note that params are always strings: convert with Number() if you need a number.

The last entry, *, is a catch-all that produces the "404" page. It is last on purpose. In our simple matcher the first matching entry wins, so more specific patterns must come before general ones. (Vue Router ranks routes by specificity for you, so order matters less there, but putting the catch-all last is still a good habit.)

A route matcher you can run

Matching is just string handling. Turn each pattern into a regular expression, remember the parameter names, and test the path against each entry in order. Type a path (or press a sample button) and see what the matcher returns.

A route table and matcher

Try /users/ada/: the trailing slash is normalized away, so it matches user-detail with id: "ada". Try /blog/2025/hello-vue?ref=home: the matcher extracts two params from the path and puts ref into a separate query object, because the query string (after ?) is not part of route matching. And /nope falls through every pattern to the catch-all.

Pay attention to decodeURIComponent. A path such as /users/ana%20maria contains an encoded space; the param should hold ana maria. Always decode params, and never trust them: they come straight from whoever typed the URL.

Hash mode and history mode

A router has to read and change the URL. Browsers offer two ways, and they give two modes.

History mode uses the History API. Your app owns clean URLs like https://example.com/users/42:

JavaScript
history.pushState({}, "", "/users/42");           // change the URL without loading
window.addEventListener("popstate", renderRoute); // back and forward buttons

Hash mode keeps the route after a #, like https://example.com/#/users/42:

JavaScript
location.hash = "#/users/42";                       // change the URL without loading
window.addEventListener("hashchange", renderRoute); // fires on every hash change
flowchart TD
  subgraph H["History mode: https://app.com/users/42"]
    H1["Browser sends GET /users/42"] --> H2["Server must answer<br/>with index.html for every route"]
  end
  subgraph S["Hash mode: https://app.com/#/users/42"]
    S1["Browser sends GET /<br/>(the hash is never sent)"] --> S2["Server only needs<br/>to serve index.html once"]
  end

The hash fragment stays in the browser, which is why hash mode needs no server setup.

The trade-offs:

History mode Hash mode
URL Clean (/users/42) Has a #/ in it
Server setup Needed: unknown paths must serve index.html None
SEO Better (real paths), best with server rendering Poor: crawlers mostly ignore fragments
Works from a static file No Yes

With history mode, a user who opens https://example.com/users/42 directly (bookmark, shared link, page refresh) sends that exact path to your server. If the server only knows /, it returns a 404 before your JavaScript ever runs. The fix is a fallback rule on the server that sends index.html for any path that is not a real file. In nginx this is one line:

NGINX
location / {
  try_files $uri /index.html;
}

Because of that, hash mode is a practical choice for static hosting and for demos. The live examples on this site run inside a sandboxed frame where history.pushState throws an error, so every runnable router here uses hash routing or an in-memory history. The matching and rendering code is identical in both modes: only "read the location" and "change the location" differ. That is exactly how Vue Router is built: you pick createWebHistory() or createWebHashHistory() and the rest of your code stays the same.

History is a stack

Before we touch the real URL, it helps to see what "history" means. The browser keeps a list of visited locations and a pointer to the current one. Going forward to a new page (a push) adds an entry after the pointer and throws away everything that was ahead of it. Back and forward just move the pointer.

The next example keeps that list in a Vue ref instead of in the browser, so you can watch it. It uses the resolve function from the previous example and a dynamic component to render whatever the route matched.

An in-memory router with back and forward

Click Users, then a person, then Back twice. The pointer moves, and Forward is enabled. Now click Home while the pointer is in the middle: the entries ahead of the pointer disappear and Forward turns off again. This is the same behavior as the browser's own buttons, and it is the reason a "redirect" should replace the current entry instead of pushing a new one, otherwise Back would return you to the page that redirected.

What a real router adds

The matcher and stack above are the core. Production routers add a long list of conveniences, and Vue Router implements most of them:

  • Named routes and params-based navigation, so you write { name: "user-detail", params: { id: 42 } } instead of building strings.
  • Nested routes for layouts with a persistent shell and a changing inner area.
  • Navigation guards: functions that can cancel or redirect a navigation, for example to protect pages behind a login.
  • Lazy loading: loading a page's code only when someone visits it.
  • Scroll and focus handling: scrolling to the top on a new page, restoring the scroll position on Back.

You will meet these in Vue Router Basics and Vue Router Advanced Features.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does history mode need a server fallback rule but hash mode does not?

    A page refresh or shared link in history mode requests a path like /users/42 from the server. The fragment after # is never sent to the server, so in hash mode the server only ever sees /.
  2. 2. What does the route pattern /users/:id produce for the path /users/42?

    Route params come from the URL, so they are always strings. Convert with Number() when you need a number.
  3. 3. In a simple first-match-wins route table, where should the catch-all * route be?

    A catch-all matches every path. If it came first, no other route would ever be reached.
  4. 4. What happens to the forward entries when you push a new location while the history pointer is in the middle of the stack?

    A new navigation starts a new branch of history, so the entries that used to be ahead of the pointer are removed. Browsers behave the same way.

Summary

  • Client-side routing means JavaScript reads the URL, matches it against a route table and renders a component, without reloading the page.
  • A route table maps patterns to views. :name segments are dynamic params and are always strings; a final * catches unknown paths.
  • Query strings are separate from path matching.
  • History mode gives clean URLs but needs a server fallback to index.html; hash mode needs no server setup and works from static files.
  • The browser history is a stack with a pointer: a push discards forward entries, and back/forward move the pointer.
  • Everything a router does can be built on a matcher, a current-location value and a dynamic component.

Next, connect these ideas to the real browser URL: Build a Tiny Hash Router.