Chrysolites Tech Academy

Designing and Shipping Web Apps · Course book

Chapter 2: How a Router Connects URLs, Data and Access

Pairs with Lesson 2: Type-Safe Routing in React with TanStack Router

Every web app has to answer one question over and over: given the address in the browser, what should be on the screen? The part of an app that answers it is called the router. This chapter explains what a router does, why modern routers also take charge of loading data and guarding pages, and what "type-safe routing" means, using TanStack Router for the examples.

The URL as part of the app

On a traditional website, clicking a link asks the server for a brand-new page and the browser throws the old one away. A single-page application works differently. The browser loads one page and a bundle of JavaScript at the start; after that, the JavaScript swaps parts of the screen in and out by itself. This is client-side routing: the address changes and the view changes, but no full page is fetched.

It is tempting to treat the address bar as decoration in such an app. That is a mistake. The URL is the one piece of state that a user can bookmark, share in a message, open in a second tab or return to with the back button. If a search filter lives only in the app's memory, refreshing the page loses it. If it lives in the URL, the page can always be rebuilt exactly as it was. A good rule is that anything a user would expect to survive a refresh or a shared link belongs in the URL.

A URL has several parts, and a router reads two of them closely.

PartExampleWhat it is forTypical content
Path/meetups/42Says which screen to showThe names of sections and pages
Path parameterthe 42 in /meetups/42Identifies one particular itemAn ID or a short name
Search parameters?city=Lagos&page=2Adjusts how the screen is shownFilters, sorting, page numbers, open tabs
Hash#reviewsPoints to a position within the pageThe ID of a heading

The distinction between the two kinds of parameter matters. A path parameter is required: without the 42 there is no meetup to display. Search parameters are optional adjustments, and the page still makes sense without them.

Routes form a tree

Screens are usually nested. A dashboard has a header and a sidebar that stay put while the middle of the page changes. Routers model this as a route tree. The root route draws the outermost frame and leaves a gap, called an outlet, where its child route is drawn. That child may have an outlet of its own, and so on down the tree.

root layout //about/meetups/meetups//meetups/$id home pageabout pagesection layoutlist of meetupsone meetup
Figure 2.1 — A route tree. Visiting /meetups/42 matches three routes at once, shown in blue: the root layout, the meetups layout inside it, and the single-meetup page inside that.

In file-based routing you do not write this tree by hand. Each route is a file, and the folder structure is the tree: a file for the root, a file for the about page, a folder for the meetups section. A build tool reads the folders and generates the tree. In TanStack Router a file name containing a dollar sign, such as $id, marks a path parameter that matches any value.

To move between routes you use a link component instead of a plain anchor element, so the router can intercept the click and switch views without a page reload. When navigation has to happen from code, for instance after a form is saved, the router provides a navigate function that does the same job.

Loading data before the screen appears

Most screens need data. The older habit was to draw the component first and let it request its own data afterwards. With nested routes this causes a waterfall: the outer layout draws and fetches, and only when it finishes does the inner page draw and start its own fetch. The requests run one after another even though neither depends on the other.

A loader is a function attached to a route that fetches the route's data. Because the router knows every route that matches a URL before anything is drawn, it can start all their loaders together.

export const Route = createFileRoute('/meetups/$id')({
  loader: ({ params }) => fetchMeetup(params.id),
  component: MeetupPage,
})

function MeetupPage() {
  const meetup = Route.useLoaderData()
  return <h1>{meetup.title}</h1>
}

Suppose the meetups layout needs the user's profile, which takes 300 milliseconds, and the meetup page needs the meetup record, which takes 400. In a waterfall the screen is complete after 300 + 400 = 700 milliseconds. With loaders running side by side it is complete when the slower one finishes, after 400 milliseconds.

WaterfallLoaders one after anotherstarted together profile 300meetup 400profile 300meetup 400 0300400700time in milliseconds
Figure 2.2 — The same two requests arranged two ways. Starting them together cuts the wait from 700 ms to 400 ms.

Loaders bring two further benefits. The router can show a pending screen while a loader runs and an error screen if it fails, so each page no longer needs its own loading and error logic. And the router can begin loading a route when the pointer merely rests on a link, so the data is often ready before the click.

When the user changes data, for example by submitting a form, the loaded data is out of date. After the change succeeds, the app tells the router to invalidate its data, and the router runs the loaders for the current page again so the screen shows the new state.

Search parameters you can trust

Search parameters arrive as text typed into an address bar, so they can be missing, misspelled or nonsense. A URL ending in ?page=banana is perfectly legal. If the code assumes that page is a number, something will break.

The answer is to validate search parameters at the route boundary. Each route declares the shape it expects, usually with a schema library such as Zod, and supplies defaults for anything missing or invalid.

const searchSchema = z.object({
  city: z.string().optional(),
  page: z.number().int().min(1).catch(1),
})

This schema says that city is optional text and that page is a whole number of at least 1. The catch(1) at the end means "if the value fails those checks, use 1". The component then receives a page that is guaranteed to be a usable number, whatever was typed in the address bar. The same validated values can be passed straight to the loader, so changing a filter in the URL fetches the matching data.

Guarding routes and loading less code

Some pages are only for signed-in users. Checking inside the page component is too late, because by then the page has started to draw and its loader may already have asked for private data. The check belongs before loading starts. TanStack Router provides a hook for this called beforeLoad, which runs ahead of the loader and can redirect the visitor elsewhere.

beforeLoad: ({ context, location }) => {
  if (!context.auth.isSignedIn) {
    throw redirect({ to: '/login', search: { from: location.href } })
  }
}

The sign-in state reaches the guard through the router context, a container of shared values that is handed to every route. Placing the guard on a layout route protects every page beneath it in the tree at once. Remembering where the visitor was heading, as the from value does here, lets the login page send them on to the right place afterwards.

A guard is not security. Anything running in the browser can be altered by a determined user. A route guard is a courtesy that keeps people away from pages they cannot use. The server must still check permission on every request for data.

Routes are also a natural place to divide an app's code. With lazy routes, the code for a page is downloaded only when someone visits it, so the first load carries the home page alone and not every screen in the app. The router keeps the small, critical parts of each route, such as its loader, available at once and fetches the component code on demand.

What type safety adds

In many routers a link is just a piece of text. Rename a route or mistype an address, and nothing complains until a user clicks and reaches a missing page. A type-safe router closes that gap. Because the route tree is generated from your files, the TypeScript compiler knows every valid path, the parameters each one needs and the shape of its search parameters.

The effect is that mistakes surface while you type. A link to a path that does not exist is underlined as an error. A link to /meetups/$id that forgets to supply the id will not compile. Reading page from the search parameters gives a number, not a vague "something", because the schema said so. And when a route is renamed, every link that pointed to the old name fails at once and shows you exactly what to update.

The underlying idea is not tied to one library. Whichever router you use, the same questions apply: which parts of the state live in the URL, which route owns which data, where access is checked, and how much of all that the tools can verify for you before a user ever sees it.

Check your understanding

  • Why should a search filter usually be stored in the URL and not only in the app's memory?
  • In the address /products/17?sort=price, which part is a path parameter and which is a search parameter?
  • A layout's data takes 250 ms to load and its child page's data takes 600 ms. How long until the screen is complete in a waterfall, and how long with parallel loaders? (Answer: 250 + 600 = 850 ms in a waterfall, 600 ms in parallel.)
  • With the schema shown in this chapter, what value does page have for the URL ?page=banana? (Answer: 1, the fallback given by catch.)
  • Why is a route guard in the browser not enough to protect private data?
  • What happens at compile time in a type-safe router if you rename a route but forget to update a link to it?

Install Chrysolites Tech Academy

Android / Chrome / Edge: open the browser menu and choose Install app or Add to Home screen.

iPhone / iPad (Safari): tap the Share button, then Add to Home Screen.