From 103427f9da670634467ddddd1bd39900daac0768 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Sun, 29 Mar 2026 18:22:33 +0000 Subject: [PATCH] docs: comprehensive documentation audit, fixes, and website improvements (#3712) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 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) --- AGENTS.md | 2 +- README.md | 2 +- docs/1.x/concepts/partials.md | 2 +- docs/check_images_test.ts | 55 ++++ docs/latest/advanced/api-reference.md | 98 ++++++ docs/latest/advanced/app-wrapper.md | 124 +++++++- docs/latest/advanced/builder.md | 4 +- docs/latest/advanced/define.md | 6 +- docs/latest/advanced/environment-variables.md | 4 +- docs/latest/advanced/error-handling.md | 26 +- docs/latest/advanced/head.md | 16 +- docs/latest/advanced/index.md | 21 ++ docs/latest/advanced/layouts.md | 35 ++- docs/latest/advanced/opentelemetry.md | 129 ++++++++ docs/latest/advanced/serialization.md | 102 ++++++ docs/latest/advanced/troubleshooting.md | 9 +- docs/latest/advanced/vite.md | 80 ++++- docs/latest/concepts/app.md | 86 ++++- docs/latest/concepts/architecture.md | 179 +++++++++++ docs/latest/concepts/context.md | 12 +- docs/latest/concepts/data-fetching.md | 133 ++++++++ docs/latest/concepts/file-routing.md | 20 +- docs/latest/concepts/index.md | 11 +- docs/latest/concepts/islands.md | 81 ++++- docs/latest/concepts/layouts.md | 168 ++++++---- docs/latest/concepts/middleware.md | 10 +- docs/latest/concepts/routing.md | 72 ++++- docs/latest/concepts/signals.md | 138 ++++++++ docs/latest/concepts/static-files.md | 81 ++++- docs/latest/contributing/index.md | 11 +- docs/latest/deployment/cloudflare-workers.md | 7 +- docs/latest/deployment/deno-compile.md | 35 ++- docs/latest/deployment/deno-deploy.md | 49 ++- docs/latest/deployment/docker.md | 22 +- docs/latest/deployment/index.md | 21 +- docs/latest/examples/api-routes.md | 82 +++++ docs/latest/examples/common-patterns.md | 295 ++++++++++++++++++ docs/latest/examples/index.md | 9 +- docs/latest/examples/markdown.md | 9 +- docs/latest/examples/rendering-raw-html.md | 4 +- .../examples/sharing-state-between-islands.md | 110 ++++--- docs/latest/getting-started/index.md | 27 +- docs/latest/introduction/index.md | 22 +- .../index.md} | 17 +- docs/latest/plugins/csrf.md | 14 +- docs/latest/plugins/index.md | 45 ++- docs/toc.ts | 23 +- packages/fresh/README.md | 2 +- packages/init/README.md | 2 +- packages/init/src/init.ts | 6 +- tools/check_links.ts | 5 +- www/components/homepage/Hero.tsx | 2 +- www/components/homepage/PartialsSection.tsx | 4 +- www/components/homepage/Simple.tsx | 66 ++++ www/routes/docs/_middleware.ts | 17 +- www/routes/recipes/lemon-honey-tea.tsx | 23 +- www/routes/recipes/lemonade.tsx | 23 +- www/routes/recipes/lemondrop.tsx | 23 +- ...wn.png => getting-started-3-countdown.png} | Bin 59 files changed, 2386 insertions(+), 295 deletions(-) create mode 100644 docs/check_images_test.ts create mode 100644 docs/latest/advanced/api-reference.md create mode 100644 docs/latest/advanced/opentelemetry.md create mode 100644 docs/latest/advanced/serialization.md create mode 100644 docs/latest/concepts/architecture.md create mode 100644 docs/latest/concepts/data-fetching.md create mode 100644 docs/latest/concepts/signals.md create mode 100644 docs/latest/examples/api-routes.md create mode 100644 docs/latest/examples/common-patterns.md rename docs/latest/{examples/migration-guide.md => migration-guide/index.md} (93%) rename www/static/docs/{getting-started-3-cotuntdown.png => getting-started-3-countdown.png} (100%) diff --git a/AGENTS.md b/AGENTS.md index d718f91c..a88208cc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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. diff --git a/README.md b/README.md index ecee756c..9921eea3 100644 --- a/README.md +++ b/README.md @@ -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: diff --git a/docs/1.x/concepts/partials.md b/docs/1.x/concepts/partials.md index aa8af04a..1b697dcf 100644 --- a/docs/1.x/concepts/partials.md +++ b/docs/1.x/concepts/partials.md @@ -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). -![A sketched layout of a typical documentation page with the sidebar on the left composed of green links and a main content area on the right. The main content area is labeled as Partial docs-content](/docs/1.x/fresh-partial-docs.png) +![A sketched layout of a typical documentation page with the sidebar on the left composed of green links and a main content area on the right. The main content area is labeled as Partial docs-content](/docs/fresh-partial-docs.png) The code for such a page (excluding styling) might look like this: diff --git a/docs/check_images_test.ts b/docs/check_images_test.ts new file mode 100644 index 00000000..e53c2ffa --- /dev/null +++ b/docs/check_images_test.ts @@ -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") + }`, + ); + } +}); diff --git a/docs/latest/advanced/api-reference.md b/docs/latest/advanced/api-reference.md new file mode 100644 index 00000000..ce6a65b9 --- /dev/null +++ b/docs/latest/advanced/api-reference.md @@ -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 ``. See [ 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. | diff --git a/docs/latest/advanced/app-wrapper.md b/docs/latest/advanced/app-wrapper.md index 54baa325..752a31c2 100644 --- a/docs/latest/advanced/app-wrapper.md +++ b/docs/latest/advanced/app-wrapper.md @@ -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 , , and tags. --- -The app wrapper component is a Preact component that represents the outer -structure of the HTML document, typically up until the ``-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 ``, ``, and `` 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 (``) +- Include global `` tags, fonts, or stylesheets +- Add analytics scripts or structured data to every page +- Set a global `` 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 ( + + + + + My App + + + + + + + ); +}); +``` + +## 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 ``/``/`` +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 ( + + + + + My App + + + + + + + + ); +}); +``` + +## 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 ( + + + Embed + + +
Embeddable widget
+ + + ); +}); +``` + +When using programmatic layouts, pass `skipAppWrapper` as an option: + +```ts main.ts +app.layout("/embed", EmbedLayout, { skipAppWrapper: true }); +``` diff --git a/docs/latest/advanced/builder.md b/docs/latest/advanced/builder.md index a4c4d5d7..9d5c75b2 100644 --- a/docs/latest/advanced/builder.md +++ b/docs/latest/advanced/builder.md @@ -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. diff --git a/docs/latest/advanced/define.md b/docs/latest/advanced/define.md index 2015ebfa..afe587ca 100644 --- a/docs/latest/advanced/define.md +++ b/docs/latest/advanced/define.md @@ -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((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) => { diff --git a/docs/latest/advanced/environment-variables.md b/docs/latest/advanced/environment-variables.md index 2d46eeae..b5c527f7 100644 --- a/docs/latest/advanced/environment-variables.md +++ b/docs/latest/advanced/environment-variables.md @@ -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. diff --git a/docs/latest/advanced/error-handling.md b/docs/latest/advanced/error-handling.md index c9af64f6..6056d7fd 100644 --- a/docs/latest/advanced/error-handling.md +++ b/docs/latest/advanced/error-handling.md @@ -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). diff --git a/docs/latest/advanced/head.md b/docs/latest/advanced/head.md index 5ab4dc58..aa4ab667 100644 --- a/docs/latest/advanced/head.md +++ b/docs/latest/advanced/head.md @@ -12,12 +12,13 @@ is a crucial element in HTML to set metadata for a page. It allows you to: - Include JavaScript code with `