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
@@ -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
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user