How to Create Routes in Fresh Framework for Deno
In Fresh for Deno, you create a route by adding a file inside the
routes directory that matches the URL path. Each file exports a default function that returns JSX to render the page for that route.Syntax
In Fresh, routes are created by adding files or folders inside the routes directory. The file name or folder structure corresponds to the URL path. Each route file must export a default function that returns JSX to render the page.
For example, a file named routes/about.tsx creates a route at /about. The default export is the page component.
tsx
export default function Page() { return <div>Hello from the route!</div>; }
Example
This example shows how to create a simple route at /hello that displays a greeting message.
tsx
import { Handlers } from "$fresh/server.ts"; export const handler: Handlers = { GET() { return new Response("Hello from GET handler!"); }, }; export default function Hello() { return <div>Hello, Fresh route!</div>; }
Output
When you visit http://localhost:8000/hello, the page shows: Hello, Fresh route!
Common Pitfalls
- Not placing the route file inside the
routesdirectory will not create the route. - For dynamic routes, use square brackets in file names like
[id].tsxto capture URL parameters. - Forgetting to export a default function will cause the route to fail.
- Mixing server handlers and page components incorrectly can cause unexpected behavior.
tsx
/* Wrong: route file outside routes folder */ // File: hello.tsx (wrong location) export default function Page() { return <div>Won't work</div>; } /* Right: inside routes folder */ // File: routes/hello.tsx export default function Page() { return <div>Works!</div>; }
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Static Route | File inside routes folder matches URL path | routes/about.tsx โ /about |
| Dynamic Route | Use square brackets to capture params | routes/[id].tsx โ /123 |
| Page Component | Default export function returns JSX | export default function Page() { return Hi ; } |
| Server Handler | Optional export to handle HTTP methods | export const handler = { GET() { return new Response('ok'); } } |
Key Takeaways
Create routes by adding files inside the routes directory matching the URL path.
Each route file must export a default function returning JSX to render the page.
Use square brackets in file names for dynamic route parameters.
Export optional handlers to manage HTTP methods like GET or POST.
Keep route files inside the routes folder to ensure they work correctly.