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:
co-authored by
Claude Opus 4.6
parent
059183b230
commit
103427f9da
@@ -12,7 +12,7 @@ with workspace members in `packages/*` and `www/`.
|
||||
- **`packages/plugin-vite/`** (`@fresh/plugin-vite`): Vite integration plugin
|
||||
with dev server, SSR/client builds, and HMR.
|
||||
- **`packages/init/`** (`@fresh/init`): Project scaffolding
|
||||
(`deno run -A jsr:@fresh/init`).
|
||||
(`deno create @fresh/init`).
|
||||
- **`packages/update/`** (`@fresh/update`): Automated Fresh 1.x to 2.x migration
|
||||
tool using ts-morph for AST transforms.
|
||||
- **`packages/build-id/`** (`@fresh/build-id`): Build/deployment ID generation.
|
||||
|
||||
@@ -29,7 +29,7 @@ You can scaffold a new project by running the Fresh init script. To scaffold a
|
||||
project run the following:
|
||||
|
||||
```sh
|
||||
deno run -Ar jsr:@fresh/init
|
||||
deno create @fresh/init
|
||||
```
|
||||
|
||||
Then navigate to the newly created project folder:
|
||||
|
||||
@@ -76,7 +76,7 @@ Let's use a typical documentation page layout as an example. It often features a
|
||||
main content area and a sidebar of links to switch between pages of the
|
||||
documentation (marked green here).
|
||||
|
||||

|
||||

|
||||
|
||||
The code for such a page (excluding styling) might look like this:
|
||||
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Verifies that all image references in documentation markdown files
|
||||
* point to existing files in www/static/.
|
||||
*
|
||||
* Run: deno test -A docs/check_images_test.ts
|
||||
*/
|
||||
import { walk } from "jsr:@std/fs@1/walk";
|
||||
import { join, resolve } from "jsr:@std/path@1";
|
||||
|
||||
const ROOT = resolve(import.meta.dirname!);
|
||||
const PROJECT_ROOT = resolve(ROOT, "..");
|
||||
const DOCS_DIR = ROOT;
|
||||
const STATIC_DIR = join(PROJECT_ROOT, "www", "static");
|
||||
|
||||
const IMAGE_RE = /!\[.*?\]\(([^)]+)\)/g;
|
||||
|
||||
Deno.test("all doc image references point to existing files", async () => {
|
||||
const errors: string[] = [];
|
||||
|
||||
for await (
|
||||
const entry of walk(DOCS_DIR, {
|
||||
exts: [".md", ".mdx"],
|
||||
includeDirs: false,
|
||||
})
|
||||
) {
|
||||
const content = await Deno.readTextFile(entry.path);
|
||||
const relativePath = entry.path.slice(PROJECT_ROOT.length);
|
||||
|
||||
for (const match of content.matchAll(IMAGE_RE)) {
|
||||
const imgPath = match[1];
|
||||
|
||||
// Skip external URLs
|
||||
if (imgPath.startsWith("http://") || imgPath.startsWith("https://")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Doc image paths like "/docs/foo.png" map to "www/static/docs/foo.png"
|
||||
const fsPath = join(STATIC_DIR, imgPath);
|
||||
|
||||
try {
|
||||
await Deno.stat(fsPath);
|
||||
} catch {
|
||||
errors.push(`${relativePath}: image not found: ${imgPath}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (errors.length > 0) {
|
||||
throw new Error(
|
||||
`Found ${errors.length} broken image reference(s):\n\n${
|
||||
errors.join("\n")
|
||||
}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
---
|
||||
description: |
|
||||
Quick reference for all public exports from Fresh's entry points: fresh, fresh/runtime, and fresh/dev.
|
||||
---
|
||||
|
||||
This page lists all public exports from Fresh's entry points.
|
||||
|
||||
> [info]: You can also explore Fresh's full API documentation on JSR:
|
||||
> [`@fresh/core`](https://jsr.io/@fresh/core/doc)
|
||||
|
||||
## `fresh`
|
||||
|
||||
The main entry point for server-side code.
|
||||
|
||||
```ts
|
||||
import { App, createDefine, HttpError, page, staticFiles } from "fresh";
|
||||
```
|
||||
|
||||
| Export | Kind | Description |
|
||||
| --------------------------------------------------------------------- | -------- | -------------------------------------------------------------------------------------------------- |
|
||||
| [`App`](https://jsr.io/@fresh/core/doc/~/App) | Class | The main application class. See [App](/docs/concepts/app). |
|
||||
| [`staticFiles`](https://jsr.io/@fresh/core/doc/~/staticFiles) | Function | Middleware for serving static files. See [Static Files](/docs/concepts/static-files). |
|
||||
| [`createDefine`](https://jsr.io/@fresh/core/doc/~/createDefine) | Function | Create type-safe `define.*` helpers. See [Define Helpers](/docs/advanced/define). |
|
||||
| [`page`](https://jsr.io/@fresh/core/doc/~/page) | Function | Return data from a handler to a page component. See [Data Fetching](/docs/concepts/data-fetching). |
|
||||
| [`HttpError`](https://jsr.io/@fresh/core/doc/~/HttpError) | Class | Throw HTTP errors with status codes. See [Error Handling](/docs/advanced/error-handling). |
|
||||
| [`cors`](https://jsr.io/@fresh/core/doc/~/cors) | Function | CORS middleware. See [cors](/docs/plugins/cors). |
|
||||
| [`csrf`](https://jsr.io/@fresh/core/doc/~/csrf) | Function | CSRF protection middleware. See [csrf](/docs/plugins/csrf). |
|
||||
| [`csp`](https://jsr.io/@fresh/core/doc/~/csp) | Function | Content Security Policy middleware. See [csp](/docs/plugins/csp). |
|
||||
| [`trailingSlashes`](https://jsr.io/@fresh/core/doc/~/trailingSlashes) | Function | Trailing slash enforcement middleware. See [trailingSlashes](/docs/plugins/trailing-slashes). |
|
||||
|
||||
**Types:**
|
||||
|
||||
| Export | Kind | Description |
|
||||
| --------------------------------------------------------------------------------------------------------------------------------------------- | --------- | --------------------------------------------------------------------------- |
|
||||
| [`Context`](https://jsr.io/@fresh/core/doc/~/Context) / [`FreshContext`](https://jsr.io/@fresh/core/doc/~/FreshContext) | Interface | The request context passed to all middlewares and handlers. |
|
||||
| [`PageProps`](https://jsr.io/@fresh/core/doc/~/PageProps) | Type | Props received by page components (`data`, `url`, `params`, `state`, etc.). |
|
||||
| [`Middleware`](https://jsr.io/@fresh/core/doc/~/Middleware) / [`MiddlewareFn`](https://jsr.io/@fresh/core/doc/~/MiddlewareFn) | Type | Middleware function type. |
|
||||
| [`HandlerFn`](https://jsr.io/@fresh/core/doc/~/HandlerFn) | Type | Single handler function type. |
|
||||
| [`HandlerByMethod`](https://jsr.io/@fresh/core/doc/~/HandlerByMethod) | Type | Object with per-method handler functions. |
|
||||
| [`RouteHandler`](https://jsr.io/@fresh/core/doc/~/RouteHandler) | Type | Union of `HandlerFn` and `HandlerByMethod`. |
|
||||
| [`PageResponse`](https://jsr.io/@fresh/core/doc/~/PageResponse) | Type | Return type of `page()`. |
|
||||
| [`RouteConfig`](https://jsr.io/@fresh/core/doc/~/RouteConfig) | Interface | Route configuration (`routeOverride`, `skipInheritedLayouts`, etc.). |
|
||||
| [`LayoutConfig`](https://jsr.io/@fresh/core/doc/~/LayoutConfig) | Interface | Layout configuration (`skipInheritedLayouts`, `skipAppWrapper`). |
|
||||
| [`Define`](https://jsr.io/@fresh/core/doc/~/Define) | Interface | Type of the object returned by `createDefine()`. |
|
||||
| [`FreshConfig`](https://jsr.io/@fresh/core/doc/~/FreshConfig) / [`ResolvedFreshConfig`](https://jsr.io/@fresh/core/doc/~/ResolvedFreshConfig) | Interface | App configuration types. |
|
||||
| [`ListenOptions`](https://jsr.io/@fresh/core/doc/~/ListenOptions) | Interface | Options for `app.listen()`. |
|
||||
| [`Island`](https://jsr.io/@fresh/core/doc/~/Island) | Type | Island component type. |
|
||||
| [`Method`](https://jsr.io/@fresh/core/doc/~/Method) | Type | HTTP method union type. |
|
||||
| [`RouteData`](https://jsr.io/@fresh/core/doc/~/RouteData) | Type | Data type returned by route handlers via `page()`. |
|
||||
| [`Lazy`](https://jsr.io/@fresh/core/doc/~/Lazy) / [`MaybeLazy`](https://jsr.io/@fresh/core/doc/~/MaybeLazy) | Type | Utility types for lazily-loaded routes and middleware. |
|
||||
| [`CORSOptions`](https://jsr.io/@fresh/core/doc/~/CORSOptions) | Interface | Options for `cors()`. |
|
||||
| [`CsrfOptions`](https://jsr.io/@fresh/core/doc/~/CsrfOptions) | Interface | Options for `csrf()`. |
|
||||
| [`CSPOptions`](https://jsr.io/@fresh/core/doc/~/CSPOptions) | Interface | Options for `csp()`. |
|
||||
|
||||
## `fresh/runtime`
|
||||
|
||||
Shared runtime utilities for both server and client code. Safe to import in
|
||||
[islands](/docs/concepts/islands).
|
||||
|
||||
```ts
|
||||
import {
|
||||
asset,
|
||||
assetSrcSet,
|
||||
Head,
|
||||
HttpError,
|
||||
IS_BROWSER,
|
||||
Partial,
|
||||
} from "fresh/runtime";
|
||||
```
|
||||
|
||||
| Export | Kind | Description |
|
||||
| --------------------------------------------------------------------- | --------- | ---------------------------------------------------------------------------------------------- |
|
||||
| [`IS_BROWSER`](https://jsr.io/@fresh/core/doc/runtime/~/IS_BROWSER) | Constant | `true` in the browser, `false` on the server. Use to guard browser-only code. |
|
||||
| [`asset`](https://jsr.io/@fresh/core/doc/runtime/~/asset) | Function | Add cache-busting query params to asset URLs. See [Static Files](/docs/concepts/static-files). |
|
||||
| [`assetSrcSet`](https://jsr.io/@fresh/core/doc/runtime/~/assetSrcSet) | Function | Apply `asset()` to all URLs in a `srcset` string. |
|
||||
| [`Partial`](https://jsr.io/@fresh/core/doc/runtime/~/Partial) | Component | Mark a region for partial updates. See [Partials](/docs/advanced/partials). |
|
||||
| [`Head`](https://jsr.io/@fresh/core/doc/runtime/~/Head) | Component | Add elements to the document `<head>`. See [<head> element](/docs/advanced/head). |
|
||||
| [`HttpError`](https://jsr.io/@fresh/core/doc/runtime/~/HttpError) | Class | HTTP error class (re-exported from `fresh`). |
|
||||
|
||||
## `fresh/dev`
|
||||
|
||||
Development and build tools. Only used in `dev.ts` (legacy) or build scripts.
|
||||
|
||||
```ts
|
||||
import { Builder } from "fresh/dev";
|
||||
```
|
||||
|
||||
| Export | Kind | Description |
|
||||
| --------------------------------------------------------- | ----- | ---------------------------------------------------------------------- |
|
||||
| [`Builder`](https://jsr.io/@fresh/core/doc/dev/~/Builder) | Class | Pre-Vite build system (legacy). See [Builder](/docs/advanced/builder). |
|
||||
|
||||
**Types:**
|
||||
|
||||
| Export | Kind | Description |
|
||||
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | ----------------------------- |
|
||||
| [`BuildOptions`](https://jsr.io/@fresh/core/doc/dev/~/BuildOptions) | Interface | Options for `new Builder()`. |
|
||||
| [`ResolvedBuildConfig`](https://jsr.io/@fresh/core/doc/dev/~/ResolvedBuildConfig) | Interface | Resolved build configuration. |
|
||||
| [`OnTransformArgs`](https://jsr.io/@fresh/core/doc/dev/~/OnTransformArgs) / [`OnTransformOptions`](https://jsr.io/@fresh/core/doc/dev/~/OnTransformOptions) / [`TransformFn`](https://jsr.io/@fresh/core/doc/dev/~/TransformFn) | Type | Build plugin hook types. |
|
||||
@@ -1,12 +1,51 @@
|
||||
---
|
||||
description: |
|
||||
Add a global app wrapper to provide common meta tags or context for application routes.
|
||||
The app wrapper defines the outermost HTML shell shared by all pages - the <html>, <head>, and <body> tags.
|
||||
---
|
||||
|
||||
The app wrapper component is a Preact component that represents the outer
|
||||
structure of the HTML document, typically up until the `<body>`-tag. It is only
|
||||
rendered on the server and never on the client. The passed `Component` value
|
||||
represents the children of this component.
|
||||
The app wrapper is the outermost component in Fresh's rendering hierarchy. It
|
||||
defines the `<html>`, `<head>`, and `<body>` tags that every page shares. It is
|
||||
only rendered on the server.
|
||||
|
||||
## When to use an app wrapper
|
||||
|
||||
Use an app wrapper when you need to:
|
||||
|
||||
- Set the document language (`<html lang="en">`)
|
||||
- Include global `<meta>` tags, fonts, or stylesheets
|
||||
- Add analytics scripts or structured data to every page
|
||||
- Set a global `<body>` class or data attribute
|
||||
- Provide a consistent HTML skeleton without repeating it in every layout
|
||||
|
||||
If you're using [file-based routing](/docs/concepts/file-routing), create a
|
||||
`routes/_app.tsx` file. Otherwise, register it programmatically with
|
||||
`app.appWrapper()`.
|
||||
|
||||
## Basic example
|
||||
|
||||
```tsx routes/_app.tsx
|
||||
import { define } from "../utils.ts";
|
||||
|
||||
export default define.page(({ Component, url }) => {
|
||||
return (
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>My App</title>
|
||||
<link rel="stylesheet" href="/styles.css" />
|
||||
</head>
|
||||
<body>
|
||||
<Component />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
## Programmatic registration
|
||||
|
||||
When building your app with `new App()` instead of file-based routing:
|
||||
|
||||
```tsx main.tsx
|
||||
function AppWrapper({ Component }) {
|
||||
@@ -26,8 +65,75 @@ function AppWrapper({ Component }) {
|
||||
app.appWrapper(AppWrapper);
|
||||
```
|
||||
|
||||
Every [`ctx.render()`](/docs/concepts/context#render-1) call will include the
|
||||
app wrapper component by default, unless opted out.
|
||||
Only one app wrapper is supported per [`App`](/docs/concepts/app) instance.
|
||||
|
||||
Note that only one app wrapper component is supported per
|
||||
[`App`](/docs/concepts/app) instance.
|
||||
## How it fits in the render hierarchy
|
||||
|
||||
When Fresh renders a page, the components nest like this:
|
||||
|
||||
1. **App wrapper** (`_app.tsx`) - outermost, provides `<html>`/`<head>`/`<body>`
|
||||
2. **[Layouts](/docs/concepts/layouts)** (`_layout.tsx`) - shared page chrome
|
||||
(nav, sidebar, footer)
|
||||
3. **Page component** - the route itself
|
||||
|
||||
The app wrapper wraps everything. Layouts sit inside it and wrap the page.
|
||||
|
||||
## Accessing request data
|
||||
|
||||
The app wrapper receives the same props as page components - `url`, `state`,
|
||||
`params`, and more. This is useful for conditional logic:
|
||||
|
||||
```tsx routes/_app.tsx
|
||||
import { define } from "../utils.ts";
|
||||
|
||||
export default define.page(({ Component, url, state }) => {
|
||||
return (
|
||||
<html lang="en" data-theme={state.theme ?? "light"}>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>My App</title>
|
||||
<meta property="og:url" content={url.href} />
|
||||
<link rel="canonical" href={url.href} />
|
||||
</head>
|
||||
<body>
|
||||
<Component />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
## Skipping the app wrapper
|
||||
|
||||
Some routes may need to bypass the app wrapper entirely - for example, API
|
||||
routes that return JSON, or pages that need a completely different HTML
|
||||
structure. Use `skipAppWrapper` in the route config:
|
||||
|
||||
```tsx routes/embed.tsx
|
||||
import { type RouteConfig } from "fresh";
|
||||
import { define } from "../utils.ts";
|
||||
|
||||
export const config: RouteConfig = {
|
||||
skipAppWrapper: true,
|
||||
};
|
||||
|
||||
export default define.page(() => {
|
||||
return (
|
||||
<html>
|
||||
<head>
|
||||
<title>Embed</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="widget">Embeddable widget</div>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
When using programmatic layouts, pass `skipAppWrapper` as an option:
|
||||
|
||||
```ts main.ts
|
||||
app.layout("/embed", EmbedLayout, { skipAppWrapper: true });
|
||||
```
|
||||
|
||||
@@ -171,7 +171,7 @@ For more information on how to use tailwindcss, check out
|
||||
You can customize the tailwind plugin via the following options:
|
||||
|
||||
```ts dev.ts
|
||||
tailwind(builder, app, {
|
||||
tailwind(builder, {
|
||||
// Exclude certain files from processing
|
||||
exclude: ["/admin/**", "*.temp.css"],
|
||||
// Force optimization (defaults to production mode)
|
||||
@@ -183,7 +183,7 @@ tailwind(builder, app, {
|
||||
|
||||
### Tailwindcss v3
|
||||
|
||||
If can't update to the current version of tailwindcss we have a dedicated
|
||||
If you can't update to the current version of tailwindcss we have a dedicated
|
||||
`@fresh/plugin-tailwindcss-v3` plugin that uses tailwindcss v3. That way you can
|
||||
decided on your own when it's best to update to v4.
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
---
|
||||
description: |
|
||||
Define helpers are a less TypeScripty way to declare middlewares, routes and layouts
|
||||
Define helpers are a less TypeScripty way to declare [middlewares](/docs/concepts/middleware), routes and [layouts](/docs/concepts/layouts)
|
||||
---
|
||||
|
||||
Define helpers can be used to shorten the amount of types you have to type
|
||||
yourself in code. They are entirely optional as some developers prefer the
|
||||
explicitness of types, other's like the convenience of `define.*` helpers.
|
||||
explicitness of types, others like the convenience of `define.*` helpers.
|
||||
|
||||
Without define helpers:
|
||||
|
||||
@@ -72,7 +72,7 @@ export default define.page<typeof handler>((props) => {
|
||||
});
|
||||
```
|
||||
|
||||
There is also a `define.layout()` helper for layouts:
|
||||
There is also a `define.layout()` helper for [layouts](/docs/concepts/layouts):
|
||||
|
||||
```tsx
|
||||
export default define.layout((props) => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
description: |
|
||||
Error pages can be used to customize the page that is shown when an error occurs in the application.
|
||||
How to use environment variables in Fresh, including public variables that are inlined into island bundles.
|
||||
---
|
||||
|
||||
Environment variables in Deno are typically read via `Deno.env.get()` or
|
||||
@@ -9,7 +9,7 @@ see
|
||||
[how to use Environment Variables in Deno](https://docs.deno.com/runtime/reference/env_variables/).
|
||||
|
||||
On top of that Fresh automatically inlines all environment variables whose names
|
||||
start with `FRESH_PUBLIC_` during bundling of islands.
|
||||
start with `FRESH_PUBLIC_` during bundling of [islands](/docs/concepts/islands).
|
||||
|
||||
> [info]: This inlining step occurs when building the app (`deno task build`).
|
||||
> Environment variables inside islands cannot be read at runtime.
|
||||
|
||||
@@ -66,12 +66,19 @@ const app = new App()
|
||||
```
|
||||
|
||||
Accessing an unknown route like `/invalid` will trigger the `notFound`
|
||||
middleware. Contrary to generic error pages this handler cannot be nested.
|
||||
[middleware](/docs/concepts/middleware). Contrary to generic error pages this
|
||||
handler cannot be nested.
|
||||
|
||||
## Throwing HTTP errors
|
||||
|
||||
If you need to bail out of execution and need to respond with a particular HTTP
|
||||
error code, you can use Fresh's `HttpError` class.
|
||||
error code, you can use Fresh's `HttpError` class:
|
||||
|
||||
```ts
|
||||
import { HttpError } from "fresh";
|
||||
```
|
||||
|
||||
`HttpError` takes a status code and an optional message:
|
||||
|
||||
```ts middleware/auth.ts
|
||||
import { HttpError } from "fresh";
|
||||
@@ -84,14 +91,22 @@ async function authMiddleware(ctx) {
|
||||
throw new HttpError(404);
|
||||
}
|
||||
|
||||
// Forbidden with a custom message
|
||||
if (!isAdmin(user)) {
|
||||
throw new HttpError(403, "Admin access required");
|
||||
}
|
||||
|
||||
return await ctx.next();
|
||||
}
|
||||
```
|
||||
|
||||
You can check the status code of the thrown `HttpError` in your error handler:
|
||||
When an `HttpError` is thrown, Fresh catches it and invokes the error handler.
|
||||
You can check the status code in your error handler:
|
||||
|
||||
```ts main.ts
|
||||
app.onError((ctx) => {
|
||||
import { HttpError } from "fresh";
|
||||
|
||||
app.onError("*", (ctx) => {
|
||||
if (ctx.error instanceof HttpError) {
|
||||
const status = ctx.error.status;
|
||||
return new Response("oops", { status });
|
||||
@@ -100,3 +115,6 @@ app.onError((ctx) => {
|
||||
// ...
|
||||
});
|
||||
```
|
||||
|
||||
`HttpError` is also available in the browser via `fresh/runtime` for use in
|
||||
[island code](/docs/concepts/islands).
|
||||
|
||||
@@ -12,12 +12,13 @@ is a crucial element in HTML to set metadata for a page. It allows you to:
|
||||
- Include JavaScript code with `<script>`
|
||||
|
||||
> [info]: The outer HTML structure including `<head>` is typically created
|
||||
> inside `_app.tsx`.
|
||||
> inside [`_app.tsx`](/docs/concepts/app).
|
||||
|
||||
## Passing metadata from `ctx.state`
|
||||
|
||||
For simple scenarios passing metadata along from a handler or a middleware by
|
||||
writing to `ctx.state` is often sufficient.
|
||||
For simple scenarios passing metadata along from a handler or a
|
||||
[middleware](/docs/concepts/middleware) by writing to `ctx.state` is often
|
||||
sufficient.
|
||||
|
||||
```tsx routes/_app.tsx
|
||||
import { define } from "../util.ts";
|
||||
@@ -39,8 +40,8 @@ export default define.page((ctx) => {
|
||||
|
||||
## Using the `<Head>`-component
|
||||
|
||||
For more complex scenarios, or to set page metadata from islands, Fresh ships
|
||||
with the `<Head>`-component.
|
||||
For more complex scenarios, or to set page metadata from
|
||||
[islands](/docs/concepts/islands), Fresh ships with the `<Head>`-component.
|
||||
|
||||
> [info]: The `<Head>` component is not dynamic by default. It will not
|
||||
> automatically update the document title or other head elements on the client
|
||||
@@ -77,5 +78,10 @@ the matching element:
|
||||
5. No matching element was found, Fresh will create a new one and append it to
|
||||
`<head>`
|
||||
|
||||
When multiple `<Head>` components render an element with the same key, the
|
||||
**last one rendered wins**. Since Fresh renders top-down (app wrapper → layout →
|
||||
route → page component), a route page can override defaults set in `_app.tsx` by
|
||||
using the same `key` prop.
|
||||
|
||||
> [info]: The `<title>`-tag is automatically deduplicated, even without a `key`
|
||||
> prop.
|
||||
|
||||
@@ -4,3 +4,24 @@ description: |
|
||||
---
|
||||
|
||||
This section of the documentation describes advanced functionality of Fresh.
|
||||
|
||||
- [App wrapper](/docs/advanced/app-wrapper) - Customize the outer HTML structure
|
||||
- [Layouts](/docs/advanced/layouts) - Define programmatic layouts
|
||||
- [Error handling](/docs/advanced/error-handling) - Custom error and 404 pages
|
||||
- [Partials](/docs/advanced/partials) - Client-side partial page updates
|
||||
- [Forms](/docs/advanced/forms) - Handle form submissions
|
||||
- [Define helpers](/docs/advanced/define) - Type-safe route and middleware
|
||||
helpers
|
||||
- [Serialization](/docs/advanced/serialization) - What types can be passed as
|
||||
island props
|
||||
- [Environment variables](/docs/advanced/environment-variables) - Use env vars
|
||||
in islands
|
||||
- [Modifying <head>](/docs/advanced/head) - Manage meta tags, titles, and
|
||||
styles
|
||||
- [Vite plugin options](/docs/advanced/vite) - Configure the Fresh Vite plugin
|
||||
- [OpenTelemetry](/docs/advanced/opentelemetry) - Built-in tracing and
|
||||
observability
|
||||
- [API Reference](/docs/advanced/api-reference) - All public exports from Fresh
|
||||
- [Troubleshooting](/docs/advanced/troubleshooting) - Common issues and
|
||||
solutions
|
||||
- [Builder (Legacy)](/docs/advanced/builder) - Pre-Vite build system
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
description: "Create re-usable layouts across routes"
|
||||
---
|
||||
|
||||
This page covers **programmatic layouts** defined via `app.layout()`. If you're
|
||||
using file-based routing, see [Layouts (file-based)](/docs/concepts/layouts)
|
||||
instead.
|
||||
|
||||
Layouts are plain Preact components that are inherited based on the matching
|
||||
pattern. When you have a section on your site where all pages share the same
|
||||
HTML structure and only the content changes, a layout is a neat way to abstract
|
||||
@@ -32,15 +36,38 @@ If you browse to the `/` route, Fresh will render the following HTML
|
||||
</div>
|
||||
```
|
||||
|
||||
## Options
|
||||
## Multiple layouts
|
||||
|
||||
Add a layout and ignore all previously inherited ones.
|
||||
You can register multiple layouts for different paths. Layouts are inherited
|
||||
from parent paths - a layout at `"*"` applies to all routes, and more specific
|
||||
layouts are added on top:
|
||||
|
||||
```ts main.ts
|
||||
app.layout("/foo/bar", MyComponent, { skipInheritedLayouts: true });
|
||||
const app = new App()
|
||||
.layout("*", MainLayout) // Applied to all routes
|
||||
.layout("/admin/*", AdminLayout) // Added on top for /admin/* routes
|
||||
.get("/", (ctx) => ctx.render(<h1>Home</h1>))
|
||||
.get("/admin/dashboard", (ctx) => ctx.render(<h1>Dashboard</h1>));
|
||||
```
|
||||
|
||||
Ignore the app wrapper component:
|
||||
For `/admin/dashboard`, both `MainLayout` and `AdminLayout` will wrap the page
|
||||
component (MainLayout as the outer wrapper, AdminLayout as the inner).
|
||||
|
||||
## Overriding layouts
|
||||
|
||||
Use `skipInheritedLayouts` to replace all inherited layouts with a single one:
|
||||
|
||||
```ts main.ts
|
||||
const app = new App()
|
||||
.layout("*", MainLayout)
|
||||
.layout("/landing", LandingLayout, { skipInheritedLayouts: true })
|
||||
.get("/", (ctx) => ctx.render(<h1>Home</h1>)) // Uses MainLayout
|
||||
.get("/landing", (ctx) => ctx.render(<h1>Landing</h1>)); // Uses only LandingLayout
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
Ignore the [app wrapper](/docs/concepts/app) component:
|
||||
|
||||
```ts main.ts
|
||||
app.layout("/foo/bar", MyComponent, { skipAppWrapper: true });
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
---
|
||||
description: |
|
||||
Fresh has built-in OpenTelemetry instrumentation for tracing requests through middleware, handlers, and rendering.
|
||||
---
|
||||
|
||||
Fresh automatically instruments key operations with
|
||||
[OpenTelemetry](https://opentelemetry.io/) spans, giving you visibility into how
|
||||
requests flow through your application. No code changes are needed - just
|
||||
configure an exporter.
|
||||
|
||||
## What's instrumented
|
||||
|
||||
Fresh creates spans for:
|
||||
|
||||
- **[Middleware](/docs/concepts/middleware) execution** - each middleware in the
|
||||
chain
|
||||
- **Route handler execution** - handler function calls
|
||||
- **Rendering** - server-side page rendering, including async components
|
||||
- **[Static file](/docs/concepts/static-files) serving** - file lookups,
|
||||
caching, and responses
|
||||
- **Lazy route loading** - dynamic imports of route modules on first access
|
||||
|
||||
All spans are created under the `fresh` tracer (named with the current Fresh
|
||||
version). The root span for each request includes `http.route` with the matched
|
||||
route pattern (e.g. `GET /blog/:slug`), making it easy to group traces by route.
|
||||
|
||||
## Enabling tracing
|
||||
|
||||
Fresh uses the `@opentelemetry/api` package (the vendor-neutral API). Spans are
|
||||
created automatically - you just need to provide an OpenTelemetry SDK and
|
||||
exporter to collect them.
|
||||
|
||||
If no exporter is configured, the spans are silently discarded with no
|
||||
performance overhead.
|
||||
|
||||
### With Deno's built-in OpenTelemetry
|
||||
|
||||
Deno has
|
||||
[built-in OpenTelemetry support](https://docs.deno.com/runtime/fundamentals/open_telemetry/).
|
||||
Enable it with the `OTEL_DENO` environment variable:
|
||||
|
||||
```sh Terminal
|
||||
OTEL_DENO=true deno task start
|
||||
```
|
||||
|
||||
This exports traces to an OTLP-compatible collector. Configure the endpoint:
|
||||
|
||||
```sh Terminal
|
||||
OTEL_DENO=true \
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 \
|
||||
deno task start
|
||||
```
|
||||
|
||||
### With Deno Deploy
|
||||
|
||||
[Deno Deploy](/docs/deployment/deno-deploy) collects Fresh traces automatically
|
||||
when using the Fresh preset - no configuration needed. Traces appear in the Deno
|
||||
Deploy dashboard.
|
||||
|
||||
### With a custom exporter
|
||||
|
||||
You can use any OpenTelemetry-compatible backend (Jaeger, Zipkin, Honeycomb,
|
||||
Grafana Tempo, Datadog, etc.). Install the SDK and configure an exporter in your
|
||||
entry point:
|
||||
|
||||
```ts main.ts
|
||||
import { NodeSDK } from "@opentelemetry/sdk-node";
|
||||
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
|
||||
|
||||
const sdk = new NodeSDK({
|
||||
traceExporter: new OTLPTraceExporter({
|
||||
url: "https://your-collector.example.com/v1/traces",
|
||||
}),
|
||||
});
|
||||
sdk.start();
|
||||
```
|
||||
|
||||
## Span attributes
|
||||
|
||||
Fresh sets the following attributes on spans:
|
||||
|
||||
| Attribute | Span type | Description |
|
||||
| ----------------- | ----------- | -------------------------------------------------------------------------- |
|
||||
| `http.route` | Root | The matched route pattern (e.g. `/blog/:slug`) |
|
||||
| `fresh.span_type` | Various | Internal span classification (`render`, etc.) |
|
||||
| `fresh.cache` | Static file | Cache status (`immutable`, `not_modified`, `no_cache`, `invalid_bust_key`) |
|
||||
| `fresh.cache_key` | Static file | The cache bust key for the asset |
|
||||
|
||||
Errors in handlers or rendering are recorded on the span with
|
||||
`span.recordException()` and the span status is set to `ERROR`.
|
||||
|
||||
## Local development
|
||||
|
||||
### Console exporter
|
||||
|
||||
The quickest way to see traces is to print them to the console. Deno (2.7+)
|
||||
supports this out of the box - no extra dependencies or services needed:
|
||||
|
||||
```sh Terminal
|
||||
OTEL_DENO=true \
|
||||
OTEL_TRACES_EXPORTER=console \
|
||||
deno task start
|
||||
```
|
||||
|
||||
Each request prints its spans directly to stderr, showing the full breakdown of
|
||||
middleware, handler, and rendering timings.
|
||||
|
||||
### Jaeger
|
||||
|
||||
For a visual trace explorer, run [Jaeger](https://www.jaegertracing.io/) locally
|
||||
with Docker:
|
||||
|
||||
```sh Terminal
|
||||
docker run -d --name jaeger \
|
||||
-p 16686:16686 \
|
||||
-p 4317:4317 \
|
||||
jaegertracing/all-in-one:latest
|
||||
```
|
||||
|
||||
Then start your Fresh app pointing at the Jaeger collector:
|
||||
|
||||
```sh Terminal
|
||||
OTEL_DENO=true \
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 \
|
||||
deno task start
|
||||
```
|
||||
|
||||
Open `http://localhost:16686` to browse traces. You'll see each request broken
|
||||
down into its middleware, handler, and rendering spans.
|
||||
@@ -0,0 +1,102 @@
|
||||
---
|
||||
description: |
|
||||
What types can be passed as island props, how Fresh serializes data between server and client, and common pitfalls.
|
||||
---
|
||||
|
||||
When Fresh renders a page on the server, [island](/docs/concepts/islands) props
|
||||
must be serialized to JSON and sent to the browser for hydration. Fresh uses a
|
||||
custom serialization system that supports more types than standard
|
||||
`JSON.stringify`.
|
||||
|
||||
## Supported types
|
||||
|
||||
The following types can be passed as island props:
|
||||
|
||||
| Type | Notes |
|
||||
| ------------------------------------ | -------------------------------------------------------------------------------------------------------------------- |
|
||||
| `string`, `number`, `boolean` | Primitive types |
|
||||
| `null`, `undefined` | |
|
||||
| `bigint` | |
|
||||
| `NaN`, `Infinity`, `-Infinity`, `-0` | Special numeric values |
|
||||
| `Array` | Including sparse arrays |
|
||||
| Plain objects | Objects with string keys and serializable values |
|
||||
| `Date` | |
|
||||
| `URL` | |
|
||||
| `RegExp` | Including flags |
|
||||
| `Set` | Values must be serializable |
|
||||
| `Map` | Keys and values must be serializable |
|
||||
| `Uint8Array` | Binary data |
|
||||
| `Signal` | From `@preact/signals` - see [Signals](/docs/concepts/signals) |
|
||||
| `Computed Signal` | Read-only signals |
|
||||
| `Temporal.*` | `Instant`, `ZonedDateTime`, `PlainDate`, `PlainTime`, `PlainDateTime`, `PlainYearMonth`, `PlainMonthDay`, `Duration` |
|
||||
| JSX Elements | Server-rendered JSX passed to islands |
|
||||
|
||||
## Not serializable
|
||||
|
||||
The following **cannot** be passed as island props:
|
||||
|
||||
- **Functions and closures** - there is no way to transfer executable code
|
||||
- **Class instances** - only plain objects are supported (no custom prototypes)
|
||||
- **Symbols** - not representable in JSON
|
||||
- **WeakMap / WeakSet** - cannot be enumerated
|
||||
- **Streams, Promises** - async values cannot be frozen for transfer
|
||||
|
||||
```tsx
|
||||
// WRONG - functions cannot be serialized
|
||||
<MyIsland onClick={() => console.log("clicked")} />
|
||||
|
||||
// WRONG - class instance loses its prototype
|
||||
<MyIsland data={new MyCustomClass()} />
|
||||
```
|
||||
|
||||
## Circular references
|
||||
|
||||
Fresh handles circular references automatically. If the same object or signal
|
||||
appears multiple times in the props tree, it is serialized once and all
|
||||
references are restored on the client:
|
||||
|
||||
```tsx
|
||||
const shared = { value: 42 };
|
||||
const data = { a: shared, b: shared };
|
||||
|
||||
// `data.a` and `data.b` will reference the same object on the client
|
||||
<MyIsland data={data} />;
|
||||
```
|
||||
|
||||
## How signals are serialized
|
||||
|
||||
When a `Signal` is detected in island props:
|
||||
|
||||
1. **Server**: the signal's current value is read via `.peek()` and serialized
|
||||
2. **Client**: the value is wrapped in a new `signal()` call, creating a live
|
||||
reactive signal
|
||||
|
||||
If the same signal object is passed to multiple islands, it is serialized once
|
||||
and all islands receive the same signal instance on the client - keeping them
|
||||
synchronized.
|
||||
|
||||
Computed signals are serialized by reading their current value and wrapping it
|
||||
in `computed(() => value)` on the client. Since the original computation
|
||||
function cannot be transferred, the client-side computed signal holds a static
|
||||
value.
|
||||
|
||||
## Common pitfalls
|
||||
|
||||
### Accidentally passing non-serializable props
|
||||
|
||||
If you pass a function or class instance as a prop to an island, you'll get a
|
||||
runtime error during serialization. Keep island props to plain data:
|
||||
|
||||
```tsx
|
||||
// Instead of passing a callback...
|
||||
<MyIsland onSave={handleSave} />
|
||||
|
||||
// ...pass data and handle events inside the island
|
||||
<MyIsland itemId={item.id} />
|
||||
```
|
||||
|
||||
### Large props
|
||||
|
||||
Every byte of serialized props is embedded in the HTML and parsed on the client.
|
||||
Keep island props small - pass IDs or minimal data, and fetch the rest
|
||||
client-side if needed.
|
||||
@@ -12,8 +12,7 @@ The Node compatibility layer in Deno is constantly receiving new improvements
|
||||
and bug fixes with every Deno version. Chances are that the issue you're running
|
||||
into has already been fixed. To rule that out, install the latest Deno version.
|
||||
|
||||
```sh
|
||||
# Install latest Deno version
|
||||
```sh Terminal
|
||||
deno upgrade
|
||||
```
|
||||
|
||||
@@ -22,7 +21,7 @@ deno upgrade
|
||||
When run for the first time, you might see Deno complaining about missing
|
||||
packages. Install them with:
|
||||
|
||||
```shell
|
||||
```sh Terminal
|
||||
deno install --allow-scripts
|
||||
```
|
||||
|
||||
@@ -41,7 +40,7 @@ already been resolved in the latest version of Fresh.
|
||||
|
||||
Fresh 1.x heavily relied on [esm.sh](https://esm.sh/) to be able to use npm
|
||||
packages with Fresh. This continued a bit through the early alpha versions of
|
||||
Fresh 2. With the move to [`vite`](https://vite.dev/) this is not necessary
|
||||
Fresh 2. With the move to [`vite`](/docs/advanced/vite) this is not necessary
|
||||
anymore and you should use the relevant npm package directly from npm.
|
||||
|
||||
```diff deno.json
|
||||
@@ -55,7 +54,7 @@ anymore and you should use the relevant npm package directly from npm.
|
||||
|
||||
> [info]: Not using `esm.sh` solves many issues and footguns with duplicate
|
||||
> Preact versions in your app. If you're seeing strange JavaScript errors in the
|
||||
> browser in your app than this is likely the cause.
|
||||
> browser in your app then this is likely the cause.
|
||||
|
||||
## Attach a debugger
|
||||
|
||||
|
||||
@@ -1,12 +1,19 @@
|
||||
---
|
||||
description: |
|
||||
Configure the fresh vite plugin.
|
||||
Configure the Fresh Vite plugin, add other Vite plugins, and understand how Fresh integrates with Vite.
|
||||
---
|
||||
|
||||
The Fresh vite plugin can be optionally configured in the following ways:
|
||||
Fresh 2 uses [Vite](https://vite.dev/) for development and production builds.
|
||||
The Fresh Vite plugin handles JSX configuration, Hot Module Replacement (HMR),
|
||||
[island](/docs/concepts/islands) discovery, client/server code splitting, and
|
||||
React-to-Preact aliasing.
|
||||
|
||||
## Configuration
|
||||
|
||||
The Fresh Vite plugin can be configured in `vite.config.ts`:
|
||||
|
||||
```ts vite.config.ts
|
||||
import { defineConfig, type Plugin } from "vite";
|
||||
import { defineConfig } from "vite";
|
||||
import { fresh } from "@fresh/plugin-vite";
|
||||
|
||||
export default defineConfig({
|
||||
@@ -30,3 +37,70 @@ export default defineConfig({
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Adding other Vite plugins
|
||||
|
||||
You can use any Vite-compatible plugin alongside Fresh. The Fresh plugin should
|
||||
generally come first:
|
||||
|
||||
```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 any other Vite plugins here
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## What the plugin does
|
||||
|
||||
Behind the scenes, the Fresh Vite plugin:
|
||||
|
||||
- **Configures JSX** for Preact automatically (`jsxImportSource: "preact"`)
|
||||
- **Aliases React to Preact** so npm packages that depend on React work out of
|
||||
the box
|
||||
- **Enables HMR** via [Prefresh](https://github.com/preactjs/prefresh) for fast
|
||||
component reloading during development
|
||||
- **Discovers islands** by scanning the islands directory and any
|
||||
`islandSpecifiers`
|
||||
- **Builds separate client and server bundles** using Vite's Environments
|
||||
feature
|
||||
- **Generates a server entry** (`_fresh/server.js`) for production deployment
|
||||
- **Validates imports** to catch mistakes like importing Node.js-only modules in
|
||||
browser code
|
||||
|
||||
## Hot Module Replacement
|
||||
|
||||
During development (`deno task dev`), the Fresh Vite plugin enables HMR so that
|
||||
changes to components, islands, and CSS are reflected in the browser instantly
|
||||
without a full page reload. This is powered by Prefresh, Preact's fast refresh
|
||||
implementation.
|
||||
|
||||
## Debugging
|
||||
|
||||
To debug Vite resolution issues, run Vite with the `--debug` flag:
|
||||
|
||||
```sh Terminal
|
||||
deno run -A npm:vite --debug
|
||||
```
|
||||
|
||||
To inspect plugin transformations, use
|
||||
[`vite-plugin-inspect`](https://github.com/antfu-collective/vite-plugin-inspect):
|
||||
|
||||
```ts vite.config.ts
|
||||
import { defineConfig } from "vite";
|
||||
import { fresh } from "@fresh/plugin-vite";
|
||||
import inspect from "vite-plugin-inspect";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
fresh(),
|
||||
inspect(), // Opens a UI at /__inspect to view all transformations
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
+70
-16
@@ -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"`
|
||||
|
||||
@@ -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">↓</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">↓</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‑circuit with a Response</div>
|
||||
</div>
|
||||
<div class="flow-arrow">↓</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">↓</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‑specific logic.</div>
|
||||
</div>
|
||||
<div class="flow-arrow">↓</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">↓</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 <html>/<head>/<body> structure</div>
|
||||
</div>
|
||||
<div class="flow-arrow">↓</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">↓</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">↓</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‑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">↓</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‑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.
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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) |
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
|
||||
@@ -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
@@ -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>© 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.
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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).
|
||||
@@ -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
|
||||
|
||||
@@ -90,4 +90,13 @@ convention, and require the `-A` flag. Snapshot tests are stored in
|
||||
`__snapshots__/` directories.
|
||||
|
||||
Some tests may fail locally but pass in CI (`Could not find server address`,
|
||||
`Text file busy (os error 26)`) — these can be safely ignored.
|
||||
`Text file busy (os error 26)`) - these can be safely ignored.
|
||||
|
||||
## Pull Requests
|
||||
|
||||
- Run `deno task ok` before submitting to catch formatting, lint, and type
|
||||
errors early
|
||||
- Keep PRs focused - one feature or fix per PR
|
||||
- Add or update tests for any behavior changes
|
||||
- Follow existing code style - the repository uses `deno fmt` for formatting and
|
||||
`deno lint` for linting
|
||||
|
||||
@@ -5,7 +5,8 @@ description: "Deploy Fresh on Cloudflare Workers"
|
||||
Deploy Fresh to Cloudflare Workers by following these instructions:
|
||||
|
||||
1. Run `deno install --allow-scripts npm:@cloudflare/vite-plugin npm:wrangler`
|
||||
2. Add the cloudflare plugin in your vite configuration file:
|
||||
2. Add the cloudflare plugin in your [vite](/docs/advanced/vite) configuration
|
||||
file:
|
||||
|
||||
```diff vite.config.ts
|
||||
import { defineConfig } from "vite";
|
||||
@@ -36,5 +37,5 @@ Check out the
|
||||
[Cloudflare Documentation](https://developers.cloudflare.com/workers/vite-plugin/)
|
||||
for further information.
|
||||
|
||||
> [info]: Make sure that you set the the correct entrypoint in your
|
||||
> `wrangler.jsonc` file. It should point to `"main": "./server.js"`
|
||||
> [info]: Make sure that you set the correct entrypoint in your `wrangler.jsonc`
|
||||
> file. It should point to `"main": "./server.js"`
|
||||
|
||||
@@ -7,14 +7,41 @@ You can create a self-contained executable out of your app with the
|
||||
It will include all assets and dependencies. This executable can run on any
|
||||
platform without requiring Deno to be installed.
|
||||
|
||||
```sh
|
||||
## Building the executable
|
||||
|
||||
```sh Terminal
|
||||
# Build your app first
|
||||
$ deno task build
|
||||
deno task build
|
||||
# Generate self-contained executable
|
||||
deno compile --output my-app --include _fresh -A _fresh/compiled-entry.js
|
||||
```
|
||||
|
||||
The `--include _fresh` flag ensures that all built assets (JavaScript bundles,
|
||||
CSS, static files) are embedded in the binary.
|
||||
|
||||
## Configuration
|
||||
|
||||
The compiled entry supports two environment variables out of the box:
|
||||
|
||||
- `PORT` to set the port number (`PORT=4000 my-app`)
|
||||
- `HOSTNAME` to set the host name number (`HOSTNAME=0.0.0.0 my-app`)
|
||||
- `PORT` to set the port number (`PORT=4000 ./my-app`)
|
||||
- `HOSTNAME` to set the host name (`HOSTNAME=0.0.0.0 ./my-app`)
|
||||
|
||||
## Cross-compilation
|
||||
|
||||
You can compile for a different platform using the `--target` flag:
|
||||
|
||||
```sh Terminal
|
||||
deno compile --target x86_64-unknown-linux-gnu --output my-app --include _fresh -A _fresh/compiled-entry.js
|
||||
```
|
||||
|
||||
See the
|
||||
[`deno compile` documentation](https://docs.deno.com/runtime/reference/cli/compile/)
|
||||
for a full list of supported targets.
|
||||
|
||||
## Limitations
|
||||
|
||||
- The executable size includes the Deno runtime (~50-130 MB depending on
|
||||
platform)
|
||||
- Dynamic imports that aren't statically analyzable may not be included
|
||||
- Native npm packages with platform-specific binaries need to match the target
|
||||
platform
|
||||
|
||||
@@ -4,8 +4,10 @@ description: "Deploy Fresh on Deno Deploy"
|
||||
|
||||
The recommended way to deploy Fresh is by using
|
||||
[Deno Deploy](https://deno.com/deploy). It will automatically create branch
|
||||
previews for pull requests, collect request and HTTP metrics, as well has
|
||||
collect traces for you out of the box.
|
||||
previews for pull requests, collect request and HTTP metrics, as well as collect
|
||||
[traces](/docs/advanced/opentelemetry) for you out of the box.
|
||||
|
||||
## Setup
|
||||
|
||||
1. Log in to [Deno Deploy](https://deno.com/deploy)
|
||||
1. Create a new app
|
||||
@@ -14,3 +16,46 @@ collect traces for you out of the box.
|
||||
|
||||
Every time you merge into the `main` branch a new production deployment will be
|
||||
created.
|
||||
|
||||
## Build step
|
||||
|
||||
Deno Deploy runs `deno task build` automatically during deployment when the
|
||||
Fresh preset is selected. Make sure your `deno.json` has the correct build task:
|
||||
|
||||
```json deno.json
|
||||
{
|
||||
"tasks": {
|
||||
"build": "vite build",
|
||||
"start": "deno serve -A _fresh/server.js"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Environment variables
|
||||
|
||||
You can set environment variables in the Deno Deploy dashboard under your
|
||||
project's **Settings > Environment Variables** section. These are available at
|
||||
runtime via `Deno.env.get()`.
|
||||
|
||||
For variables that need to be available in [island](/docs/concepts/islands) code
|
||||
(client-side), prefix them with `FRESH_PUBLIC_` - see
|
||||
[Environment Variables](/docs/advanced/environment-variables).
|
||||
|
||||
## Custom domains
|
||||
|
||||
Custom domains can be configured in the Deno Deploy dashboard under your
|
||||
project's **Settings > Domains** section. Deno Deploy automatically provisions
|
||||
TLS certificates for your domains.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
If your deployment fails to start:
|
||||
|
||||
1. Ensure `deno task build` has been run (check that the Fresh preset is
|
||||
selected)
|
||||
2. Verify your entry point is `_fresh/server.js`, not `main.ts` - Fresh 2
|
||||
generates the server entry during the build step
|
||||
3. Check the deployment logs in the Deno Deploy dashboard for specific errors
|
||||
|
||||
See the [Deno Deploy documentation](https://docs.deno.com/deploy/manual/) for
|
||||
more details.
|
||||
|
||||
@@ -6,12 +6,14 @@ You can deploy Fresh to any platform that can run Docker containers. Docker is a
|
||||
tool to containerize projects and portably run them on any supported platform.
|
||||
|
||||
When packaging your Fresh app for Docker, it is important that you set the
|
||||
`DENO_DEPLOYMENT_ID` environment variable in your container. This variable needs
|
||||
to be set to an opaque string ID that represents the version of your application
|
||||
that is currently being run. This could be a Git commit hash, or a hash of all
|
||||
files in your project. It is critical for the function of Fresh that this ID
|
||||
changes when _any_ file in your project changes - if it doesn't, incorrect
|
||||
caching **will** cause your project to not function correctly.
|
||||
`DENO_DEPLOYMENT_ID`
|
||||
[environment variable](/docs/advanced/environment-variables) in your container.
|
||||
This variable needs to be set to an opaque string ID that represents the version
|
||||
of your application that is currently being run. This could be a Git commit
|
||||
hash, or a hash of all files in your project. It is critical for the function of
|
||||
Fresh that this ID changes when _any_ file in your project changes - if it
|
||||
doesn't, incorrect caching **will** cause your project to not function
|
||||
correctly.
|
||||
|
||||
Here is an example `Dockerfile` for a Fresh project:
|
||||
|
||||
@@ -24,14 +26,18 @@ ENV DENO_DEPLOYMENT_ID=${GIT_REVISION}
|
||||
WORKDIR /app
|
||||
|
||||
COPY . .
|
||||
RUN deno install --allow-scripts
|
||||
RUN deno task build
|
||||
RUN deno cache _fresh/server.js
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["serve", "-A", "_fresh/server.js"]
|
||||
CMD ["deno", "serve", "-A", "_fresh/server.js"]
|
||||
```
|
||||
|
||||
> [info]: The `deno install --allow-scripts` step is required to populate
|
||||
> `node_modules` and run any post-install scripts needed by npm packages (e.g.
|
||||
> Tailwind CSS). This must happen before `deno task build`.
|
||||
|
||||
To build your Docker image inside of a Git repository:
|
||||
|
||||
```sh Terminal
|
||||
|
||||
@@ -3,14 +3,23 @@ description: "Create a production build of your app"
|
||||
---
|
||||
|
||||
When shipping an app to production, we can run a build step that optimizes
|
||||
assets for consumption in the browser. This step can be invoked by running:
|
||||
assets for consumption in the browser. First, make sure dependencies are
|
||||
installed:
|
||||
|
||||
```sh Terminal
|
||||
deno install --allow-scripts
|
||||
```
|
||||
|
||||
Then run the build:
|
||||
|
||||
```sh Terminal
|
||||
deno task build
|
||||
# or
|
||||
deno run -A dev.ts build
|
||||
```
|
||||
|
||||
> [info]: This runs [vite](/docs/advanced/vite) build under the hood. If you're
|
||||
> migrating from Fresh 1.x and still have a `dev.ts` file, see the
|
||||
> [migration guide](/docs/migration-guide) for updating your tasks.
|
||||
|
||||
Once completed, it will have created a `_fresh` folder in the project directory
|
||||
which contains the optimized assets.
|
||||
|
||||
@@ -28,8 +37,8 @@ To run Fresh in production mode, run the `start` task:
|
||||
|
||||
```sh Terminal
|
||||
deno task start
|
||||
# or
|
||||
deno serve -A _fresh/server.js
|
||||
```
|
||||
|
||||
Fresh will automatically pick up the optimized assets in the `_fresh` directory.
|
||||
This runs `deno serve -A _fresh/server.js`, which serves the built assets
|
||||
directly. Fresh will automatically pick up the optimized assets in the `_fresh`
|
||||
directory.
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
```
|
||||
@@ -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;
|
||||
});
|
||||
```
|
||||
@@ -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)
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -9,7 +9,7 @@ Let's set up your first Fresh project. To create a new project, run this
|
||||
command:
|
||||
|
||||
```sh Terminal
|
||||
deno run -Ar jsr:@fresh/init
|
||||
deno create @fresh/init
|
||||
```
|
||||
|
||||
This will spawn a short wizard that guides you through the setup, like the
|
||||
@@ -22,10 +22,10 @@ project folder should look like this:
|
||||
│ └── Button.tsx
|
||||
├── islands/ # Components that need JS to run client-side
|
||||
│ └── Counter.tsx
|
||||
├── routes/ # File system based routes
|
||||
├── routes/ # [File system based routes](/docs/concepts/file-routing)
|
||||
│ ├── api/
|
||||
│ │ └── [name].tsx # API route for /api/:name
|
||||
│ ├── _app.tsx # Renders the outer <html> content structure
|
||||
│ ├── [_app.tsx](/docs/concepts/app) # Renders the outer <html> content structure
|
||||
│ └── index.tsx # Renders /
|
||||
├── static/ # Contains static assets like css, logos, etc
|
||||
│ └── ...
|
||||
@@ -33,7 +33,7 @@ project folder should look like this:
|
||||
├── client.ts # Client entry file that's loaded on every page.
|
||||
├── main.ts # The server entry file of your app
|
||||
├── deno.json # Contains dependencies, tasks, etc
|
||||
└── vite.config.ts # Vite configuration file
|
||||
└── [vite.config.ts](/docs/advanced/vite) # Vite configuration file
|
||||
```
|
||||
|
||||
## Path aliases
|
||||
@@ -113,7 +113,7 @@ Create a new file at `islands/Countdown.tsx`
|
||||
import { useSignal } from "@preact/signals";
|
||||
import { useEffect } from "preact/hooks";
|
||||
|
||||
export function Countdown(props: { target: string }) {
|
||||
export function Countdown() {
|
||||
const count = useSignal(10);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -155,4 +155,19 @@ export default define.page(() => {
|
||||
|
||||
Now, we can see our countdown in action:
|
||||
|
||||

|
||||

|
||||
|
||||
## Next steps
|
||||
|
||||
Now that you have a working Fresh project, here are some things to explore:
|
||||
|
||||
- [**Routing**](/docs/concepts/routing) - Learn about route patterns, dynamic
|
||||
parameters, and method-specific handlers
|
||||
- [**Data Fetching**](/docs/concepts/data-fetching) - Load data on the server
|
||||
and pass it to page components
|
||||
- [**Islands**](/docs/concepts/islands) - Understand how Fresh's partial
|
||||
hydration works and what can be passed as props
|
||||
- [**Middleware**](/docs/concepts/middleware) - Add authentication, logging, or
|
||||
custom headers to your routes
|
||||
- [**Architecture**](/docs/concepts/architecture) - See how requests flow
|
||||
through the entire framework
|
||||
|
||||
@@ -24,7 +24,7 @@ app.listen();
|
||||
Create a new Fresh app by running:
|
||||
|
||||
```sh Terminal
|
||||
deno run -Ar jsr:@fresh/init
|
||||
deno create @fresh/init
|
||||
```
|
||||
|
||||
## Features
|
||||
@@ -39,7 +39,8 @@ referred to as the
|
||||
- **Lightweight** 🏎️ - Only ship the JavaScript you need
|
||||
- **Extensible** 🧩 - Nearly every aspect can be customized
|
||||
- **Powerful & small API** 🤗 - Familiar APIs make you productive quickly
|
||||
- **Built-in OpenTelemetry** 📈 - Built-in support for OpenTelemetry
|
||||
- **Built-in [OpenTelemetry](/docs/advanced/opentelemetry)** 📈 - Built-in
|
||||
support for OpenTelemetry
|
||||
|
||||
## When to use Fresh
|
||||
|
||||
@@ -52,6 +53,12 @@ home page, an e-commerce shop or something like GitHub or Bluesky.
|
||||
- Landing pages & Documentation
|
||||
- CRUD apps
|
||||
|
||||
Fresh's small API surface and
|
||||
[file-based conventions](/docs/concepts/file-routing) also make it a great fit
|
||||
for AI-assisted development. Agents can scaffold routes, add
|
||||
[middleware](/docs/concepts/middleware), and build features with minimal context
|
||||
because the framework is simple and predictable.
|
||||
|
||||
That said, if you want to build a Single-Page-App (=SPA), then Fresh is not the
|
||||
right framework.
|
||||
|
||||
@@ -61,14 +68,11 @@ Fresh powers [deno.com](https://deno.com) and [Deno Deploy][deno-deploy] among
|
||||
many other projects at Deno. It's also used by [deco.cx](https://deco.cx/) for
|
||||
e-commerce projects.
|
||||
|
||||
## Where to host Fresh apps?
|
||||
## Hosting
|
||||
|
||||
Fresh is most often deployed on [Deno Deploy][deno-deploy] where it can be
|
||||
deployed with 1-click and has out of the box integrations with metrics among
|
||||
other things.
|
||||
|
||||
Fresh projects can be deployed manually to any platform with [Deno][deno] like
|
||||
via docker containers too.
|
||||
Fresh runs anywhere [Deno][deno] runs. Deploy with a single click on
|
||||
[Deno Deploy][deno-deploy], or package your app in a Docker container for any
|
||||
cloud provider or self-hosted infrastructure.
|
||||
|
||||
[preact]: https://preactjs.com
|
||||
[deno]: https://deno.com
|
||||
|
||||
@@ -20,8 +20,8 @@ update by running it in your project directory:
|
||||
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`.
|
||||
This will apply most API changes made in Fresh 2 automatically, like changing
|
||||
`$fresh/server.ts` imports to `fresh`.
|
||||
|
||||
## Getting `main.ts` and `dev.ts` ready
|
||||
|
||||
@@ -98,7 +98,8 @@ export const app = new App()
|
||||
## Merging error pages
|
||||
|
||||
Both the `_500.tsx` and `_404.tsx` template have been unified into a single
|
||||
`_error.tsx` template.
|
||||
`_error.tsx` template. See [error pages](/docs/advanced/error-handling) for
|
||||
details.
|
||||
|
||||
```diff Project structure
|
||||
└── <root>/routes/
|
||||
@@ -203,9 +204,9 @@ have a trailing slash at the end or that they will never have one.
|
||||
|
||||
### 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`.
|
||||
[Middleware](/docs/concepts/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");
|
||||
@@ -292,7 +293,7 @@ To render JSX in general, use the `ctx.render()` function:
|
||||
|
||||
```tsx
|
||||
const app = new App()
|
||||
.get("/", () => ctx.render(<h1>hello</h1>));
|
||||
.get("/", (ctx) => ctx.render(<h1>hello</h1>));
|
||||
```
|
||||
|
||||
## `createHandler`
|
||||
@@ -313,7 +314,7 @@ to [update the command](/docs/deployment/deno-compile) to generate the binary.
|
||||
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`
|
||||
eg. `mkdir fresh2-demo && cd fresh2-demo && deno create @fresh/init`
|
||||
|
||||
### 2. Document
|
||||
|
||||
@@ -2,19 +2,17 @@
|
||||
description: "Prevent Cross-Site Request Forgery with this middleware"
|
||||
---
|
||||
|
||||
The `csrf()` middleware can be used to add safeguard against
|
||||
The `csrf()` middleware can be used to safeguard against
|
||||
[Cross-Site Request Forgery vulnerabilities](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/CSRF).
|
||||
It checks if the user is allowed to load the requested URL based on the values
|
||||
in the
|
||||
It verifies that state-changing requests (POST, PUT, DELETE, etc.) originate
|
||||
from your own site by checking the
|
||||
[`Sec-Fetch-Site`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Sec-Fetch-Site)
|
||||
header and
|
||||
and
|
||||
[`Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Origin)
|
||||
header. to HTTP requests. These allow the server to indicate which origins
|
||||
(domains, scheme or port) other than its own is permitted to load resources
|
||||
from.
|
||||
headers. Requests from untrusted origins are rejected.
|
||||
|
||||
```ts main.ts
|
||||
import { app, csrf } from "fresh";
|
||||
import { App, csrf } from "fresh";
|
||||
|
||||
const app = new App();
|
||||
|
||||
|
||||
@@ -9,8 +9,8 @@ features in Fresh itself are built using these APIs.
|
||||
## Custom middlewares
|
||||
|
||||
If you need to modify requests, add HTTP headers or pass additional data to
|
||||
other middlewares via `ctx.state`, then going with a middleware is the way to
|
||||
go.
|
||||
other [middlewares](/docs/concepts/middleware) via `ctx.state`, then going with
|
||||
a middleware is the way to go.
|
||||
|
||||
```ts middleware/fresh.ts
|
||||
const addXFreshHeader = define.middleware(async (ctx) => {
|
||||
@@ -22,4 +22,43 @@ const addXFreshHeader = define.middleware(async (ctx) => {
|
||||
|
||||
Learn more about [middlewares](/docs/concepts/middleware).
|
||||
|
||||
TODO: Show more ways
|
||||
## Creating reusable plugins
|
||||
|
||||
Since Fresh plugins are just middlewares and route handlers, creating a reusable
|
||||
plugin is as simple as exporting a function that returns a middleware:
|
||||
|
||||
```ts plugins/request-id.ts
|
||||
import type { MiddlewareFn } from "fresh";
|
||||
|
||||
export function requestId(): MiddlewareFn<{ requestId: string }> {
|
||||
return async (ctx) => {
|
||||
ctx.state.requestId = crypto.randomUUID();
|
||||
const res = await ctx.next();
|
||||
res.headers.set("X-Request-Id", ctx.state.requestId);
|
||||
return res;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
```ts main.ts
|
||||
import { App, staticFiles } from "fresh";
|
||||
import { requestId } from "./plugins/request-id.ts";
|
||||
|
||||
const app = new App()
|
||||
.use(staticFiles())
|
||||
.use(requestId())
|
||||
.fsRoutes();
|
||||
```
|
||||
|
||||
For more complex plugins, you can combine multiple middlewares, add routes, or
|
||||
use the [`Builder`](/docs/advanced/builder) hooks for build-time processing.
|
||||
|
||||
## Built-in plugins
|
||||
|
||||
Fresh ships with the following plugins:
|
||||
|
||||
- [cors()](/docs/plugins/cors) - Set CORS HTTP headers
|
||||
- [csrf()](/docs/plugins/csrf) - CSRF protection
|
||||
- [csp()](/docs/plugins/csp) - Content Security Policy headers
|
||||
- [trailingSlashes()](/docs/plugins/trailing-slashes) - Enforce trailing slash
|
||||
behavior
|
||||
|
||||
+16
-7
@@ -33,15 +33,16 @@ const toc: RawTableOfContents = {
|
||||
title: "Concepts",
|
||||
link: "latest",
|
||||
pages: [
|
||||
["architecture", "Architecture", "link:latest"],
|
||||
["islands", "Islands", "link:latest"],
|
||||
["app", "App", "link:latest"],
|
||||
["routing", "Routing", "link:latest"],
|
||||
["data-fetching", "Data Fetching", "link:latest"],
|
||||
["middleware", "Middlewares", "link:latest"],
|
||||
["context", "Context", "link:latest"],
|
||||
|
||||
["routing", "Routing", "link:latest"],
|
||||
|
||||
["islands", "Islands", "link:latest"],
|
||||
["signals", "Signals", "link:latest"],
|
||||
["layouts", "Layouts", "link:latest"],
|
||||
["static-files", "Static files", "link:latest"],
|
||||
|
||||
["file-routing", "File routing", "link:latest"],
|
||||
],
|
||||
},
|
||||
@@ -55,9 +56,12 @@ const toc: RawTableOfContents = {
|
||||
["partials", "Partials", "link:latest"],
|
||||
["forms", "Forms", "link:latest"],
|
||||
["define", "Define Helpers", "link:latest"],
|
||||
["serialization", "Serialization", "link:latest"],
|
||||
["environment-variables", "Environment Variables", "link:latest"],
|
||||
["head", "Modifying <head>", "link:latest"],
|
||||
["head", "<head> element", "link:latest"],
|
||||
["vite", "Vite Plugin Options", "link:latest"],
|
||||
["opentelemetry", "OpenTelemetry", "link:latest"],
|
||||
["api-reference", "API Reference", "link:latest"],
|
||||
["troubleshooting", "Troubleshooting", "link:latest"],
|
||||
["builder", "Builder (Legacy)", "link:latest"],
|
||||
],
|
||||
@@ -90,7 +94,7 @@ const toc: RawTableOfContents = {
|
||||
title: "Examples",
|
||||
link: "latest",
|
||||
pages: [
|
||||
["migration-guide", "Migration Guide", "link:latest"],
|
||||
["api-routes", "API Routes", "link:latest"],
|
||||
["daisyui", "daisyUI", "link:latest"],
|
||||
["markdown", "Rendering Markdown", "link:latest"],
|
||||
["rendering-raw-html", "Rendering raw HTML", "link:latest"],
|
||||
@@ -101,8 +105,13 @@ const toc: RawTableOfContents = {
|
||||
],
|
||||
["active-links", "Active links", "link:latest"],
|
||||
["session-management", "Session management", "link:latest"],
|
||||
["common-patterns", "Common Patterns", "link:latest"],
|
||||
],
|
||||
},
|
||||
"migration-guide": {
|
||||
title: "Migration Guide",
|
||||
link: "latest",
|
||||
},
|
||||
contributing: {
|
||||
title: "Contributing",
|
||||
link: "latest",
|
||||
|
||||
@@ -11,7 +11,7 @@ web applications.
|
||||
Generate a new Fresh project with `@fresh/init`:
|
||||
|
||||
```sh
|
||||
deno run -Ar jsr:@fresh/init
|
||||
deno create @fresh/init
|
||||
```
|
||||
|
||||
Add middleware, routes, & endpoints as needed via the `routes/` folder or
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
This is a CLI tool to bootstrap a new Fresh project. To do so, run this command:
|
||||
|
||||
```sh
|
||||
deno run -Ar jsr:@fresh/init
|
||||
deno create @fresh/init
|
||||
```
|
||||
|
||||
Go to [https://fresh.deno.dev/](https://fresh.deno.dev/) for more information
|
||||
|
||||
@@ -48,13 +48,13 @@ Initialize a new Fresh project. This will create all the necessary files
|
||||
for a new project.
|
||||
|
||||
To generate a project in the './foobar' subdirectory:
|
||||
${colors.rgb8("deno run -Ar jsr:@fresh/init ./foobar", 245)}
|
||||
${colors.rgb8("deno create @fresh/init ./foobar", 245)}
|
||||
|
||||
To generate a project in the current directory:
|
||||
${colors.rgb8("deno run -Ar jsr:@fresh/init .", 245)}
|
||||
${colors.rgb8("deno create @fresh/init .", 245)}
|
||||
|
||||
${colors.rgb8("USAGE:", 3)}
|
||||
${colors.rgb8("deno run -Ar jsr:@fresh/init [DIRECTORY]", 245)}
|
||||
${colors.rgb8("deno create @fresh/init [DIRECTORY]", 245)}
|
||||
|
||||
${colors.rgb8("OPTIONS:", 3)}
|
||||
${colors.rgb8("--force", 2)} Overwrite existing files
|
||||
|
||||
@@ -24,6 +24,7 @@ const EXCLUDED_PREFIXES = [
|
||||
"javascript:",
|
||||
"vscode:",
|
||||
"data:",
|
||||
"https://github.com/denoland/fresh/edit/",
|
||||
];
|
||||
|
||||
interface FailedLink {
|
||||
@@ -164,7 +165,7 @@ async function crawlPage(pageUrl: URL, referrer: string) {
|
||||
const urlStr = nextUrl.href;
|
||||
|
||||
if (nextUrl.origin === rootUrl.origin) {
|
||||
// Internal link — crawl the page if it's a docs page
|
||||
// Internal link -- crawl the page if it's a docs page
|
||||
if (
|
||||
!visitedPages.has(nextUrl.pathname) &&
|
||||
nextUrl.pathname.startsWith("/docs")
|
||||
@@ -177,7 +178,7 @@ async function crawlPage(pageUrl: URL, referrer: string) {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// External link — verify it's live
|
||||
// External link -- verify it's live
|
||||
if (!checkedUrls.has(urlStr)) {
|
||||
linkChecks.push(checkUrl(urlStr, pathname).then(() => {}));
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ export function Hero() {
|
||||
</h2>
|
||||
<div class="mt-12 flex flex-wrap justify-center items-stretch md:justify-start gap-4">
|
||||
<FancyLink href="/docs/getting-started">Get started</FancyLink>
|
||||
<CopyArea code={`deno run -Ar jsr:@fresh/init`} />
|
||||
<CopyArea code={`deno create @fresh/init`} />
|
||||
</div>
|
||||
</div>
|
||||
<div class="md:col-span-2 flex justify-center items-end">
|
||||
|
||||
@@ -33,7 +33,7 @@ export const Recipes = () => (
|
||||
|
||||
export function PartialsSection() {
|
||||
return (
|
||||
<PageSection>
|
||||
<PageSection id="partials">
|
||||
<SideBySide
|
||||
mdColSplit="3/2"
|
||||
lgColSplit="3/2"
|
||||
@@ -67,7 +67,7 @@ export function PartialsSection() {
|
||||
<SectionHeading>Stream HTML straight from the server</SectionHeading>
|
||||
<p>
|
||||
Fresh Partials let you fetch HTML and slot it directly into the
|
||||
page, without a full page reload—perfect for interactive elements
|
||||
page, without a full page reload - perfect for interactive elements
|
||||
and dynamic apps.
|
||||
</p>
|
||||
<FancyLink href="/docs/advanced/partials" class="mt-4">
|
||||
|
||||
@@ -1,5 +1,31 @@
|
||||
import { PageSection } from "../../components/PageSection.tsx";
|
||||
|
||||
const ONE_FILE_EXAMPLE = `import { App } from "fresh";
|
||||
|
||||
const app = new App()
|
||||
.get("/", () => new Response("Hello, World!"));
|
||||
|
||||
app.listen();`;
|
||||
|
||||
const ADD_JSX_EXAMPLE = `import { App } from "fresh";
|
||||
|
||||
const app = new App()
|
||||
.get("/", (ctx) => ctx.render(<h1>Hello!</h1>));
|
||||
|
||||
app.listen();`;
|
||||
|
||||
const ADD_ISLAND_EXAMPLE = `// islands/Counter.tsx
|
||||
import { useSignal } from "@preact/signals";
|
||||
|
||||
export function Counter() {
|
||||
const count = useSignal(0);
|
||||
return (
|
||||
<button onClick={() => count.value++}>
|
||||
Count: {count}
|
||||
</button>
|
||||
);
|
||||
}`;
|
||||
|
||||
export function Simple() {
|
||||
return (
|
||||
<PageSection class="!mb-12 !mt-20">
|
||||
@@ -13,6 +39,46 @@ export function Simple() {
|
||||
tools, conventions, and web standards.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="grid md:grid-cols-3 gap-6 mt-8">
|
||||
<StepCard
|
||||
step="1"
|
||||
title="One file. That's it."
|
||||
description="No config files, no build step, no node_modules. Just one file and you have a server."
|
||||
code={ONE_FILE_EXAMPLE}
|
||||
/>
|
||||
<StepCard
|
||||
step="2"
|
||||
title="Add JSX"
|
||||
description="Render HTML with JSX. Server-side by default, fast by design."
|
||||
code={ADD_JSX_EXAMPLE}
|
||||
/>
|
||||
<StepCard
|
||||
step="3"
|
||||
title="Sprinkle interactivity"
|
||||
description="Add islands for client-side JS only where you need it. Zero JS shipped by default."
|
||||
code={ADD_ISLAND_EXAMPLE}
|
||||
/>
|
||||
</div>
|
||||
</PageSection>
|
||||
);
|
||||
}
|
||||
|
||||
function StepCard(
|
||||
props: { step: string; title: string; description: string; code: string },
|
||||
) {
|
||||
return (
|
||||
<div class="flex flex-col gap-3">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="bg-green-200 text-green-800 text-sm font-bold rounded-full w-7 h-7 flex items-center justify-center">
|
||||
{props.step}
|
||||
</span>
|
||||
<h3 class="font-bold text-lg">{props.title}</h3>
|
||||
</div>
|
||||
<p class="text-gray-600 text-sm">{props.description}</p>
|
||||
<pre class="bg-slate-800 text-green-100 rounded-md p-4 text-sm overflow-x-auto flex-1">
|
||||
<code>{props.code}</code>
|
||||
</pre>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,13 +3,24 @@ import type { Context } from "fresh";
|
||||
const REDIRECTS: Record<string, string> = {
|
||||
"/docs/getting-started/fetching-data":
|
||||
"/docs/getting-started/custom-handlers",
|
||||
"/docs/canary/examples/modifying-the-head": "/docs/advanced/head",
|
||||
"/docs/canary/concepts/builder": "/docs/advanced/builder",
|
||||
};
|
||||
|
||||
export async function handler<T>(ctx: Context<T>) {
|
||||
const { pathname } = ctx.url;
|
||||
|
||||
// Redirect /docs/canary/... to /docs/... since canary docs
|
||||
// have been merged into latest
|
||||
if (pathname.startsWith("/docs/canary/")) {
|
||||
const rest = pathname.slice("/docs/canary".length);
|
||||
const url = new URL(`/docs${rest}`, ctx.url.origin);
|
||||
return new Response("", {
|
||||
status: 301,
|
||||
headers: { location: url.href },
|
||||
});
|
||||
}
|
||||
|
||||
// Redirect from old doc URLs to new ones
|
||||
const redirect = REDIRECTS[ctx.url.pathname];
|
||||
const redirect = REDIRECTS[pathname];
|
||||
if (redirect) {
|
||||
const url = new URL(redirect, ctx.url.origin);
|
||||
return new Response("", {
|
||||
|
||||
@@ -1,12 +1,25 @@
|
||||
import { page } from "fresh";
|
||||
import { Partial } from "fresh/runtime";
|
||||
import type { RouteConfig } from "fresh";
|
||||
import { define } from "../../utils/state.ts";
|
||||
|
||||
export const config: RouteConfig = {
|
||||
export const handler = define.handlers({
|
||||
GET(ctx) {
|
||||
if (!ctx.isPartial) {
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers: { location: "/#partials" },
|
||||
});
|
||||
}
|
||||
return page();
|
||||
},
|
||||
});
|
||||
|
||||
export const config = {
|
||||
skipAppWrapper: true,
|
||||
skipInheritedLayouts: true,
|
||||
};
|
||||
|
||||
export const LemonHoneyTea = () => (
|
||||
export default define.page(() => (
|
||||
<Partial name="recipe">
|
||||
<h2 class="mb-2 font-extrabold">Lemon-honey tea</h2>
|
||||
<ul>
|
||||
@@ -17,6 +30,4 @@ export const LemonHoneyTea = () => (
|
||||
<li>Lemon peel</li>
|
||||
</ul>
|
||||
</Partial>
|
||||
);
|
||||
|
||||
export default LemonHoneyTea;
|
||||
));
|
||||
|
||||
@@ -1,12 +1,25 @@
|
||||
import { page } from "fresh";
|
||||
import { Partial } from "fresh/runtime";
|
||||
import type { RouteConfig } from "fresh";
|
||||
import { define } from "../../utils/state.ts";
|
||||
|
||||
export const config: RouteConfig = {
|
||||
export const handler = define.handlers({
|
||||
GET(ctx) {
|
||||
if (!ctx.isPartial) {
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers: { location: "/#partials" },
|
||||
});
|
||||
}
|
||||
return page();
|
||||
},
|
||||
});
|
||||
|
||||
export const config = {
|
||||
skipAppWrapper: true,
|
||||
skipInheritedLayouts: true,
|
||||
};
|
||||
|
||||
export const Lemonade = () => (
|
||||
export default define.page(() => (
|
||||
<Partial name="recipe">
|
||||
<h2 class="mb-2 font-extrabold">Lemonade</h2>
|
||||
<ul>
|
||||
@@ -17,6 +30,4 @@ export const Lemonade = () => (
|
||||
<li>Ice</li>
|
||||
</ul>
|
||||
</Partial>
|
||||
);
|
||||
|
||||
export default Lemonade;
|
||||
));
|
||||
|
||||
@@ -1,12 +1,25 @@
|
||||
import { page } from "fresh";
|
||||
import { Partial } from "fresh/runtime";
|
||||
import type { RouteConfig } from "fresh";
|
||||
import { define } from "../../utils/state.ts";
|
||||
|
||||
export const config: RouteConfig = {
|
||||
export const handler = define.handlers({
|
||||
GET(ctx) {
|
||||
if (!ctx.isPartial) {
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers: { location: "/#partials" },
|
||||
});
|
||||
}
|
||||
return page();
|
||||
},
|
||||
});
|
||||
|
||||
export const config = {
|
||||
skipAppWrapper: true,
|
||||
skipInheritedLayouts: true,
|
||||
};
|
||||
|
||||
export const LemonDrop = () => (
|
||||
export default define.page(() => (
|
||||
<Partial name="recipe">
|
||||
<h2 class="mb-2 font-extrabold">Lemondrop Martini</h2>
|
||||
<ul>
|
||||
@@ -18,6 +31,4 @@ export const LemonDrop = () => (
|
||||
<li>3/4 oz simple syrup</li>
|
||||
</ul>
|
||||
</Partial>
|
||||
);
|
||||
|
||||
export default LemonDrop;
|
||||
));
|
||||
|
||||
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.5 KiB |
Reference in New Issue
Block a user