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>
This commit is contained in:
Bartek Iwańczuk
2026-03-29 18:22:33 +00:00
committed by GitHub
co-authored by Claude Opus 4.6
parent 059183b230
commit 103427f9da
59 changed files with 2386 additions and 295 deletions
+70 -16
View File
@@ -1,26 +1,46 @@
---
description: |
Add a global app wrapper to provide common meta tags or context for application routes.
The App class is the heart of Fresh, used to define routes, middlewares, layouts and more.
---
The `App` class is the heart of Fresh and routes incoming requests to the
correct middlewares. This is where routes, middlewares, layouts and more are
defined.
correct [middlewares](/docs/concepts/middleware). This is where routes,
middlewares, [layouts](/docs/concepts/layouts) and more are defined.
```tsx main.ts
```ts main.ts
const app = new App()
.use(staticFiles())
.get("/", () => new Response("hello"))
.get("/about", (ctx) => ctx.render(<h1>About me</h1>));
.get("/", () => new Response("hello"));
// Start server
app.listen();
```
> [tip]: To use JSX in your `main` file (e.g. with
> `ctx.render(<h1>Hello</h1>)`), rename it to `main.tsx` and set
> `serverEntry: "main.tsx"` in the `fresh()` plugin options in `vite.config.ts`.
## Configuration
The `App` constructor accepts an options object:
```ts
const app = new App({
// Serve the app from a sub-path instead of root.
// All routes will be prefixed with this path.
basePath: "/my-app",
});
```
With `basePath: "/my-app"`, a route registered at `/about` will respond to
`/my-app/about`. This is useful when Fresh runs behind a reverse proxy or is
mounted alongside other apps. The base path is available in handlers via
`ctx.config.basePath`.
All items are applied from top to bottom. This means that when you defined a
middleware _after_ a `.get()` handler, it won't be included.
```tsx main.tsx
```ts main.ts
const app = new App()
.use((ctx) => {
// Will be called for all middlewares
@@ -28,10 +48,10 @@ const app = new App()
})
.get("/", () => new Response("hello"))
.use((ctx) => {
// Will only be called for `/about
// Will only be called for `/about`
return ctx.next();
})
.get("/about", (ctx) => ctx.render(<h1>About me</h1>));
.get("/about", () => new Response("About me"));
```
## `.use()`
@@ -238,8 +258,8 @@ app.all("/api/foo", async () => {
## `.fsRoute()`
Injects all file-based routes, middlewares, layouts and error pages to the app
instance.
Injects all [file-based routes](/docs/concepts/file-routing), middlewares,
layouts and [error pages](/docs/advanced/error-handling) to the app instance.
```ts
app.fsRoutes();
@@ -257,7 +277,18 @@ app.fsRoutes("/foo/bar");
## `.route()`
TODO
Register a route with a component and optional handlers for data loading.
```tsx
app.route("/about", {
component: (ctx) => <h1>About {ctx.data.name}</h1>,
handler: {
GET(ctx) {
return page({ name: "Fresh" });
},
},
});
```
## `.appWrapper()`
@@ -282,9 +313,13 @@ app.onError("*", (ctx) => {
});
```
Setting a route:
Setting a route with a component:
TODO
```tsx
app.onError("*", {
component: (ctx) => <h1>Oops! {String(ctx.error)}</h1>,
});
```
## `.notFound()`
@@ -296,7 +331,13 @@ app.notFound(() => {
});
```
TODO: Route
With a component:
```tsx
app.notFound((ctx) => {
return ctx.render(<h1>Page not found</h1>);
});
```
## `.mountApp()`
@@ -335,7 +376,8 @@ frameworks.
## `.listen()`
Spawns a server and listens for incoming connections.
Spawns a server and listens for incoming connections. This calls `Deno.serve()`
internally.
```ts
const app = new App()
@@ -350,3 +392,15 @@ aspects.
```ts
app.listen({ port: 4000 });
```
> **Important:** `.listen()` is only used when running your app directly with
> `deno run -A main.ts`. The default project setup uses `deno task dev` (Vite
> dev server) and `deno task start` (`deno serve`), which spawn their own
> servers - calling `.listen()` alongside these will create a second server and
> cause `AddrInUse` errors.
>
> To customize the port in the default setup:
>
> - **Dev:** set `server.port` in `vite.config.ts`
> - **Prod:** pass `--port` to `deno serve` in your task, e.g.
> `"start": "deno serve --port 4000 -A _fresh/server.js"`
+179
View File
@@ -0,0 +1,179 @@
---
description: |
How Fresh processes requests: the flow from incoming request through middleware, routing, handlers, layouts, and island hydration.
---
Fresh is a server-first web framework. Pages are rendered on the server and only
the interactive parts ([islands](/docs/concepts/islands)) ship JavaScript to the
browser. This page explains how a request flows through the framework.
## Request lifecycle
<div style="max-width:620px;font-family:system-ui,-apple-system,sans-serif;font-size:14px;color:#1a1a1a;">
<style>
.flow-step{display:flex;align-items:flex-start;gap:16px}
.flow-box{flex-shrink:0;width:200px;padding:10px 14px;border:1.5px solid #333;border-radius:6px;background:#f8f9fa;text-align:center}
.flow-box strong{display:block;font-size:14px}
.flow-box small{font-size:11px;color:#777}
.flow-box.accent{background:#eef6ff}
.flow-box.green{background:#f0faf0}
.flow-desc{padding-top:10px;font-size:12.5px;color:#555;line-height:1.5}
.flow-arrow{text-align:center;width:200px;color:#666;font-size:18px;line-height:1;padding:4px 0}
.flow-arrow-label{text-align:center;width:200px;padding:2px 0}
.flow-arrow-label em{font-size:11px;color:#777}
.flow-divider{margin:12px 0 8px;padding-top:8px;border-top:1px dashed #e0e0e0;font-size:11px;color:#999;font-weight:600;letter-spacing:0.5px;text-transform:uppercase}
</style>
<!-- Browser Request -->
<div class="flow-step">
<div class="flow-box accent"><strong>Browser Request</strong></div>
</div>
<div class="flow-arrow">&#x2193;</div>
<!-- Static Files -->
<div class="flow-step">
<div class="flow-box"><strong>Static Files</strong></div>
<div class="flow-desc">Serve file directly if path matches a static asset</div>
</div>
<div class="flow-arrow-label"><em>no match</em></div>
<div class="flow-arrow">&#x2193;</div>
<!-- Global Middleware -->
<div class="flow-step">
<div class="flow-box"><strong>Global Middleware</strong><small>runs in registration order</small></div>
<div class="flow-desc">Can modify request/response, set state, or short&#8209;circuit with a Response</div>
</div>
<div class="flow-arrow">&#x2193;</div>
<!-- Router -->
<div class="flow-step">
<div class="flow-box"><strong>Router</strong></div>
<div class="flow-desc">Match URL pattern + HTTP method. Static routes checked first, then dynamic.</div>
</div>
<div class="flow-arrow">&#x2193;</div>
<!-- Scoped Middleware -->
<div class="flow-step">
<div class="flow-box"><strong>Scoped Middleware</strong></div>
<div class="flow-desc">Middleware that only runs for matching path prefixes (e.g. /admin/*). Used for auth, logging, or other route&#8209;specific logic.</div>
</div>
<div class="flow-arrow">&#x2193;</div>
<!-- Handler -->
<div class="flow-step">
<div class="flow-box"><strong>Handler</strong></div>
<div class="flow-desc">API route? Return Response directly (JSON, redirect, etc.)</div>
</div>
<div class="flow-arrow-label"><em>has component</em></div>
<div class="flow-arrow">&#x2193;</div>
<!-- Rendering section -->
<div class="flow-divider">Rendering</div>
<!-- App Wrapper -->
<div class="flow-step">
<div class="flow-box"><strong>App Wrapper</strong></div>
<div class="flow-desc">Outer &lt;html&gt;/&lt;head&gt;/&lt;body&gt; structure</div>
</div>
<div class="flow-arrow">&#x2193;</div>
<!-- Layouts -->
<div class="flow-step">
<div class="flow-box"><strong>Layouts</strong></div>
<div class="flow-desc">Nested layout components (inherited from parent directories)</div>
</div>
<div class="flow-arrow">&#x2193;</div>
<!-- Page Component -->
<div class="flow-step">
<div class="flow-box"><strong>Page Component</strong></div>
<div class="flow-desc">Route component receives props.data from handler</div>
</div>
<div class="flow-arrow">&#x2193;</div>
<!-- HTML Response -->
<div class="flow-step">
<div class="flow-box accent"><strong>HTML + JS Response</strong><small>sent to browser</small></div>
<div class="flow-desc">Server&#8209;rendered HTML with island props <a href="/docs/advanced/serialization">serialized</a> inline</div>
</div>
<!-- Client section -->
<div class="flow-divider">Client (Browser)</div>
<div class="flow-arrow">&#x2193;</div>
<!-- Hydration -->
<div class="flow-step">
<div class="flow-box green"><strong>Island Hydration</strong><small>only islands receive JS</small></div>
<div class="flow-desc">Rest of the page stays static HTML. No JavaScript for non&#8209;island components.</div>
</div>
</div>
## Key concepts
### Server-first rendering
Every page is fully rendered to HTML on the server before being sent to the
browser. This means:
- Pages are visible immediately - no blank loading screens
- Search engines see complete content
- Pages work without JavaScript enabled
### Islands architecture
Fresh uses the
[islands architecture](https://jasonformat.com/islands-architecture/). Only
components in the `islands/` directory are [hydrated](/docs/concepts/islands) in
the browser. Everything else is static HTML that never runs JavaScript on the
client.
This means a page with a single interactive button only ships the JavaScript for
that button - not for the entire page.
### Middleware chain
Middlewares execute in registration order, wrapping the handler. Each middleware
calls `ctx.next()` to pass control to the next middleware (or handler). This
creates an onion-like pattern where middlewares can act on both the request
(before `ctx.next()`) and the response (after `ctx.next()`):
```ts
app.use(async (ctx) => {
// Before: runs on the way in
console.log("Request:", ctx.url.pathname);
const response = await ctx.next();
// After: runs on the way out
console.log("Status:", response.status);
return response;
});
```
Scoped middleware runs only for requests that match a specific path prefix. Pass
a path pattern as the first argument to `app.use()`:
```ts
app.use("/admin/*", async (ctx) => {
// Only runs for /admin/* routes
const user = ctx.state.user;
if (!user?.isAdmin) return new Response("Forbidden", { status: 403 });
return ctx.next();
});
```
Global middleware runs on every request; scoped middleware lets you apply logic
like authentication or logging to a subset of routes.
### Layout inheritance
[Layouts](/docs/concepts/layouts) wrap page components and are inherited from
parent directories. A page at `routes/blog/post.tsx` inherits layouts from:
1. `routes/_layout.tsx` (root layout)
2. `routes/blog/_layout.tsx` (section layout)
Layouts nest from the outside in: the root layout is outermost, each deeper
layout wraps closer to the page, and the innermost layout directly wraps the
page component. The [app wrapper](/docs/concepts/app) (`_app.tsx`) wraps
everything.
### Build and deploy
Fresh uses [Vite](https://vite.dev/) to bundle island JavaScript for production.
The `deno task build` command:
1. Discovers all islands and their dependencies
2. Bundles client-side JavaScript with code splitting
3. Generates a server entry point (`_fresh/server.js`)
4. Hashes assets for cache busting
In production, `_fresh/server.js` serves the pre-built assets. In development,
Vite provides Hot Module Replacement for instant feedback.
+7 -5
View File
@@ -1,9 +1,10 @@
---
description: Plugins can add new functionality to Fresh without requiring significant complexity.
description: The Context object is shared across all middlewares and provides access to the request, URL, params, state, and response helpers.
---
The `Context` instance is shared across all middlewares in Fresh. Use it to
respond with HTML, trigger redirects, access the incoming
The `Context` instance is shared across all
[middlewares](/docs/concepts/middleware) in Fresh. Use it to respond with HTML,
trigger redirects, access the incoming
[`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) or read
other metadata.
@@ -56,7 +57,7 @@ matched.
```ts
app.get("/foo/:id", (ctx) => {
console.log(ctx.route); // Logs: "/foo/:id
console.log(ctx.route); // Logs: "/foo/:id"
// ...
});
```
@@ -98,7 +99,8 @@ app.use((ctx) => {
## `.error`
If an error was thrown, this property will hold the caught value (default:
`null`). This is typically used mainly on an error page.
`null`). This is typically used mainly on an
[error page](/docs/advanced/error-handling).
```ts
app.onError((ctx) => {
+133
View File
@@ -0,0 +1,133 @@
---
description: |
Load data on the server in handlers and pass it to page components with full type safety.
---
Data fetching in Fresh happens on the server. Handlers load data and pass it to
page components via the `page()` helper. This keeps API keys, database
connections, and sensitive logic out of the browser.
## Handlers and page components
A handler fetches data and returns it with `page()`. The page component receives
it in `props.data`:
```tsx routes/projects/[id].tsx
import { HttpError, page } from "fresh";
import { define } from "@/utils.ts";
interface Data {
project: { name: string; stars: number };
}
export const handler = define.handlers({
async GET(ctx) {
const project = await db.projects.findOne(ctx.params.id);
if (!project) {
throw new HttpError(404);
}
return page({ project });
},
});
export default define.page<typeof handler>(({ data }) => {
return (
<div>
<h1>{data.project.name}</h1>
<p>{data.project.stars} stars</p>
</div>
);
});
```
The `define.page<typeof handler>` generic links the handler's return type to the
component's props, giving you full autocompletion on `data`.
## Setting response headers and status
Pass options to `page()` to customize the HTTP response:
```ts
return page(data, {
status: 201,
headers: { "Cache-Control": "public, max-age=3600" },
});
```
## Async page components
For simpler cases, you can fetch data directly in an async component without a
separate handler:
```tsx routes/projects/[id].tsx
import { HttpError } from "fresh";
import { define } from "@/utils.ts";
export default define.page(async (ctx) => {
const project = await db.projects.findOne(ctx.params.id);
if (!project) {
throw new HttpError(404);
}
return (
<div>
<h1>{project.name}</h1>
<p>{project.stars} stars</p>
</div>
);
});
```
This is convenient for pages where you don't need the type-safe data bridge
between handler and component.
## Passing state from middleware
[Middleware](/docs/concepts/middleware) can set values on `ctx.state` that are
available to all downstream handlers and components:
```ts routes/_middleware.ts
import { define } from "@/utils.ts";
export default define.middleware(async (ctx) => {
const session = await getSession(ctx.req);
ctx.state.user = session?.user ?? null;
return ctx.next();
});
```
```tsx routes/dashboard.tsx
import { page } from "fresh";
import { define } from "@/utils.ts";
export const handler = define.handlers({
GET(ctx) {
if (!ctx.state.user) {
return ctx.redirect("/login");
}
return page();
},
});
export default define.page((ctx) => {
return <h1>Welcome, {ctx.state.user.name}</h1>;
});
```
## What's available in page props
Page components receive these properties:
| Property | Type | Description |
| ----------- | ------------------------ | ----------------------------------------- |
| `data` | `Data` | Data returned by the handler via `page()` |
| `url` | `URL` | The request URL |
| `params` | `Record<string, string>` | Route parameters (e.g. `:id`) |
| `req` | `Request` | The original HTTP request |
| `state` | `State` | Shared state set by middleware |
| `config` | `ResolvedFreshConfig` | The resolved Fresh configuration |
| `route` | `string \| null` | The matched route pattern |
| `info` | `Deno.ServeHandlerInfo` | Server connection info |
| `error` | `unknown \| null` | Caught error (on error pages) |
| `isPartial` | `boolean` | Whether this is a partial request |
| `Component` | `FunctionComponent` | Child component (in layouts) |
+18 -2
View File
@@ -19,8 +19,8 @@ const app = new App({ basePath: "/foo" })
```
> [info]: The `staticFiles()` middleware is required when using file based
> routing. Otherwise the necessary JavaScript files for islands won't be served
> to the browser.
> routing. Otherwise the necessary JavaScript files for
> [islands](/docs/concepts/islands) won't be served to the browser.
Example project structure:
@@ -46,6 +46,15 @@ Example project structure:
└── index.tsx
```
**Special directories inside `routes/`:**
- **`(_islands)`** - Files in this directory are treated as
[islands](/docs/concepts/islands), just like files in the top-level `islands/`
folder. This lets you co-locate islands next to the routes that use them.
- **`(_components)`** - A conventional directory for non-island components that
are only used by nearby routes. Fresh does not treat these files specially -
the parentheses just prevent them from becoming routes.
File names are mapped to route patterns as follows:
- File extensions are ignored.
@@ -84,6 +93,13 @@ export const config: RouteConfig = {
// ...
```
You can also load additional CSS files for a specific route by exporting a `css`
array. This is a top-level export, separate from `config`:
```ts routes/dashboard.tsx
export const css = ["./assets/dashboard.css"];
```
## Route Groups
When working with [layouts](/docs/advanced/layouts) or
+10 -1
View File
@@ -13,6 +13,8 @@ Fresh will boot them up in the browser and execute the relevant JavaScript.
Here is an overview of the basic concepts in Fresh:
- [**Architecture**](/docs/concepts/architecture) - How requests flow through
Fresh, from middleware to islands
- [**App**](/docs/concepts/app) - Holds all the information about your app, like
routes, etc
- [**Middleware**](/docs/concepts/middleware) - Respond to a request and return
@@ -21,10 +23,17 @@ Here is an overview of the basic concepts in Fresh:
called a "handler".
- [**Context**](/docs/concepts/context) - Passed through every middleware. Use
this to share state, trigger redirects or render HTML.
- [**Routes**](/docs/concepts/routing) - Responds to a particular URL and runs
- [**Routing**](/docs/concepts/routing) - Responds to a particular URL and runs
as chain of middlewares if it matches
- [**Data Fetching**](/docs/concepts/data-fetching) - Load data on the server
and pass it to page components
- [**Islands**](/docs/concepts/islands) - Render interactive Preact components
on the client
- [**Signals**](/docs/concepts/signals) - Reactive state management for islands
- [**Static Files**](/docs/concepts/static-files) - Serve images, CSS, and other
assets
- [**File Routing**](/docs/concepts/file-routing) - Convention-based routing
from the filesystem
Advanced concepts:
+74 -7
View File
@@ -39,8 +39,9 @@ const app = new App()
## Passing props to islands
Passing props to islands is supported, but only if the props are serializable.
Fresh can serialize the following types of values:
Passing props to islands is supported, but only if the props are
[serializable](/docs/advanced/serialization). Fresh can serialize the following
types of values:
- Primitive types `string`, `number`, `boolean`, `bigint`, `undefined`, and
`null`
@@ -51,9 +52,11 @@ Fresh can serialize the following types of values:
- `RegExp`
- `JSX` Elements
- Collections `Map` and `Set`
- `Temporal` objects (`Instant`, `ZonedDateTime`, `PlainDate`, `PlainTime`,
`PlainDateTime`, `PlainYearMonth`, `PlainMonthDay`, `Duration`)
- Plain objects with string keys and serializable values
- Arrays containing serializable values
- Preact Signals (if the inner value is serializable)
- Preact [Signals](/docs/concepts/signals) (if the inner value is serializable)
Circular references are supported. If an object or signal is referenced multiple
times, it is only serialized once and the references are restored upon
@@ -102,7 +105,7 @@ that is needed for the islands to the browser.
export default (props: { foo: string }) => <>{props.foo}</>;
```
```tsx route/index.tsx
```tsx routes/index.tsx
import MyIsland from "../islands/my-island.tsx";
import OtherIsland from "../islands/other-island.tsx";
@@ -117,9 +120,10 @@ import OtherIsland from "../islands/other-island.tsx";
## Rendering islands on client only
When using client-only APIs, like `EventSource` or `navigator.getUserMedia`,
this component will not run on the server as it will produce an error. To fix
this use the `IS_BROWSER` flag as a guard:
When using client-only APIs, like `EventSource` or `navigator.getUserMedia`, the
component would error during server-side rendering. Use the `IS_BROWSER`
constant from `fresh/runtime` to guard browser-only code. It is `false` on the
server and `true` in the browser:
```tsx islands/my-island.tsx
import { IS_BROWSER } from "fresh/runtime";
@@ -133,3 +137,66 @@ export function MyIsland() {
return <div></div>;
}
```
## Using Custom Elements (Web Components)
[Custom elements](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements)
can be used in Fresh, but they must be registered client-side since
`customElements.define()` is a browser API.
### Registering a custom element
Use an island to register and render custom elements:
```tsx islands/MyElement.tsx
import { useEffect } from "preact/hooks";
import { IS_BROWSER } from "fresh/runtime";
export function MyElement() {
useEffect(() => {
if (customElements.get("my-greeting")) return;
customElements.define(
"my-greeting",
class extends HTMLElement {
connectedCallback() {
const name = this.getAttribute("name") ?? "World";
this.innerHTML = `<p>Hello, ${name}!</p>`;
}
},
);
}, []);
if (!IS_BROWSER) {
return <div></div>;
}
return <my-greeting name="Fresh" />;
}
```
### Using third-party web components
Third-party web component libraries work the same way - import and register them
inside an island:
```tsx islands/ThirdPartyElement.tsx
import { useEffect } from "preact/hooks";
import { IS_BROWSER } from "fresh/runtime";
export function ShoelaceButton() {
useEffect(() => {
// Import the library's registration script
import("@shoelace-style/shoelace/dist/components/button/button.js");
}, []);
if (!IS_BROWSER) {
return <button>Click me</button>;
}
return <sl-button variant="primary">Click me</sl-button>;
}
```
> [tip]: Return a plain HTML fallback from the server-side branch
> (`!IS_BROWSER`) so the page is usable before JavaScript loads.
+112 -56
View File
@@ -1,59 +1,96 @@
---
description: |
Add a layout to provide common meta tags, context for application sub routes, and common layout.
Wrap pages in shared UI using _layout.tsx files. Layouts nest automatically, support async data loading, and can be skipped per route.
---
A layout is defined in a `_layout.tsx` file in any sub directory (at any level)
under the `routes/` folder. It must contain a default export that is a regular
Preact component. Only one such layout is allowed per sub directory.
This page covers **file-based layouts** using `_layout.tsx` files. If you're
defining routes programmatically with `new App()`, see
[Layouts (programmatic)](/docs/advanced/layouts) instead.
Layouts let you wrap groups of pages in shared UI - navigation bars, sidebars,
footers, or any common structure. They are defined in `_layout.tsx` files and
nest automatically based on the directory tree.
## How layouts work
Place a `_layout.tsx` file in any directory under `routes/`. It wraps every page
in that directory and its subdirectories. You can have one layout per directory.
```txt-files Project structure
<project root>
└── routes
   ├── sub
   │ ├── page.tsx
   │   └── index.tsx
├── other
│ ├── _layout.tsx # will be applied on top of `routes/_layout.tsx`
│ └── page.tsx
├── _layout.tsx # will be applied to all routes
└── _app.tsx
├── _app.tsx # App wrapper (outermost HTML shell)
├── _layout.tsx # Root layout - wraps all pages
├── index.tsx
├── about.tsx
├── blog
│ ├── _layout.tsx # Blog layout - wraps blog pages
│ ├── index.tsx
│ └── [slug].tsx
└── admin
├── _layout.tsx # Admin layout - wraps admin pages
└── dashboard.tsx
```
The component to be wrapped is received via props, in addition to a few other
things. This allows for the introduction of a global container functioning as a
template which can be conditioned based on state and params. Note that any state
set by middleware is available via `props.state`.
When a user visits `/blog/my-post`, Fresh renders these components from the
outside in:
```tsx routes/sub/_layout.tsx
import { define } from "../../utils.ts";
1. `_app.tsx` - the outer `<html>`/`<head>`/`<body>` shell
2. `routes/_layout.tsx` - root layout (e.g. site header and footer)
3. `routes/blog/_layout.tsx` - blog layout (e.g. blog sidebar)
4. `routes/blog/[slug].tsx` - the page itself
export default define.layout({ Component, state }) => {
// do something with state here
## Basic layout
A layout receives `Component` (the child to wrap) and other props like `state`
and `url`. Any state set by [middleware](/docs/concepts/middleware) is available
via `props.state`.
```tsx routes/_layout.tsx
import { define } from "../utils.ts";
export default define.layout(({ Component, state, url }) => {
return (
<div class="layout">
<Component />
<nav>
<a href="/" class={url.pathname === "/" ? "active" : ""}>Home</a>
<a href="/about">About</a>
{state.user && <span>Hi, {state.user.name}</span>}
</nav>
<main>
<Component />
</main>
<footer>&copy; 2026</footer>
</div>
);
})
});
```
## Async layouts
In case you need to fetch data asynchronously before rendering the layout, you
can use an async layout to do so.
Layouts can be async to fetch data before rendering:
```tsx routes/sub/_layout.tsx
```tsx routes/blog/_layout.tsx
import { define } from "../../utils.ts";
export default define.layout(async (ctx) => {
// do something with state here
const data = await loadData();
const categories = await db.categories.list();
return (
<div class="layout">
<p>{data.greeting}</p>
<ctx.Component />
<div class="blog-layout">
<aside>
<h2>Categories</h2>
<ul>
{categories.map((c) => (
<li>
<a href={`/blog?cat=${c.slug}`}>{c.name}</a>
</li>
))}
</ul>
</aside>
<article>
<ctx.Component />
</article>
</div>
);
});
@@ -61,45 +98,64 @@ export default define.layout(async (ctx) => {
## Opting out of layout inheritance
Sometimes you want to opt out of the layout inheritance mechanism for a
particular route. This can be done via route configuration. Picture a directory
structure like this:
Sometimes a route needs completely different chrome - a login page, a
full-screen dashboard, or a print view. Use `skipInheritedLayouts` in the route
config to skip all layouts inherited from parent directories:
```txt-files Project structure
└── <root>/routes
   ├── sub
   │ ├── _layout_.tsx
   │ ├── special.tsx # should not inherit layouts
   │   └── index.tsx
└── _layout.tsx
```
To make `routes/sub/special.tsx` opt out of rendering layouts we can set
`skipInheritedLayouts: true`.
```tsx routes/sub/special.tsx
```tsx routes/login.tsx
import { type RouteConfig } from "fresh";
import { define } from "../../utils.ts";
import { define } from "../utils.ts";
export const config: RouteConfig = {
skipInheritedLayouts: true, // Skip already inherited layouts
skipInheritedLayouts: true,
};
export default define.layout(() => {
return <p>Hello world</p>;
export default define.page(() => {
return (
<div class="login-page">
<h1>Sign in</h1>
<form method="POST">
<input type="email" name="email" placeholder="Email" />
<input type="password" name="password" placeholder="Password" />
<button type="submit">Sign in</button>
</form>
</div>
);
});
```
You can skip already inherited layouts inside a layout file:
You can also skip inherited layouts from within a layout file itself. This is
useful when a section of your site needs a completely different shell:
```tsx routes/special/_layout.tsx
```tsx routes/admin/_layout.tsx
import { type LayoutConfig } from "fresh";
import { define } from "../../utils.ts";
export const config: LayoutConfig = {
skipInheritedLayouts: true, // Skip already inherited layouts
skipInheritedLayouts: true,
};
export default function MyPage() {
return <p>Hello world</p>;
}
export default define.layout(({ Component, state }) => {
return (
<div class="admin-shell">
<aside class="admin-sidebar">
<a href="/admin/dashboard">Dashboard</a>
<a href="/admin/users">Users</a>
</aside>
<main>
<Component />
</main>
</div>
);
});
```
## Layout vs app wrapper
The [app wrapper](/docs/concepts/app) (`_app.tsx`) and layouts serve different
purposes:
- **App wrapper** - the outermost `<html>`/`<head>`/`<body>` structure. There is
only one, and it wraps everything.
- **Layouts** - reusable UI shells that nest based on directory structure. There
can be many, and they sit between the app wrapper and the page component.
+6 -4
View File
@@ -52,13 +52,15 @@ const middleware = define.middleware(async (ctx) => {
Fresh ships with the following middlewares built-in:
- [cors()](/docs/plugins/cors) - Set CORS HTTP headers
- [csrf()](/docs/plugins/csrf) - Set CSRF HTTP headers
- [trailingSlash()](/docs/plugins/trailing-slashes) - Enforce trailing slashes
- [csrf()](/docs/plugins/csrf) - CSRF protection
- [csp()](/docs/plugins/csp) - Content Security Policy headers
- [trailingSlashes()](/docs/plugins/trailing-slashes) - Enforce trailing slashes
## Filesystem-based middlewares
With file system based routing you can define a middleware in a `_middleware.ts`
file inside the `routes/` folder or any of it's subfolders.
With [file system based routing](/docs/concepts/file-routing) you can define a
middleware in a `_middleware.ts` file inside the `routes/` folder or any of its
subfolders.
```ts routes/_middleware.ts
import { define } from "../utils.ts";
+70 -2
View File
@@ -1,6 +1,6 @@
---
description: |
File based routing is the simplest way to do routing in Fresh apps. Additionally custom patterns can be configured per route.
How routing works in Fresh, including route patterns, matching priority, method-specific handlers, and URLPattern support.
---
Routing defines which middlewares and routes should respond to a particular
@@ -16,7 +16,7 @@ const app = new App()
const id = ctx.params.id;
return new Response(`Book id: ${id}`);
})
.get("/blog/:post/comments", () => {
.get("/blog/:post/comments", (ctx) => {
// Responds to: GET /blog/my-post/comments, /blog/hello/comments, etc
const post = ctx.params.post;
return new Response(`Blog post comments for post: ${post}`);
@@ -30,3 +30,71 @@ const app = new App()
Fresh supports the full
[`URLPattern`](https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API)
syntax for setting pathnames.
## Route matching priority
Routes are matched in the following order:
1. **Static routes** (exact path match like `/about`) are checked first and
always take precedence.
2. **Dynamic routes** (patterns like `/posts/:id`) are checked in the order they
were registered. The first matching route wins.
This means the registration order matters for dynamic routes:
```ts main.ts
const app = new App()
// This is checked first since it's registered first
.get("/posts/featured", () => new Response("Featured posts"))
// This is checked second - won't match "/posts/featured" because it's
// already handled above
.get("/posts/:id", (ctx) => new Response(`Post: ${ctx.params.id}`));
```
## HTTP method handlers
Fresh provides method-specific route registration via `.get()`, `.post()`,
`.put()`, `.delete()`, `.head()`, `.patch()`, and `.options()`. Each method only
responds to its matching HTTP verb.
Use `.all()` to respond to any HTTP method:
```ts main.ts
app.all("/api/health", () => new Response("ok"));
```
If a route is registered for `GET` but receives a `POST` request, Fresh returns
a `405 Method Not Allowed` response. `HEAD` requests automatically fall back to
the `GET` handler if no dedicated `HEAD` handler is defined.
## File-based route handlers
In file-based routes, export a `handlers` object with method-specific functions:
```ts routes/api/users.ts
import { define } from "@/utils.ts";
export const handlers = define.handlers({
GET(ctx) {
return new Response(JSON.stringify({ users: [] }), {
headers: { "Content-Type": "application/json" },
});
},
POST(ctx) {
return new Response("Created", { status: 201 });
},
});
```
To handle all methods, export a single function instead:
```ts routes/api/health.ts
import { define } from "@/utils.ts";
export const handlers = define.handlers((ctx) => {
return new Response(`Received a ${ctx.req.method} request`);
});
```
See [File routing](/docs/concepts/file-routing) for more on the file-based
routing convention.
+138
View File
@@ -0,0 +1,138 @@
---
description: |
Signals provide reactive state management in Fresh islands using @preact/signals.
---
[Signals](https://preactjs.com/guide/v10/signals/) are Preact's reactive
primitive for managing state in [islands](/docs/concepts/islands). When a
signal's value changes, any component that reads it re-renders automatically -
no need for `setState` or manual subscriptions.
## Creating signals
Use `useSignal` inside a component for local state, or `signal` at module level
for shared state:
```tsx islands/Counter.tsx
import { useSignal } from "@preact/signals";
export default function Counter() {
const count = useSignal(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => count.value++}>Increment</button>
</div>
);
}
```
> [info]: Signals can be rendered directly in JSX (`{count}`) without accessing
> `.value`. Preact detects the signal and subscribes to updates automatically.
## Computed signals
Use `computed` to derive values from other signals. Computed signals update
automatically when their dependencies change:
```tsx islands/TemperatureConverter.tsx
import { useComputed, useSignal } from "@preact/signals";
export default function TemperatureConverter() {
const celsius = useSignal(20);
const fahrenheit = useComputed(() => celsius.value * 9 / 5 + 32);
return (
<div>
<input
type="range"
min={-40}
max={100}
value={celsius}
onInput={(e) => celsius.value = Number(e.currentTarget.value)}
/>
<p>{celsius}°C = {fahrenheit}°F</p>
</div>
);
}
```
## Passing signals as props
Signals can be passed as props to islands. Fresh automatically serializes them
on the server and reconstructs them as live signals on the client:
```tsx routes/index.tsx
import { useSignal } from "@preact/signals";
import Slider from "@/islands/Slider.tsx";
export default function Home() {
const value = useSignal(50);
return (
<div>
<Slider value={value} />
<Slider value={value} />
</div>
);
}
```
Both sliders share the same signal - moving one updates the other. When the same
signal object is passed to multiple islands, Fresh preserves the reference so
they stay synchronized.
> [info]: Using `useSignal` in a route component (not an island) is intentional
> here. The signal is created during server rendering, serialized into the HTML,
> and reconstructed as a live signal on the client. This is how Fresh shares
> reactive state between multiple islands on the same page.
## Shared state across islands
For state that needs to be shared between unrelated islands, create a signal in
a separate module:
```ts utils/cart.ts
import { signal } from "@preact/signals";
export const cart = signal<string[]>([]);
```
```tsx islands/AddToCart.tsx
import { cart } from "@/utils/cart.ts";
export default function AddToCart(props: { product: string }) {
return (
<button onClick={() => cart.value = [...cart.value, props.product]}>
Add {props.product}
</button>
);
}
```
```tsx islands/CartCount.tsx
import { cart } from "@/utils/cart.ts";
export default function CartCount() {
return <span>Items in cart: {cart.value.length}</span>;
}
```
Since both islands import the same module-level signal, they share the same
state automatically. See
[Sharing state between islands](/docs/examples/sharing-state-between-islands)
for more patterns.
## Serialization
When signals are passed as island props, Fresh handles
[serialization](/docs/advanced/serialization) automatically:
- The signal's current value is extracted on the server via `.peek()`
- On the client, the value is wrapped back into a live `signal()` or
`computed()`
- Circular references and duplicate signal references are preserved
The signal's inner value must itself be serializable (see
[Islands - Passing props](/docs/concepts/islands#passing-props-to-islands) for
the full list of supported types).
+78 -3
View File
@@ -18,9 +18,9 @@ const app = new App()
## Imported assets vs static files
When using Fresh with Vite (now the default), **files that you import in your
JavaScript/TypeScript code should not be placed in the `static/` folder**. This
prevents file duplication during the build process.
When using Fresh with [Vite](/docs/advanced/vite) (now the default), **files
that you import in your JavaScript/TypeScript code should not be placed in the
`static/` folder**. This prevents file duplication during the build process.
```tsx
// Don't import from static/
@@ -37,6 +37,11 @@ import "./assets/styles.css";
- Files **referenced by URL path** (favicon.ico, fonts, robots.txt, PDFs, etc.):
place in `static/`
> [tip]: Always use root-relative URLs (starting with `/`) when referencing
> static files in HTML. For example, use `src="/image/photo.png"` instead of
> `src="image/photo.png"`. Relative paths resolve against the browser's current
> URL, which breaks when navigating between routes.
When you import a file in your code, Vite processes it through its build
pipeline, optimizes it, and adds a content hash to the filename for cache
busting. Keeping these files outside `static/` ensures they're only included
@@ -76,3 +81,73 @@ export default function About() {
return <a href={asset("/brochure.pdf")}>View brochure</a>;
}
```
For `<img>` tags with a `srcset` attribute, use `assetSrcSet()`:
```tsx routes/gallery.tsx
import { assetSrcSet } from "fresh/runtime";
export default function Gallery() {
return (
<img
src="/photo.jpg"
srcset={assetSrcSet("/photo-640.jpg 640w, /photo-1280.jpg 1280w")}
/>
);
}
```
## Image optimization
Fresh does not include a built-in image optimization pipeline, but since Fresh 2
uses Vite, you can use Vite plugins or external services to optimize images.
### Build-time optimization with Vite
[vite-imagetools](https://github.com/JonasKruckenberg/imagetools) lets you
import images with query parameters to resize, convert formats, and generate
`srcset` at build time:
```ts
deno add -D npm:vite-imagetools
```
```ts vite.config.ts
import { defineConfig } from "vite";
import { fresh } from "@fresh/plugin-vite";
import { imagetools } from "vite-imagetools";
export default defineConfig({
plugins: [fresh(), imagetools()],
});
```
Then import optimized images directly:
```tsx
import heroAvif from "../static/hero.jpg?format=avif&w=800";
export default function Page() {
return <img src={heroAvif} alt="Hero" width={800} />;
}
```
### CDN image services
For dynamic optimization without a build step, use a CDN image service that
transforms images on-the-fly:
- [Cloudflare Images](https://developers.cloudflare.com/images/)
- [imgix](https://imgix.com/)
- [Cloudinary](https://cloudinary.com/)
These services resize, compress, and convert images to modern formats (WebP,
AVIF) based on URL parameters, with automatic caching at the edge.
### Best practices
- Use modern formats (WebP, AVIF) with `<picture>` fallbacks
- Provide responsive images with `srcset` and `sizes` attributes
- Set `width` and `height` on `<img>` tags to prevent layout shift
- Use `loading="lazy"` for below-the-fold images
- Use `asset()` / `assetSrcSet()` for cache-busted URLs