Skip to main content
0 reactions

TanStack Start Tutorial — Part 3: Pages and Links: File-Based Routing

Card titled Pages and Links: File-Based Routing, labelled TanStack Start Tutorial Part 3, with three files in src/routes, index.tsx, about.tsx and books/index.tsx, each pointing to its address: /, /about and /books.
TanStack Start Tutorial, Part 3: Pages and Links.

In TanStack Start, you add a page by adding a file. This is called file-based routing: every file in src/routes is a page, and the file’s name sets the page’s address. In this part, you use it to grow the Bookshop from one page to three, and link the pages together.

This is Part 3 of the TanStack Start Tutorial, a free, hands-on course for complete beginners. You continue the Bookshop, the small website you started in Part 2.

By the end of this part, you’ll have:

  • an About page at /about and a Books page at /books
  • a header that links every page and shows which page is open
  • a friendly page for addresses that don’t exist, in place of the plain “Not Found”

This is Part 3 of the TanStack Start Tutorial. The parts in Module A, Start Here:

All parts of the TanStack Start Tutorial

Module A: Start Here

Module B: Routing

  • Part 4: Dynamic Routes and Path Params
  • Part 5: Search Params: Type-Safe Filters and Sorting
  • Part 6: Layouts, Nested Routes and Navigation in Code

Module C: Data

  • Part 7: Load Data with Route Loaders
  • Part 8: Server Functions
  • Part 9: Forms and Mutations
  • Part 10: TanStack Query with TanStack Start
  • Part 11: Streaming and Deferred Data

Module D: Server

  • Part 12: What Runs Where: the Execution Model
  • Part 13: Environment Variables and Secrets
  • Part 14: Server Routes: Build a JSON API
  • Part 15: Middleware and Context
  • Part 16: Errors and Not Found Pages

Module E: Database

  • Part 17: Connect PostgreSQL with Drizzle ORM
  • Part 18: Create, Edit and Delete Data

Module F: Sign-In

  • Part 19: Sessions and Cookies
  • Part 20: Protected Routes
  • Part 21: Sign-In with Better Auth: Email and GitHub

Module G: Rendering

  • Part 22: Server-Side Rendering and Hydration Errors
  • Part 23: Selective SSR and SPA Mode
  • Part 24: Static Prerendering and ISR

Module H: Look and SEO

  • Part 25: Style with Tailwind CSS
  • Part 26: SEO: Titles, Meta Tags, Sitemap and Structured Data

Module I: Ship

  • Part 27: Test Your App with Vitest
  • Part 28: Production Build and Checklist
  • Part 29: Deploy to Netlify for Free with a Neon Database
  • Part 30: Final Project, Cheat Sheet and What to Learn Next

Cost: free. Everything in this part runs on your own computer.

Every command and output on this page is real, run with TanStack Start 1 on Node.js 26.

Prerequisites

Where Your Project Is Now

At the end of Part 2, the Bookshop has one page, its home page. If you’re starting with this part, create the app with Part 2’s steps, then make sure src/routes/index.tsx matches this file:

src/routes/index.tsxTypeScript
import { createFileRoute } from "@tanstack/react-router";

export const Route = createFileRoute("/")({ component: Home });

function Home() {
	return (
		<main className="mx-auto max-w-2xl p-8">
			<h1 className="text-4xl font-bold">Welcome to the Bookshop</h1>
			<p className="mt-4 text-lg">Find your next favourite book.</p>
			<h2 className="mt-8 text-2xl font-semibold">Featured books</h2>
			<ul className="mt-2 list-disc pl-6 text-lg">
				<li>The Paper Lantern Café</li>
				<li>Salt and Starlight</li>
			</ul>
		</main>
	);
}

Step 1: Add an About Page

Start the dev server from the bookshop folder, if it isn’t already running:

TerminalBash
npm run dev

In your code editor, create a new file named about.tsx in the src/routes folder. As soon as you save the empty file, TanStack Start fills it with starter code that shows Hello "/about"!, because the dev server watches that folder. Replace all of it with this:

src/routes/about.tsxTypeScript
import { createFileRoute } from "@tanstack/react-router";

export const Route = createFileRoute("/about")({ component: About });

function About() {
	return (
		<main className="mx-auto max-w-2xl p-8">
			<h1 className="text-4xl font-bold">About the Bookshop</h1>
			<p className="mt-4 text-lg">
				The Bookshop is a small online shop for hand-picked novels.
			</p>
		</main>
	);
}

Two parts make this file a page:

  • createFileRoute("/about") connects the file to the address /about. TanStack Start writes this address for you from the file name, so it always matches the file.
  • The About component returns what the page shows, and component: About tells TanStack Start to use it for this address.

Open http://localhost:3000/about in your browser:

The Bookshop’s new About page in a browser, with the heading About the Bookshop and one line about the shop.
The About page, made from one file: src/routes/about.tsx.

Step 2: Add a Books Page in a Folder

A folder in src/routes adds its name to the address of every page inside it. Create a folder named books in src/routes, and in it a file named index.tsx. A file named index.tsx is the page at its folder’s own address, so this one is the page at /books, just as src/routes/index.tsx is the page at /:

src/routes/books/index.tsxTypeScript
import { createFileRoute } from "@tanstack/react-router";

export const Route = createFileRoute("/books/")({ component: Books });

function Books() {
	return (
		<main className="mx-auto max-w-2xl p-8">
			<h1 className="text-4xl font-bold">Books</h1>
			<ul className="mt-4 list-disc pl-6 text-lg">
				<li>The Paper Lantern Café by Mira Kale</li>
				<li>A Map of Quiet Places by Tomas Vell</li>
				<li>The Clockmaker’s Garden by Mira Kale</li>
				<li>Salt and Starlight by Nadia Quill</li>
			</ul>
		</main>
	);
}

TanStack Start writes this address as "/books/", with a slash at the end, which is how it names the index page of a folder. Visitors still open it at /books. Part 4 adds a page for every book in the same folder.

Open http://localhost:3000/books:

The Bookshop’s Books page with the heading Books and four books with their authors, from The Paper Lantern Café by Mira Kale to Salt and Starlight by Nadia Quill.
The Books page at /books, from src/routes/books/index.tsx.

Each time you add a page, TanStack Start also adds it to src/routeTree.gen.ts, the list of all your pages. It writes that file for you, so never change it by hand.

Visitors need a way to move between the pages. The root route, src/routes/__root.tsx, wraps every page, so a header you add there shows on all of them.

Open src/routes/__root.tsx. Add Link to the names it imports from @tanstack/react-router:

src/routes/__root.tsx (excerpt)TypeScript
import {
	createRootRoute,
	HeadContent,
	Link,
	Scripts,
} from "@tanstack/react-router";

Then add this header right after the <body> tag, above {children}:

src/routes/__root.tsx (excerpt)TypeScript
<header className="border-b border-gray-200">
	<nav className="mx-auto flex max-w-2xl gap-6 px-8 py-4 text-lg">
		<Link to="/">Home</Link>
		<Link to="/books">Books</Link>
		<Link to="/about">About</Link>
	</nav>
</header>

What each part does:

  • Link is TanStack Router’s link. It becomes a normal link in the page, so visitors can still open it in a new tab, but a click changes the page without loading the whole site again.
  • to is the address of the page. TypeScript checks it against your pages, so a mistyped address shows up as an error.
  • {children} is the page that’s open, so the header sits above every page.

Save the file. The header appears on every page:

The Bookshop home page with a new header of three links, Home, Books and About, above the welcome heading.
The header from the root route shows on every page.

Click Books and About: the page changes at once, and the header stays where it is.

Step 4: Show Which Page Is Open

A header should also show visitors where they are. Link takes an activeProps option: settings it adds only while its page is open. Change the three links in the header to this:

src/routes/__root.tsx (excerpt)TypeScript
<nav className="mx-auto flex max-w-2xl gap-6 px-8 py-4 text-lg">
	<Link to="/" activeProps={{ className: "font-bold" }}>
		Home
	</Link>
	<Link to="/books" activeProps={{ className: "font-bold" }}>
		Books
	</Link>
	<Link to="/about" activeProps={{ className: "font-bold" }}>
		About
	</Link>
</nav>

activeProps={{ className: "font-bold" }} gives the link of the open page the Tailwind CSS class font-bold, which makes its text bold. Open the Books page:

The Books page with the header link Books in bold, while Home and About stay in normal text.
The link of the open page is bold.

A link is also active on the pages under its address. When Part 4 adds a page for each book, Books stays bold on all of them.

Step 5: Add a Page for Addresses That Don’t Exist

Open an address that has no page, such as http://localhost:3000/nope. TanStack Start shows its plain default page:

A browser showing only the words Not Found at the top left, the default page TanStack Router shows for an address with no page.
The default page for an address that doesn’t exist.

The terminal that runs the dev server also prints a warning, and it names the fix:

Output (the lines that matter)Plain text
8:34:16 AM [vite] (client) [console.warn] Warning: A notFoundError was encountered on the route with ID "__root__", but a notFoundComponent option was not configured, nor was a router level defaultNotFoundComponent configured. Consider configuring at least one of these to avoid TanStack Router's overly generic defaultNotFoundComponent (<p>Not Found</p>)

In src/routes/__root.tsx, add the notFoundComponent option to createRootRoute, and add the NotFound component below it:

src/routes/__root.tsx (excerpt)TypeScript
	notFoundComponent: NotFound,
	shellComponent: RootDocument,
});

function NotFound() {
	return (
		<main className="mx-auto max-w-2xl p-8">
			<h1 className="text-4xl font-bold">Page not found</h1>
			<p className="mt-4 text-lg">There is no page at this address.</p>
			<Link to="/" className="mt-4 inline-block text-lg underline">
				Go to the home page
			</Link>
		</main>
	);
}

notFoundComponent is the page TanStack Start shows when no page matches the address. It appears inside the root route, so the header stays, and its Link takes visitors back to the home page. Open http://localhost:3000/nope again:

The Bookshop’s custom 404 page with the header links, the heading Page not found, the line There is no page at this address, and a link to the home page.
The custom 404 page keeps the header and links back home.

The warning doesn’t appear any more.

The Complete Root Route

src/routes/about.tsx and src/routes/books/index.tsx are complete as shown in Steps 1 and 2. This is the complete src/routes/__root.tsx:

src/routes/__root.tsxTypeScript
import { TanStackDevtools } from "@tanstack/react-devtools";
import {
	createRootRoute,
	HeadContent,
	Link,
	Scripts,
} from "@tanstack/react-router";
import { TanStackRouterDevtoolsPanel } from "@tanstack/react-router-devtools";

import appCss from "../styles.css?url";

export const Route = createRootRoute({
	head: () => ({
		meta: [
			{
				charSet: "utf-8",
			},
			{
				name: "viewport",
				content: "width=device-width, initial-scale=1",
			},
			{
				title: "TanStack Start Starter",
			},
		],
		links: [
			{
				rel: "stylesheet",
				href: appCss,
			},
		],
	}),
	notFoundComponent: NotFound,
	shellComponent: RootDocument,
});

function NotFound() {
	return (
		<main className="mx-auto max-w-2xl p-8">
			<h1 className="text-4xl font-bold">Page not found</h1>
			<p className="mt-4 text-lg">There is no page at this address.</p>
			<Link to="/" className="mt-4 inline-block text-lg underline">
				Go to the home page
			</Link>
		</main>
	);
}

function RootDocument({ children }: { children: React.ReactNode }) {
	return (
		<html lang="en">
			<head>
				<HeadContent />
			</head>
			<body>
				<header className="border-b border-gray-200">
					<nav className="mx-auto flex max-w-2xl gap-6 px-8 py-4 text-lg">
						<Link to="/" activeProps={{ className: "font-bold" }}>
							Home
						</Link>
						<Link to="/books" activeProps={{ className: "font-bold" }}>
							Books
						</Link>
						<Link to="/about" activeProps={{ className: "font-bold" }}>
							About
						</Link>
					</nav>
				</header>
				{children}
				<TanStackDevtools
					config={{
						position: "bottom-right",
					}}
					plugins={[
						{
							name: "Tanstack Router",
							render: <TanStackRouterDevtoolsPanel />,
						},
					]}
				/>
				<Scripts />
			</body>
		</html>
	);
}

Clean Up

Stop the dev server: click in the terminal and press Ctrl+C. Keep the bookshop folder, because Part 4 continues from it.

Common Mistakes

MistakeWhat happensDo this instead
Saving a page file outside src/routesIt never becomes a pageKeep every page in src/routes
Linking a page with <a href="/about">Every click loads the whole site againUse <Link to="/about">
Naming a file 404.tsx for the 404 pageYou get an ordinary page at the address /404Use notFoundComponent on the root route
Editing src/routeTree.gen.tsTanStack Start writes over your changesChange the files in src/routes

Troubleshooting

ProblemFix
A new page shows Not FoundCheck that the file is in src/routes, that its name matches the address, and that the dev server is running.
npx tsc reports Type '"/abuot"' is not assignable to type '"." | ".." | "/" | "/about" | "/books"'The address in to has a typo. Use one of the addresses the error lists.
The terminal warns A notFoundError was encountered on the route with ID "__root__", but a notFoundComponent option was not configuredAdd notFoundComponent to the root route, as in Step 5.
A new, empty route file fills itself with codeThat’s TanStack Start’s starter code for the page. Replace it with your own.

FAQ

Do I need to register a new page anywhere? No. Saving the file in src/routes is enough: TanStack Start adds the page to src/routeTree.gen.ts for you.

What’s the difference between Link and a normal <a> tag? Link renders an <a> tag with a real address, so it works like any link, but a click moves to the new page inside the app instead of loading the whole site again (TanStack Router’s navigation guide (opens in a new tab)).

Does the 404 page send a real 404 status? Yes. For an address with no page, the server answers with the status code 404 together with your NotFound page, which tells browsers and search engines that the page doesn’t exist. TanStack Start’s production checklist (opens in a new tab) asks for exactly that.

Can a folder hold more pages than index.tsx? Yes. A file at src/routes/books/new.tsx would be the page at /books/new.

Conclusion

The Bookshop now has three pages, one file each in src/routes. You linked them from a header in the root route, showed which page is open with activeProps, and gave wrong addresses a friendly page with notFoundComponent. That’s file-based routing: your files decide your pages.

← Previous: Part 2: Create Your First TanStack Start App

Coming next: Part 4: Dynamic Routes and Path Params.

Additional Resources

TanStack, React and other names mentioned are trademarks of their respective owners. JD Bots isn’t affiliated with or endorsed by TanStack.

0 comments