File-based routing for React apps
better-router is a Vite plugin that maps files in src/routes to React pages and API endpoints.
Add betterRouter() to vite.config.ts and your folder tree becomes the router — with SSR, typed loaders, and SPA navigations. No central route config.
APIs may change. Install better-router@alpha and pin the version you ship.
Project layout
Setup
Create a Vite React app, enable the plugin, then add your first route file.
Install
Add the plugin
index.html and src/main.tsx. Enable better-router in vite.config.ts:Add a route
src/routes. Each file becomes a URL:One plugin, three pieces
better-router sits inside Vite. It scans your route files at dev and build time, generates a Hono server, and wires React pages to URLs.
Vite plugin
betterRouter() into vite.config.ts. The dev server hot-reloads routes when you add or rename files. vite build emits the same app for Node, Bun, Deno, or Cloudflare Workers.React pages
.tsx files are React route components. The first visit is server-rendered HTML. <Link> navigations fetch JSON and swap the page. Colocated .server.tsx files export typed loaders and actions.Server Routes
src/routes and generates a Hono app. Folder names and file names define URLs. Dynamic segments like [id].tsx, nested layouts in _layout.tsx, and API handlers in api/*.ts follow predictable conventions — no manual route table.How a request is routed
Every request runs through the Hono app the plugin generates. Middleware runs first, then loaders, then the React page or API handler.
Match the file route
src/routes. Dynamic segments like [id].tsx and catch-alls like [...slug].tsx follow normal file-based conventions.Run middleware and loaders
src/middleware and nested _middleware.ts files run with (c, next). Layout and page loaders in .server.tsx files fetch data on the server.Render React or return JSON
<Link> navigations fetch JSON and swap the page. API routes export GET, POST, and other HTTP methods directly.Route modules
Special files start with _ and are not routes. Colocate server logic next to the page with a matching stem.
Document shell
_document.tsx for HTML, title, and global CSS — no index.html or main.tsx.Layouts
_layout.tsx wraps nested UI inside #app. Markdown pages use the same tree.Loaders and actions
dashboard.server.tsx exports loader and action. Loader return types flow into the page props.Middleware
API routes
.ts files under src/routes export HTTP method handlers on the same Hono app.Read next
Start with a page and a loader, or jump to the part of the routing tree you are wiring up.
Quickstart
Routing
Layouts
Loaders and actions
SPA navigation
main.tsx — Link, loaders, and opt-out modes.