Svelte 5 File-Based Micro-Router
A lightweight, zero-dependency routing engine for Svelte 5 and Vite. This project brings the "File-based Routing" experience of SvelteKit to standard Single Page Applications (SPA).
📖 What is it?
This is a client-side router that uses Vite’s dynamic scanning capabilities (import.meta.glob) to automatically turn your .svelte files into reachable URLs.
- No manual route definitions: If the file exists in
/routes, the URL exists. - Svelte 5 Native: Uses the new Runes system (
$state,$props) for reactive route matching. - Automatic Navigation: Intercepts standard
<a>tags to prevent page refreshes.
⚙️ Installation & Setup
1. Project Requirements
You must be using Vite and Svelte 5.
npm install svelte@next
2. Vite Configuration
Ensure your vite.config.js is configured to handle Svelte. No special router plugin is needed, but an alias is recommended for cleaner pathing:
// vite.config.js
import { defineConfig } from 'vite';
import { svelte } from '@sveltejs/vite-plugin-svelte';
import path from 'path';
export default defineConfig({
plugins: [svelte()],
resolve: {
alias: {
// Helps the router find your pages folder
'$routes': path.resolve('./src/routes')
}
}
});
3. Router Placement
Save the router code as src/lib/Router.svelte.
🚀 How to Use
1. Create your Pages
The router looks at src/routes/. Simply create files to define your website structure:
| File Path | Resulting URL | Type |
|---|---|---|
src/routes/index.svelte |
/ |
Home |
src/routes/about.svelte |
/about |
Static |
src/routes/post/[id].svelte |
/post/:id |
Dynamic |
2. Initialize in App.svelte
Import and place the <Router /> in your root component. This acts as the placeholder where your pages will be swapped.
<script>
import Router from './lib/Router.svelte';
</script>
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
</nav>
<main>
<Router />
</main>
3. Handling Dynamic Parameters
Inside a file like [id].svelte, the router automatically passes the URL parameters as props.
<script>
// Receive the [id] from the filename as a prop
let { id } = $props();
</script>
<h1>Displaying Post: {id}</h1>
🛠️ Advanced Options
The Router supports Snippets for loading states and 404 errors:
<Router>
{#snippet loading()}
<div class="spinner">Fetching page...</div>
{/snippet}
{#snippet fallback()}
<div class="error">
<h1>404</h1>
<p>Page not found.</p>
</div>
{/snippet}
</Router>
⚠️ Important: Production Deployment
Since this is a Client-Side Router (SPA), you must configure your hosting provider (Netlify, Vercel, or Nginx) to redirect all traffic to index.html.
If you don't do this, refreshing the page on /about will result in a 404 error because the server looks for a physical file that doesn't exist.
- Netlify (
_redirects):/* /index.html 200 - Vercel (
vercel.json): Use therewritesconfiguration.