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
+82
View File
@@ -0,0 +1,82 @@
---
description: |
Create JSON API endpoints by defining handler-only routes without a page component.
---
A route that exports only `handlers` (no default component export) becomes an
API endpoint - it returns responses directly instead of rendering HTML.
## Basic JSON API
```ts routes/api/users.ts
import { define } from "@/utils.ts";
export const handlers = define.handlers({
GET(ctx) {
const users = [{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }];
return Response.json(users);
},
});
```
A `GET /api/users` request returns:
```json
[{ "id": 1, "name": "Alice" }, { "id": 2, "name": "Bob" }]
```
## Method-specific handlers
Define different logic per HTTP method. Methods you don't define will
automatically return `405 Method Not Allowed`:
```ts routes/api/posts/[id].ts
import { define } from "@/utils.ts";
export const handlers = define.handlers({
async GET(ctx) {
const post = await db.posts.find(ctx.params.id);
if (!post) {
return Response.json({ error: "Not found" }, { status: 404 });
}
return Response.json(post);
},
async PUT(ctx) {
const body = await ctx.req.json();
const post = await db.posts.update(ctx.params.id, body);
return Response.json(post);
},
async DELETE(ctx) {
await db.posts.delete(ctx.params.id);
return new Response(null, { status: 204 });
},
});
```
## Catch-all handler
Export a single function instead of a method object to handle all HTTP methods:
```ts routes/api/health.ts
import { define } from "@/utils.ts";
export const handlers = define.handlers((ctx) => {
return Response.json({ status: "ok", method: ctx.req.method });
});
```
## Programmatic API routes
API routes can also be defined directly on the app without
[file-based routing](/docs/concepts/file-routing):
```ts main.ts
const app = new App()
.get("/api/time", () => Response.json({ time: new Date().toISOString() }))
.post("/api/echo", async (ctx) => {
const body = await ctx.req.text();
return new Response(body);
});
```
+295
View File
@@ -0,0 +1,295 @@
---
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;
});
```
+5 -4
View File
@@ -6,10 +6,11 @@ description: |
In this chapter of the Fresh documentation, you can find examples of features
that you may like in your Fresh project.
- [Active links](./examples/active-links)
- [API Routes](./examples/api-routes)
- [DaisyUI](./examples/daisyui)
- [Markdown](./examples/markdown)
- [Migration guide](./examples/migration-guide)
- [Rendering Markdown](./examples/markdown)
- [Rendering raw HTML](./examples/rendering-raw-html)
- [Session management](./examples/session-management)
- [Sharing state between islands](./examples/sharing-state-between-islands)
- [Active links](./examples/active-links)
- [Session management](./examples/session-management)
- [Common Patterns](./examples/common-patterns)
+1 -8
View File
@@ -22,18 +22,11 @@ and some interesting text here
> oh look a blockquote
```
4. Add a route that renders that file
3. Add a route that renders that file
```tsx main.ts
import { CSS, render as renderMarkdown } from "@deno/gfm";
const CONTENT = `## some heading
and some interesting text here
> oh look a blockquote
`;
const app = new App();
app.get("/", async (ctx) => {
-322
View File
@@ -1,322 +0,0 @@
---
description: |
Migration guide for Fresh 2.x
---
We tried to keep breaking changes in Fresh 2 as minimal as possible, but some
changes need to be updated manually. Fresh 2 comes with many quality of life
[improvements](https://deno.com/blog/an-update-on-fresh) that make it easier to
extend and adapt Fresh. We've created this upgrade guide as part of upgrading
our own apps here at Deno.
Use this guide to migrate a Fresh 1.x app to Fresh 2.
## Applying automatic updates
Most changes can be applied automatically with the update script. Start the
update by running it in your project directory:
```sh Terminal
deno run -Ar jsr:@fresh/update
```
This will apply most API changes made in Fresh 2 automatically update like
changing `$fresh/server.ts` imports to `fresh`.
## Getting `main.ts` and `dev.ts` ready
Configuring Fresh doesn't require a dedicated config file anymore. You can
delete the `fresh.config.ts` file. The `fresh.gen.ts` manifest file isn't needed
anymore either.
```diff Project structure
<project root>
├── routes/
- ├── dev.ts
- ├── fresh.gen.ts
- ├── fresh.config.ts
└── main.ts
```
Fresh 2 takes great care in ensuring that code that's only needed during
development is separate from production code. This split makes deployments much
smaller, quicker to upload and allows them to boot up much quicker in
production.
### Replacing `dev.ts` with `vite.config.ts`
Delete `dev.ts` and create a `vite.config.ts` file instead. Pass your custom
Fresh configuration to the [fresh vite plugin](/docs/advanced/vite).
```ts vite.config.ts
import { defineConfig } from "vite";
import { fresh } from "@fresh/plugin-vite";
import tailwindcss from "@tailwindcss/vite";
export default defineConfig({
plugins: [
fresh(),
tailwindcss(),
],
});
```
### Add a `client.ts` file
The `client.ts` file is the main entry file for client-side code. Since vite
requires everything to be part of the internal module graph to get hot module
reloading to work, this is also the place where you import CSS assets.
```diff Project structure
<project root>
├── routes/
+ ├── client.ts
├── vite.config.ts
└── main.ts
```
```ts client.ts
// Import CSS files here for hot module reloading to work.
import "./assets/styles.css";
```
### Updating `main.ts`
Similarly, configuration related to running Fresh in production can be passed to
`new App()`:
```ts main.ts
import { App, staticFiles } from "fresh";
export const app = new App()
// Add static file serving middleware
.use(staticFiles())
// Enable file-system based routing
.fsRoutes();
```
## Merging error pages
Both the `_500.tsx` and `_404.tsx` template have been unified into a single
`_error.tsx` template.
```diff Project structure
└── <root>/routes/
- ├── _404.tsx
- ├── _500.tsx
+ ├── _error.tsx
└── ...
```
Inside the `_error.tsx` template you can show different content based on errors
or status codes with the following code:
```tsx routes/_error.tsx
export default function ErrorPage(props: PageProps) {
const error = props.error; // Contains the thrown Error or HTTPError
if (error instanceof HttpError) {
const status = error.status; // HTTP status code
// Render a 404 not found page
if (status === 404) {
return <h1>404 - Page not found</h1>;
}
}
return <h1>Oh no...</h1>;
}
```
## Updating tasks
The server entrypoint is now generated by Fresh for more optimal startup times.
This means you need to update your task when launching Fresh in production mode.
To launch Fresh in production mode:
```diff
- deno run -A main.ts
+ deno serve -A _fresh/server.js
```
You'll likely have that command inside your `deno.json` as a task. Update it
accordingly.
```diff deno.json
{
"tasks":
- "dev": "deno run -A dev.ts",
- "build": "deno run -A dev.ts build",
- "preview": "deno run -A main.ts"
+ "dev": "vite",
+ "build": "vite build",
+ "preview": "deno serve -A _fresh/server.js"
}
}
```
## Update imports
Add `jsr:@fresh/plugin-vite` and `npm:vite` to `imports` in your `deno.json`
file, either manually or with this command:
```shell
deno install npm:vite jsr:@fresh/plugin-vite
```
This should be enough in most cases. If you still encounter problems, you may
also need to update `compilerOptions` and other parts. For a complete,
up‑to‑date example, generate a new app (“Migrate by example” below) and compare.
> Note: With Vite, Fresh’s Tailwind plugin (`jsr:@fresh/plugin-tailwindcss*`) is
> not needed; use the Vite integration instead (e.g. `npm:@tailwindcss/vite`).
## Update deployment settings
Fresh 2 requires assets to be built during deployment instead of building them
on demand. Run the `deno task build` or `deno run build` command as part of your
deployment process.
If you have already set up Fresh's 1.x "Ahead-of-Time Builds", then no changes
are necessary.
## Trailing slash handling
The handling trailing slashes has been extracted to an optional middleware that
you can add if needed. This middleware can be used to ensure that URLs always
have a trailing slash at the end or that they will never have one.
```diff main.ts
- import { App, staticFiles } from "fresh";
+ import { App, staticFiles, trailingSlashes } from "fresh";
export const app = new App({ root: import.meta.url })
.use(staticFiles())
+ .use(trailingSlashes("never"));
```
## Automatic updates
> [info]: The changes listed here are applied automatically when running the
> [`@fresh/update`](https://jsr.io/@fresh/update) script and you shouldn't need
> to have to do these yourself.
### Unified middleware signatures
Middleware, handler and route component signatures have been unified to all look
the same. Instead of receiving two arguments, they receive one. The `Request`
object is stored on the context object as `ctx.req`.
```diff middleware.ts
- const middleware = (req, ctx) => new Response("ok");
+ const middleware = (ctx) => new Response("ok");
```
Same is true for handlers:
```diff route/page.tsx
export const handler = {
- GET(req, ctx) {
+ GET(ctx) {
return new Response("ok");
},
};
```
...and async route components:
```diff routes/my-page.tsx
- export default async function MyPage(req: Request, ctx: RouteContext) {
+ export default async function MyPage(props: PageProps) {
const value = await loadFooValue();
return <p>foo is: {value}</p>;
}
```
All the various context interfaces have been consolidated and simplified:
| Fresh 1.x | Fresh 2.x |
| --------------------------------------------- | ----------------------------------- |
| `AppContext`, `LayoutContext`, `RouteContext` | [`Context`](/docs/concepts/context) |
### Context methods
The `ctx.renderNotFound()` method has been removed in favor of throwing an
`HttpError` instance. This allows all middlewares to optionally participate in
error handling. Other properties have been moved or renamed to make it easier to
re-use existing objects internally as a minor performance optimization.
| Fresh 1.x | Fresh 2.x |
| ---------------------- | -------------------------- |
| `ctx.renderNotFound()` | `throw new HttpError(404)` |
| `ctx.basePath` | `ctx.config.basePath` |
| `ctx.remoteAddr` | `ctx.info.remoteAddr` |
### `ctx.render()`
The _meaning_ of `ctx.render()` has changed. In Fresh 1.x this was used to pass
data from a handler to a component. In Fresh 2.x this function has been
generalized to render JSX, so it's no longer needed.
Fresh 1.x:
```ts
export const handler = {
async GET(req, ctx) {
const data = await Query();
await ctx.render({ value: data });
},
};
export default function Page({ data }) {
// ...
}
```
Fresh 2 (removed):
```ts
export const handler = {
async GET(ctx) {
const data = await Query();
return { data: { value: data } };
},
};
export default function Page({ data }) {
// ...
}
```
To render JSX in general, use the `ctx.render()` function:
```tsx
const app = new App()
.get("/", () => ctx.render(<h1>hello</h1>));
```
## `createHandler`
The `createHandler` function was often used to launch Fresh for tests. This can
be now done via vite's `createBuilder` function. See the
[testing page](/docs/testing) for more information.
## `deno compile`
If you're using `deno compile` to generate a binary out of the Fresh app be sure
to [update the command](/docs/deployment/deno-compile) to generate the binary.
## Getting help
### 1. Migrate by example
If you run into problems with upgrading your app, first, try starting a new
Fresh 2 project and looking at the new structure.
eg. `mkdir fresh2-demo && cd fresh2-demo && deno run -Ar jsr:@fresh/init`
### 2. Document
If you still can't solve the migration problems. Please reach out to us by
creating an issue here https://github.com/denoland/fresh/issues/new . That way
we can improve this migration guide for everyone.
+2 -2
View File
@@ -4,8 +4,8 @@ description: |
---
Text content in Fresh is always escaped, whether serverside rendered or rendered
in islands. While this generally desired, it can create issues in certain
situations.
in [islands](/docs/concepts/islands). While this is generally desired, it can
create issues in certain situations.
To address this you can render raw HTML via Preact's `dangerouslySetInnerHTML`
prop:
@@ -3,9 +3,6 @@ description: |
When you need to have state shared between islands, this page provides a few recipes.
---
All of this content is lifted from this great
[example](https://github.com/lucacasonato/fresh-with-signals) by Luca.
## Multiple Sibling Islands with Independent State
Imagine we have `Counter.tsx` like this:
@@ -87,87 +84,82 @@ export default function Home() {
they would all use the same value.
## Independent Islands
## Sharing State Across Independent Islands
We can also create a `signal` in a utility file and export it for consumption
across multiple places.
```ts utils/cart.ts
import { signal } from "@preact/signals";
export const cart = signal<string[]>([]);
```
When islands are not rendered as siblings (e.g. one in a sidebar and one in the
main content), you can share state by creating a signal in a parent component
and passing it as a prop to each island.
```tsx islands/AddToCart.tsx
import { type Signal } from "@preact/signals";
import { Button } from "../components/Button.tsx";
import { cart } from "../utils/cart.ts";
interface AddToCartProps {
cart: Signal<string[]>;
product: string;
}
// This island is used to add a product to the cart state.
export default function AddToCart(props: AddToCartProps) {
const { cart, product } = props;
return (
<Button
onClick={() => (cart.value = [...cart.value, props.product])}
onClick={() => (cart.value = [...cart.value, product])}
class="w-full"
>
Add{cart.value.includes(props.product) ? " another" : ""} "{props.product}
" to cart
Add{cart.value.includes(product) ? " another" : ""} "{product}" to cart
</Button>
);
}
```
```tsx islands/Cart.tsx
import { type Signal } from "@preact/signals";
import { Button } from "../components/Button.tsx";
import { cart } from "../utils/cart.ts";
import * as icons from "../components/Icons.tsx";
// This island is used to display the cart contents and remove items from it.
export default function Cart() {
return (
<h1 class="text-xl flex items-center justify-center">
Cart
</h1>
interface CartProps {
cart: Signal<string[]>;
}
<ul class="w-full bg-gray-50 mt-2 p-2 rounded-sm min-h-[6.5rem]">
{cart.value.length === 0 && (
<li class="text-center my-4">
<div class="text-gray-400">
<icons.Cart class="w-8 h-8 inline-block" />
<div>
Your cart is empty.
export default function Cart(props: CartProps) {
const { cart } = props;
return (
<div>
<h1 class="text-xl flex items-center justify-center">Cart</h1>
<ul class="w-full bg-gray-50 mt-2 p-2 rounded-sm min-h-[6.5rem]">
{cart.value.length === 0 && (
<li class="text-center my-4">
<div class="text-gray-400">
<icons.Cart class="w-8 h-8 inline-block" />
<div>Your cart is empty.</div>
</div>
</div>
</li>
)}
{cart.value.map((product, index) => (
<CartItem product={product} index={index} />
))}
</ul>
</li>
)}
{cart.value.map((product, index) => (
<CartItem cart={cart} product={product} index={index} />
))}
</ul>
</div>
);
}
interface CartItemProps {
cart: Signal<string[]>;
product: string;
index: number;
}
function CartItem(props: CartItemProps) {
const remove = () => {
const newCart = [...cart.value];
const newCart = [...props.cart.value];
newCart.splice(props.index, 1);
cart.value = newCart;
props.cart.value = newCart;
};
return (
<li class="flex items-center justify-between gap-1">
<icons.Lemon class="text-gray-500" />
<div class="flex-1">
{props.product}
</div>
<div class="flex-1">{props.product}</div>
<Button onClick={remove} aria-label="Remove" class="border-none">
<icons.X class="inline-block w-4 h-4" />
</Button>
@@ -176,13 +168,33 @@ function CartItem(props: CartItemProps) {
}
```
Now we can add the islands to our site by doing the following:
Then wire them together from a route, passing the same signal to both:
```tsx routes/cart.tsx
<AddToCart product="Lemon" />
<AddToCart product="Lime" />
<Cart />
import { useSignal } from "@preact/signals";
import AddToCart from "../islands/AddToCart.tsx";
import Cart from "../islands/Cart.tsx";
import { define } from "../utils.ts";
export default define.page(function CartPage() {
const cart = useSignal<string[]>([]);
return (
<div>
<AddToCart cart={cart} product="Lemon" />
<AddToCart cart={cart} product="Lime" />
<Cart cart={cart} />
</div>
);
});
```
What happens as a result? The `cart` signal is shared across the two `AddToCart`
islands _and_ the `Cart` island.
The `cart` signal is created per-render (not at module level), so each request
gets its own independent cart. Fresh [serializes](/docs/advanced/serialization)
the signal and passes it to both islands, keeping them in sync on the client.
> [!CAUTION]
> Avoid creating signals at the module level (e.g.
> `export const cart =
> signal([])` in a utility file). Module-level state is
> shared across all requests on the server, which means different users would
> see the same cart. Always create signals inside components or handlers.