Islands architecture on Deno
# Fresh Framework with Deno
You are an expert in Fresh, the next-generation web framework for Deno with islands architecture and zero runtime overhead by default.
## Key Principles
- Use Deno runtime for TypeScript-first development
- Leverage islands for selective client-side interactivity
- Write routes and handlers with file-based routing
- Use Preact for component rendering
- Deploy seamlessly to Deno Deploy
## Project Structure
```
my-fresh-app/
├── deno.json # Deno configuration
├── fresh.gen.ts # Generated manifest
├── main.ts # Entry point
├── dev.ts # Dev server
├── routes/
│ ├── _app.tsx # App wrapper
│ ├── _layout.tsx # Layout component
│ ├── _middleware.ts # Route middleware
│ ├── index.tsx # / route
│ ├── about.tsx # /about route
│ ├── blog/
│ │ ├── index.tsx # /blog
│ │ └── [slug].tsx # /blog/:slug
│ └── api/
│ └── users.ts # /api/users
├── islands/
│ ├── Counter.tsx # Interactive island
│ └── SearchBar.tsx
├── components/
│ ├── Header.tsx # Static component
│ └── Footer.tsx
├── static/
│ └── styles.css
└── utils/
└── db.ts
```
## Route Handlers
```tsx
// routes/blog/[slug].tsx
import { Handlers, PageProps } from "$fresh/server.ts";
import { Head } from "$fresh/runtime.ts";
import { db } from "../../utils/db.ts";
import Comments from "../../islands/Comments.tsx";
interface Post {
slug: string;
title: string;
content: string;
publishedAt: Date;
}
interface Data {
post: Post;
}
export const handler: Handlers<Data> = {
async GET(req, ctx) {
const { slug } = ctx.params;
const post = await db.posts.findBySlug(slug);
if (!post) {
return ctx.renderNotFound();
}
return ctx.render({ post });
},
async POST(req, ctx) {
const form = await req.formData();
const comment = form.get("comment")?.toString();
if (!comment || comment.length < 3) {
return new Response("Comment too short", { status: 400 });
}
await db.comments.create({
postSlug: ctx.params.slug,
content: comment,
});
// Redirect back to post
return new Response("", {
status: 303,
headers: { Location: `/blog/${ctx.params.slug}` },
});
},
};
export default function BlogPost({ data }: PageProps<Data>) {
const { post } = data;
return (
<>
<Head>
<title>{post.title} | My Blog</title>
<meta name="description" content={post.content.slice(0, 160)} />
</Head>
<article>
<h1>{post.title}</h1>
<time>{post.publishedAt.toLocaleDateString()}</time>
<div dangerouslySetInnerHTML={{ __html: post.content }} />
</article>
{/* Interactive island for comments */}
<Comments postSlug={post.slug} />
</>
);
}
```
## Islands (Interactive Components)
```tsx
// islands/Counter.tsx
import { useSignal } from "@preact/signals";
interface CounterProps {
initialCount?: number;
step?: number;
}
export default function Counter({ initialCount = 0, step = 1 }: CounterProps) {
const count = useSignal(initialCount);
return (
<div class="counter">
<p>Count: {count.value}</p>
<button onClick={() => count.value -= step}>-{step}</button>
<button onClick={() => count.value += step}>+{step}</button>
<button onClick={() => count.value = initialCount}>Reset</button>
</div>
);
}
// islands/SearchBar.tsx
import { useSignal } from "@preact/signals";
import { useEffect } from "preact/hooks";
interface SearchResult {
id: string;
title: string;
url: string;
}
export default function SearchBar() {
const query = useSignal("");
const results = useSignal<SearchResult[]>([]);
const loading = useSignal(false);
useEffect(() => {
if (query.value.length < 2) {
results.value = [];
return;
}
const controller = new AbortController();
loading.value = true;
fetch(`/api/search?q=${encodeURIComponent(query.value)}`, {
signal: controller.signal,
})
.then((res) => res.json())
.then((data) => {
results.value = data;
loading.value = false;
})
.catch((e) => {
if (e.name !== "AbortError") {
loading.value = false;
}
});
return () => controller.abort();
}, [query.value]);
return (
<div class="search">
<input
type="search"
value={query.value}
onInput={(e) => query.value = e.currentTarget.value}
placeholder="Search..."
/>
{loading.value && <span>Loading...</span>}
{results.value.length > 0 && (
<ul class="results">
{results.value.map((result) => (
<li key={result.id}>
<a href={result.url}>{result.title}</a>
</li>
))}
</ul>
)}
</div>
);
}
```
## Middleware
```tsx
// routes/_middleware.ts
import { FreshContext } from "$fresh/server.ts";
interface State {
user: { id: string; name: string } | null;
startTime: number;
}
export async function handler(
req: Request,
ctx: FreshContext<State>,
) {
// Add timing
ctx.state.startTime = performance.now();
// Authentication
const sessionId = getCookie(req.headers, "session");
if (sessionId) {
ctx.state.user = await validateSession(sessionId);
}
// Continue to route handler
const response = await ctx.next();
// Add headers
const duration = performance.now() - ctx.state.startTime;
response.headers.set("X-Response-Time", `${duration.toFixed(2)}ms`);
response.headers.set("X-Frame-Options", "DENY");
return response;
}
// routes/admin/_middleware.ts - Protected routes
export async function handler(
req: Request,
ctx: FreshContext<State>,
) {
if (!ctx.state.user) {
return new Response("", {
status: 303,
headers: { Location: "/login" },
});
}
return ctx.next();
}
```
## API Routes
```tsx
// routes/api/users.ts
import { Handlers } from "$fresh/server.ts";
import { db } from "../../utils/db.ts";
export const handler: Handlers = {
async GET(req) {
const url = new URL(req.url);
const limit = Number(url.searchParams.get("limit")) || 10;
const offset = Number(url.searchParams.get("offset")) || 0;
const users = await db.users.findMany({ limit, offset });
return Response.json(users);
},
async POST(req) {
const { name, email } = await req.json();
if (!name || !email) {
return Response.json(
{ error: "Name and email required" },
{ status: 400 }
);
}
const user = await db.users.create({ name, email });
return Response.json(user, { status: 201 });
},
};
```
## Static Components
```tsx
// components/Header.tsx
interface HeaderProps {
user?: { name: string } | null;
}
export default function Header({ user }: HeaderProps) {
return (
<header>
<nav>
<a href="/">Home</a>
<a href="/blog">Blog</a>
<a href="/about">About</a>
{user ? (
<span>Welcome, {user.name}</span>
) : (
<a href="/login">Login</a>
)}
</nav>
</header>
);
}
```
## Deployment
```bash
# Deploy to Deno Deploy
deno task build
deployctl deploy --project=my-app main.ts
# Or use GitHub integration with deno.json
{
"tasks": {
"start": "deno run -A --watch=static/,routes/ dev.ts",
"build": "deno run -A dev.ts build",
"preview": "deno run -A main.ts"
}
}
```
## Best Practices
- Keep islands minimal - most content should be static
- Use signals for island state management
- Leverage middleware for auth and logging
- Use Deno KV for simple data persistence
- Deploy to Deno Deploy for global edge performance
- Use Fresh plugins for shared functionalityThis Fresh prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their fresh implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For Fresh projects, consider mentioning your framework version, coding style, and any specific libraries you're using.