Files
sweet/docs/latest/examples/common-patterns.md
T
Bartek IwańczukandClaude Opus 4.6 103427f9da docs: comprehensive documentation audit, fixes, and website improvements (#3712)
## Summary

Full documentation audit and fixes for Fresh 2.x docs. Addresses every
issue identified in the [audit
report](https://gist.github.com/bartlomieju/91ddb08c23552f642d2073c0e9a36102).

### Critical fixes
- Remove 4 TODO placeholders (app.md, plugins/index.md)
- Fix 4 broken code examples (layouts syntax error, routing missing ctx,
csrf wrong import, getting-started unused prop)
- Fix 3 copy-pasted frontmatter descriptions (context, env-vars, app)
- Fix CSRF page describing CORS instead of CSRF

### New pages (8)
- **Architecture** — request lifecycle diagram, server-first rendering,
islands architecture
- **Data Fetching** — handlers, page(), type-safe data passing, async
components, PageProps reference
- **Signals** — useSignal, computed, props, shared state, serialization
- **Serialization** — supported types, what can't be serialized,
circular refs, pitfalls
- **API Routes** — handler-only routes, method-specific, catch-all,
programmatic
- **Common Patterns** — protected routes, redirects, cookies,
WebSockets, streaming, content negotiation, subdomain routing, proxying,
lazy-loading islands
- **API Reference** — all exports from fresh, fresh/runtime, fresh/dev
- **OpenTelemetry** — what's instrumented, enabling tracing, Deno Deploy

### Expanded pages (6)
- **Routing** — matching priority, HTTP methods, HEAD fallback,
file-based handlers
- **Vite plugin** — HMR, plugin composition, internals, debugging
- **Deno Deploy** — build config, env vars, custom domains,
troubleshooting
- **deno compile** — cross-compilation, limitations
- **Error handling** — expanded HttpError with message param, import
paths
- **Plugins index** — plugin authoring guidance, built-in plugin list

### Structural improvements
- Update all 3 index pages (concepts, advanced, examples) with links to
every sub-page
- Cross-link the two Layouts pages (file-based vs programmatic)
- Resolve contradictory build commands (remove legacy dev.ts references)
- Add "next steps" to Getting Started
- Explain `(_islands)` and `(_components)` directories in file routing
- Document `basePath`, `assetSrcSet()`, `IS_BROWSER`, route `css` option
- Add PR guidelines to Contributing page
- Add Deno version requirements to Introduction

### Docs fixes from issue triage
- **Docker deployment** — add missing `deno install --allow-scripts`
step, remove stale `deno cache`, fix CMD (#3500)
- **Deployment index** — add install step before build (#3500)
- **Static files** — add tip about root-relative URLs (#3482), add image
optimization section with vite-imagetools, CDN services, best practices
(#671)
- **main.ts vs main.tsx** — fix examples showing JSX in main.ts, add tip
about serverEntry config (#3476)
- **Head component** — clarify dedup precedence: last-rendered wins
(#2749)
- **Islands** — add custom elements / web components section (#2741)
- **Sharing state** — rewrite cart example to avoid shared module-level
signals (#2437, #1877)
- **Common patterns** — add subdomain routing (#603), proxying requests
(#361), lazy-loading islands (#565)

### Website fixes
- **Canary redirects** — catch-all `/docs/canary/...` → `/docs/...`
redirect (#3375)
- **Recipe partials** — redirect direct access to recipe routes to
homepage (#2559)
- **Homepage** — add progressive complexity code examples to Simple
section (#2755)

### Image reference fixes
- Rename `getting-started-3-cotuntdown.png` →
`getting-started-3-countdown.png`
- Fix 1.x partials image path

### Grammar/typos
- 11 corrections across 12 files

### CI
- Add `docs/check_images_test.ts` — verifies all markdown image
references resolve to existing files in `www/static/`

Closes #3514
Closes #3476
Closes #3591
Closes #2876
Closes #2075
Closes #1612
Closes #1535
Closes #527
Closes #3059
Closes #3695
Closes #3548
Closes #3500
Closes #3482
Closes #3375
Closes #2749
Closes #2741
Closes #2559
Closes #2437
Closes #671
Closes #361

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 18:22:33 +00:00

296 lines
6.9 KiB
Markdown

---
description: |
Common patterns and recipes for Fresh applications: authentication, redirects, content negotiation, cookies, and more.
---
This page collects common patterns you'll encounter when building Fresh apps.
## Protected routes
Use [middleware](/docs/concepts/middleware) to check authentication and redirect
unauthenticated users:
```ts routes/dashboard/_middleware.ts
import { define } from "@/utils.ts";
export default define.middleware(async (ctx) => {
const session = await getSession(ctx.req);
if (!session) {
return ctx.redirect("/login");
}
ctx.state.user = session.user;
return ctx.next();
});
```
All routes under `routes/dashboard/` are now protected. The user data is
available in any downstream handler or component via `ctx.state.user`.
## Redirect old URLs
Handle URL migrations with middleware:
```ts routes/_middleware.ts
import { define } from "@/utils.ts";
const REDIRECTS: Record<string, string> = {
"/old-page": "/new-page",
"/blog/old-slug": "/blog/new-slug",
};
export default define.middleware((ctx) => {
const redirect = REDIRECTS[ctx.url.pathname];
if (redirect) {
return ctx.redirect(redirect, 301);
}
return ctx.next();
});
```
> [info]: `ctx.redirect()` includes protection against open redirect attacks.
> Protocol-relative URLs like `//evil.com` are rejected.
## Content negotiation
Return different formats based on the `Accept` header:
```ts routes/api/users/[id].ts
import { HttpError } from "fresh";
import { define } from "@/utils.ts";
export const handler = define.handlers({
async GET(ctx) {
const user = await db.users.find(ctx.params.id);
if (!user) {
throw new HttpError(404);
}
const accept = ctx.req.headers.get("Accept") ?? "";
if (accept.includes("text/html")) {
return ctx.render(<UserProfile user={user} />);
}
return Response.json(user);
},
});
```
## Setting cookies
Use the `@std/http` cookie utilities:
```ts routes/_middleware.ts
import { getCookies, setCookie } from "@std/http";
import { define } from "@/utils.ts";
export default define.middleware(async (ctx) => {
const cookies = getCookies(ctx.req.headers);
ctx.state.theme = cookies["theme"] ?? "light";
const response = await ctx.next();
// Set a cookie on the response
setCookie(response.headers, {
name: "theme",
value: ctx.state.theme,
path: "/",
httpOnly: true,
sameSite: "Lax",
maxAge: 60 * 60 * 24 * 365, // 1 year
});
return response;
});
```
See [Session management](/docs/examples/session-management) for a complete
session example.
## Reading query parameters
Access URL search params from the context:
```ts routes/search.tsx
import { page } from "fresh";
import { define } from "@/utils.ts";
export const handler = define.handlers({
GET(ctx) {
const query = ctx.url.searchParams.get("q") ?? "";
const pageNum = Number(ctx.url.searchParams.get("page") ?? "1");
const results = search(query, pageNum);
return page({ query, results });
},
});
```
## Adding response headers
Set custom headers in middleware:
```ts routes/_middleware.ts
import { define } from "@/utils.ts";
export default define.middleware(async (ctx) => {
const response = await ctx.next();
response.headers.set("X-Frame-Options", "DENY");
response.headers.set("X-Content-Type-Options", "nosniff");
return response;
});
```
Or set headers on a specific route using `page()`:
```ts
import { page } from "fresh";
return page(data, {
headers: { "Cache-Control": "public, max-age=3600" },
});
```
## Streaming responses
Return a streaming response from a handler:
```ts routes/api/stream.ts
import { define } from "@/utils.ts";
export const handler = define.handlers({
GET() {
const body = new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode("Hello "));
setTimeout(() => {
controller.enqueue(new TextEncoder().encode("World!"));
controller.close();
}, 1000);
},
});
return new Response(body, {
headers: { "Content-Type": "text/plain" },
});
},
});
```
## WebSockets
Fresh runs on Deno, so you can upgrade HTTP connections to WebSockets directly:
```ts routes/api/ws.ts
import { define } from "@/utils.ts";
export const handler = define.handlers({
GET(ctx) {
const { socket, response } = Deno.upgradeWebSocket(ctx.req);
socket.onopen = () => {
console.log("Client connected");
};
socket.onmessage = (event) => {
socket.send(`Echo: ${event.data}`);
};
socket.onclose = () => {
console.log("Client disconnected");
};
return response;
},
});
```
## Subdomain routing
Use middleware with `URLPattern` to route based on subdomains:
```ts routes/_middleware.ts
import { define } from "@/utils.ts";
const SUBDOMAIN_PATTERN = new URLPattern({ hostname: ":sub.example.com" });
export default define.middleware(async (ctx) => {
const match = SUBDOMAIN_PATTERN.exec(ctx.req.url);
if (match) {
const sub = match.hostname.groups["sub"];
ctx.state.subdomain = sub;
// Route to different handlers based on subdomain
if (sub === "api") {
return ctx.next(); // Let API routes handle it
}
if (sub !== "www") {
// Tenant-specific logic
ctx.state.tenant = await getTenant(sub);
}
}
return ctx.next();
});
```
## Proxying requests
Forward requests to an upstream server from a route handler:
```ts routes/api/[...path].ts
import { define } from "@/utils.ts";
const UPSTREAM = "https://api.example.com";
export const handler = define.handlers({
async GET(ctx) {
const url = new URL(ctx.params.path, UPSTREAM);
url.search = ctx.url.search;
const response = await fetch(url, {
headers: ctx.req.headers,
});
return new Response(response.body, {
status: response.status,
headers: response.headers,
});
},
});
```
This is useful for proxying to backend services or working around CORS
restrictions during development.
## Lazy-loading island content
Use Preact's `lazy()` and `<Suspense>` to code-split heavy components inside an
island, so their JavaScript is only loaded when needed:
```tsx islands/HeavyFeature.tsx
import { lazy, Suspense } from "preact/compat";
const Chart = lazy(() => import("../components/Chart.tsx"));
export function HeavyFeature() {
return (
<Suspense fallback={<p>Loading chart...</p>}>
<Chart />
</Suspense>
);
}
```
The `Chart` component's code is split into a separate chunk and only fetched
when `HeavyFeature` renders in the browser.
## Timing middleware
Measure how long request processing takes:
```ts routes/_middleware.ts
import { define } from "@/utils.ts";
export default define.middleware(async (ctx) => {
const start = performance.now();
const response = await ctx.next();
const duration = performance.now() - start;
response.headers.set("Server-Timing", `total;dur=${duration.toFixed(1)}`);
return response;
});
```