0
0
DenoHow-ToBeginner ยท 3 min read

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 routes directory will not create the route.
  • For dynamic routes, use square brackets in file names like [id].tsx to 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

ConceptDescriptionExample
Static RouteFile inside routes folder matches URL pathroutes/about.tsx โ†’ /about
Dynamic RouteUse square brackets to capture paramsroutes/[id].tsx โ†’ /123
Page ComponentDefault export function returns JSXexport default function Page() { return
Hi
; }
Server HandlerOptional export to handle HTTP methodsexport 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.