docs: update canary docs for Fresh 2 (#3108)

There are still some rough edges here and there, but it's in a much
better shape than what we have today.
This commit is contained in:
Marvin Hagemeister
2025-07-18 15:18:38 +02:00
committed by GitHub
parent a66e0df08d
commit a703e79181
29 changed files with 2094 additions and 62 deletions
+243
View File
@@ -0,0 +1,243 @@
---
description: |
Add a global app wrapper to provide common meta tags or context for application routes.
---
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.
```tsx
const app = new App()
.use(staticFiles())
.get("/", () => new Response("hello"))
.get("/about", (ctx) => ctx.render(<h1>About me</h1>));
// Start server
app.listen();
```
## `.use()`
Add one or more [middlewares](/docs/canary/concepts/middleware). Middlewares are
matched left to right.
```ts
// Add a middleware at the root
app.use(async (ctx) => {
console.log("my middleware");
return await ctx.next();
});
```
You can also add multiple middlewares:
```ts
app.use(middleware1, middleware2, middleware3);
```
Adding middlewares at a specific path:
```ts
app.use("/foo/bar", middleware);
```
## `.get()`
Respond to a `GET` request with the specified middlewares.
```ts
app.get("/about", async (ctx) => {
return new Response(`GET: ${ctx.url.pathname}`);
});
```
Respond with multiple middlewares:
```ts
app.get("/about", middleware1, middleware2, async (ctx) => {
return new Response(`GET: ${ctx.url.pathname}`);
});
```
## `.post()`
Respond to a `POST` request with the specified middlewares.
```ts
app.post("/api/user/:id", async (ctx) => {
await somehowCreateUser(ctx.params.id);
return new Response(`User created`);
});
```
Respond with multiple middlewares:
```ts
app.post("/api/user/:id", middleware1, middleware2, async (ctx) => {
await somehowCreateUser(ctx.params.id);
return new Response(`User created`);
});
```
## `.put()`
Respond to a `PUT` request with the specified middlewares.
```ts
app.put("/api/user/:id", async (ctx) => {
await somehowSaveUser(ctx.params.id);
return new Response(`Updated user`);
});
```
Respond with multiple middlewares:
```ts
app.put("/api/user/:id", middleware1, middleware2, async (ctx) => {
await somehowSaveUser(ctx.params.id);
return new Response(`Updated user`);
});
```
## `.delete()`
Respond to a `DELETE` request with the specified middlewares.
```ts
app.delete("/api/user/:id", async (ctx) => {
await somehowDeleteUser(ctx.params.id);
return new Response(`User deleted`);
});
```
Respond with multiple middlewares:
```ts
app.delete("/api/user/:id", middleware1, middleware2, async (ctx) => {
await somehowDeleteUser(ctx.params.id);
return new Response(`User deleted`);
});
```
## `.head()`
Respond to a `HEAD` request with the specified middlewares.
```ts
app.head("/api/user/:id", async (ctx) => {
return new Response(null, { status: 200 });
});
```
Respond with multiple middlewares:
```ts
app.head("/api/user/:id", middleware1, middleware2, async (ctx) => {
return new Response(null, { status: 200 });
});
```
## `.all()`
Respond to a request for all HTTP verbs with the specified middlewares.
```ts
app.all("/api/foo", async (ctx) => {
return new Response("hehe");
});
```
Respond with multiple middlewares:
```ts
app.all("/api/foo", middleware1, middleware2, async (ctx) => {
return new Response("hehe");
});
```
## `.route()`
TODO
## `.appWrapper()`
Set the [App Wrapper](/docs/canary/advanced/app-wrapper) component. This is
where the outer HTML, typically up until the `<body>`-tag is rendered.
## `.layout()`
Set a [Layout](/docs/canary/advanced/layouts) component at the specified path.
The app wrapper component and prior layouts are inherited by default unless
opted out.
## `.onError()`
Set an error route or middleware that will be rendered when it catches an error.
Setting a middleware:
```ts
// top level error handler
app.onError("*", ctx => {
return new Response(String(ctx.error), { status: 500 })
}))
```
Setting a route:
TODO
## `.notFound()`
Call this middleware or route whenever a HTTP 404 error is caught.
```ts
app.notFound(() => {
return new Response("Not found", { status: 404 });
});
```
TODO: Route
## `.mountApp()`
TODO
## `.handler()`
Create a handler function out of your app. This is a function where you can pass
a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) instance
to and receive a
[`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
```ts
const app = new App()
.get("/", () => new Response("hello"));
const handler = app.handler();
const response = await handler(new Request("http://localhost"));
console.log(await response.text()); // Logs: "hello"
```
This functionality is often used during testing or to run Fresh inside other
frameworks.
## `.listen()`
Spawns a server and listens for incoming connections.
```ts
const app = new App()
.get("/", () => new Response("hello"));
app.listen();
```
You can pass an options object to customize which port to listen on and other
aspects.
```ts
app.listen({ port: 4000 });
```
+137
View File
@@ -0,0 +1,137 @@
---
description: Plugins can add new functionality to Fresh without requiring significant complexity.
---
The `Context` instance is shared across all middlewares 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.
## `.config`
Contains the resolved Fresh configuration.
```ts
app.get("/", (ctx) => {
console.log("Config: ", ctx.config);
return new Response("hey");
});
```
## `.url`
Contains a [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL)
instance of the requested url.
```ts
app.get("/", (ctx) => {
console.log("path: ", ctx.url.pathname);
const hasParam = ctx.url.searchParams.has("q");
return new Response(`Has q param: ${String(hasParam)});
});
```
## `.req`
Contains the incoming
[`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) instance.
```ts
app.get("/", (ctx) => {
console.log("Request: ", ctx.req);
if (ctx.req.headers.has("X-Foo")) {
// do something
}
return new Response("hello");
});
```
## `.params`
Contains the params of the matched route pattern.
```ts
app.get("/foo/:id", (ctx) => {
console.log("id: ", ctx.params.id);
return new Response(`Accessed: /foo/${ctx.params.id}`);
});
```
## `.state`
Pass data to the next middlewares with state. Every request has its own state
object.
```ts
app.use((ctx) => {
ctx.state.text = "foo";
return ctx.next();
});
app.use((ctx) => {
console.log(ctx.state.text); // Logs: "foo"
return ctx.next();
});
```
## `.error`
If an error was thrown, this property will hold the caught value (default:
`null`). This is typically used mainly on an error page.
```ts
app.onError((ctx) => {
const message = ctx.error instanceof Error
? ctx.error.message
: String(ctx.error);
return new Response(message, { status: 500 });
});
```
## `.redirect()`
Trigger a redirect from a middleware:
```ts
app.get("/old-url", (ctx) => {
return ctx.redirect("/new-url");
});
```
Set a custom status code (default is `302`):
```ts
app.get("/old-url", (ctx) => {
return ctx.redirect("/new-url", 307);
});
```
## `.render()`
Render JSX and create a HTML `Response`.
```tsx
app.get("/", (ctx) => {
return ctx.render(<h1>hello world</h1>);
});
```
Set custom response headers or other metadata:
```tsx
app.get("/teapot", (ctx) => {
return ctx.render(
<h1>I'm a teapot</h1>,
{
status: 418,
headers: {
"X-Foo": "abc",
},
},
);
});
```
+141
View File
@@ -0,0 +1,141 @@
---
description: |
Routes are the basic building block of Fresh applications. They are used to define the behaviour the application when a given path is requested.
---
Fresh ships with the `fsRoutes` helper which automatically adds routes based on
the structure in the `routes/` folder in your project. When you add a new file
there, it will register a new route automatically.
```ts
import { App, fsRoutes, staticFiles } from "fresh";
const app = new App({ root: import.meta.url })
.use(staticFiles());
await fsRoutes(app, {
loadIsland: (path) => import(`./islands/${path}`),
loadRoute: (path) => import(`./routes/${path}`),
});
```
> [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.
Example project structure:
```sh Project structure
└── routes
   ├── (marketing) # Route group, used to group related routes
   │ ├── _layout.tsx # Apply layout to all routes in this directory
   │ ├── about.tsx # /about route
   │ ├── career.tsx # /career route
│ ├── (_components) # related components
   │ │ └── newsletter-cta.tsx
│ └── (_islands) # Local island directory
│ └── interactive-stats.tsx # Fresh treats this as an island
└── shop
├── (_components)
│ └── product-card.tsx
├── (_islands)
│ └── cart.tsx # Fresh treats this as an island
└── index.tsx
```
File names are mapped to route patterns as follows:
- File extensions are ignored.
- Literals in the file path are treated as string literals to match.
- Files named `<path>/index.<ext>` behave identically to a file named
`<path>.<ext>`.
- Path segments can be made dynamic by surrounding an identifier with `[` and
`]`.
- Paths where the last path segment follows the structure `[...<ident>]` are
treated as having a wildcard suffix.
Here is a table of file names, which route patterns they map to, and which paths
they might match:
| File name | Route pattern | Matching paths |
| --------------------------- | ---------------------- | --------------------------------------- |
| `index.ts` | `/` | `/` |
| `about.ts` | `/about` | `/about` |
| `blog/index.ts` | `/blog` | `/blog` |
| `blog/[slug].ts` | `/blog/:slug` | `/blog/foo`, `/blog/bar` |
| `blog/[slug]/comments.ts` | `/blog/:slug/comments` | `/blog/foo/comments` |
| `old/[...path].ts` | `/old/:path*` | `/old/foo`, `/old/bar/baz` |
| `docs/[[version]]/index.ts` | `/docs{/:version}?` | `/docs`, `/docs/latest`, `/docs/canary` |
Advanced use-cases can require that a more complex pattern be used for matching.
A custom [URL pattern][urlpattern] can be specified in the route configuration.
This pattern will be used instead of the file path based pattern:
```ts routes/my-route.ts
import { RouteConfig } from "fresh";
export const config: RouteConfig = {
routeOverride: "/x/:module@:version/:path*",
};
// ...
```
## Route Groups
When working with [layouts](/docs/concepts/layouts) or
[middlewares](/docs/concepts/middleware), you'll sometimes come across a
situation where you want your routes to inherit from a layout other than what's
suggested by the URL segment.
Let's illustrate that with an example:
```txt
/about -> layout A
/career -> layout A
/archive -> layout B
/contact -> layout B
```
Without any way to group routes this is a problem because every route segment
can only have one `_layout` file.
```txt Project structure
└── routes
   ├── _layout.tsx # applies to all routes here :(
   ├── about.tsx
   ├── career.tsx
   ├── archive.tsx
   └── contact.tsx
```
We can solve this problem with route groups. A route group is a folder which has
a name that is wrapped in parentheses. For example `(info)` would be considered
a route group and so would `(marketing)`. This enables us to group related
routes in a folder and use a different `_layout` file for each group.
```txt Project structure
└── routes
   ├── (marketing)
   │ ├── _layout.tsx # only applies to about.tsx and career.tsx
   │ ├── about.tsx
   │ └── career.tsx
   └── (info)
   ├── _layout.tsx # only applies to archive.tsx and contact.tsx
   ├── archive.tsx
   └── contact.tsx
```
> [warn]: Be careful about routes in different groups which match to the same
> URL. Such scenarios will lead to ambiguity as to which route file should be
> picked.
>
> ```txt Project structure
> └── routes
>    ├── (group-1)
>    │ └── about.tsx # Bad: Maps to same `/about` url
>    └── (group-2)
>    └── about.tsx # Bad: Maps to same `/about` url
> ```
[urlpattern]: https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API
+36
View File
@@ -0,0 +1,36 @@
---
description: |
This chapter goes over some fundamental concepts of Fresh.
---
The way Fresh works is that it receives a
[`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request), passes it
through one or more middlewares until one of them responds. This can be an HTML
response, a JSON response or any other response for that matter.
If the response was HTML and contained Islands (=interactive Preact components),
Fresh will boot them up in the browser and execute the relevant JavaScript.
Here is an overview of the basic concepts in Fresh:
- [**App**](/docs/canary/concepts/app) - Holds all the information about your
app, like routes, etc
- [**Middleware**](/docs/canary/concepts/middleware) - Respond to a request and
return a `Response`. Used to set headers, or pass state to other middelwares.
When a middleware doesn't call the next one and returns a response, it's
usually called a "handler".
- [**Context**](/docs/canary/context) - Passed through every middleware. Use
this to share state, trigger redirects or render HTML.
- [**Routes**](/docs/canary/routes) - Responds to a particular URL and runs as
chain of middlewares if it matches
- [**Islands**](/docs/canary/concepts/islands) - Render interactive Preact
components on the client
Advanced concepts:
- [**App wrapper**](/docs/canary/advanced/app-wrapper) - Responsible for the
outer HTML structure, usually up to the `<body>`-tag
- [**Layouts**](/docs/canary/advanced/layouts) - Re-use a shared layout when
calling `ctx.render()` across routes
- [**Partials**](/docs/canary/advanced/partials) - Stream in server generated
content on the current page
+122
View File
@@ -0,0 +1,122 @@
---
description: |
Islands enable client side interactivity in Fresh. They are hydrated on the client in addition to being rendered on the server.
---
Islands enable client side interactivity in Fresh and they are rendered both on
the server and in the client.
Islands are defined by creating a file in the `islands/` folder or a
`(_islands)` folder somewhere in the `routes/` directory. The name of this file
must be a PascalCase or kebab-case name of the island.
```tsx islands/my-island.tsx
import { useSignal } from "@preact/signals";
export default function MyIsland() {
const count = useSignal(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => (count.value += 1)}>+</button>
</div>
);
}
```
An island can be used anywhere like a regular Preact component. Fresh will take
care of making it interactive on the client.
```tsx
import MyIsland from "../islands/my-island.tsx";
const app = new App()
.get("/", (ctx) => ctx.render(<MyIsland />));
```
## 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:
- Primitive types `string`, `number`, `boolean`, `bigint`, and `null`
- `Infinity`, `-Infinity`, and `NaN`
- `Uint8Array`
- `Date`
- `RegExp`
- `JSX` Elements
- Plain objects with string keys and serializable values
- Arrays containing serializable values
- Preact 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
deserialization.
> [warn]: Passing functions to an island is not supported.
>
> ```tsx
> // WRONG
> <MyIsland onClick={() => console.log("hey")} />;
> ```
### Passing JSX
A powerful feature of Fresh is that you can pass server-rendered JSX to an
island via props.
```tsx routes/index.tsx
import MyIsland from "../islands/my-island.tsx";
const app = new App()
.get("/", (ctx) => {
return ctx.render(
<MyIsland jsx={<h1>hello</h1>}>
<p>This text is rendered on the server</p>
</MyIsland>,
);
});
```
### Nesting islands
Islands can be nested within other islands as well. In that scenario they act
like a normal Preact component, but still receive the serialized props if any
were present.
In essence, Fresh allows you to mix static and interactive parts in your app in
a way that's most optimal for your app. We'll keep sending only the JavaScript
that is needed for the islands to the browser.
```tsx route/index.tsx
import MyIsland from "../islands/my-island.tsx";
import OtherIsland from "../islands/other-island.tsx";
// Later...
<div>
<MyIsland>
<OtherIsland foo="this prop will be serialized" />
</MyIsland>
<p>Some more server rendered text</p>
</div>;
```
## 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:
```tsx islands/my-island.tsx
import { IS_BROWSER } from "fresh/runtime";
export function MyIsland() {
// Return any prerenderable JSX here which makes sense for your island
if (!IS_BROWSER) return <div></div>;
// All the code which must run in the browser comes here!
// Like: EventSource, navigator.getUserMedia, etc.
return <div></div>;
}
```
+124
View File
@@ -0,0 +1,124 @@
---
description: |
Add a layout to provide common meta tags, context for application sub routes, and common layout.
---
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.
```txt Project structure
└── 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
```
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`.
```tsx routes/sub/_layout.tsx
import { PageProps } from "$fresh/server.ts";
export default function Layout({ Component, state }: PageProps) {
// do something with state here
return (
<div class="layout">
<Component />
</div>
);
}
```
## Async layouts
In case you need to fetch data asynchronously before rendering the layout, you
can use an async layout to do so.
```tsx routes/sub/_layout.tsx
import { FreshContext } from "$fresh/server.ts";
export default async function Layout(req: Request, ctx: FreshContext) {
// do something with state here
const data = await loadData();
return (
<div class="layout">
<p>{data.greeting}</p>
<ctx.Component />
</div>
);
}
```
### Define helper
To make it a little quicker to write async layouts, Fresh ships with a
`defineLayout` helper which automatically infers the correct types for the
function arguments.
```tsx
import { defineLayout } from "$fresh/server.ts";
export default defineLayout(async (req, ctx) => {
const data = await loadData();
return (
<div class="layout">
<p>{data.greeting}</p>
<ctx.Component />
</div>
);
});
```
## 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:
```txt Project structure
└── 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
import { RouteConfig } from "$fresh/server.ts";
export const config: RouteConfig = {
skipInheritedLayouts: true, // Skip already inherited layouts
};
export default function MyPage() {
return <p>Hello world</p>;
}
```
You can skip already inherited layouts inside a layout file:
```tsx routes/special/_layout.tsx
import { LayoutConfig } from "$fresh/server.ts";
export const config: LayoutConfig = {
skipInheritedLayouts: true, // Skip already inherited layouts
};
export default function MyPage() {
return <p>Hello world</p>;
}
```
+88
View File
@@ -0,0 +1,88 @@
---
description: |
Add middleware routes to intercept requests or responses for analytics purposes, access control, or anything else.
---
A middleware is a function that receives a [`Context`](/docs/canary/context)
object with the
[`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) and
returns a
[`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response). They
are typically used to set HTTP Headers, measure response times or fetch data and
pass it to another middleware.
```tsx
const app = new App<{ greeting: string }>()
.use((ctx) => {
// Middleware to pass data
ctx.state.greeting = "Hello world";
return ctx.next();
})
.use(async (ctx) => {
// Middleware to add a HTTP header
const res = await ctx.next();
res.headers.set("server", "fresh server");
return res;
})
// A handler is a form of middleware that responds. Here we
// render HTML and return it.
.get("/", (ctx) => {
return ctx.render(<h1>{ctx.state.greeting}</h1>);
});
```
Middlewares can be chained and combined in whatever way you desire. They are an
excellent way to make http-related logic reusable on the server.
## Middleware helper
Use the `define.middleware()` helper to get typings out of the box:
```ts
import { define } from "./utils.ts";
const middleware = define.middleware(async (ctx) => {
console.log("my middleware");
return await ctx.next();
});
```
## Included middlewares
Fresh ships with the following middlewares built-in:
- [cors()](/docs/canary/plugins/cors) - Set CORS HTTP headers
- [trailingSlash()](/docs/canary/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.
```ts routes/foo/_middleware.ts
import { define } from "./utils.ts";
export default define.middleware(async (ctx) => {
console.log("my middleware");
return await ctx.next();
});
```
You can also export an array of middlewares:
```ts routes/foo/_middleware.ts
import { define } from "./utils.ts";
const middleware1 = define.middleware(async (ctx) => {
console.log("A");
return await ctx.next();
});
const middleware1 = define.middleware(async (ctx) => {
console.log("B");
return await ctx.next();
});
export default [middleware1, middleware2];
```
+32
View File
@@ -0,0 +1,32 @@
---
description: |
File based routing is the simplest way to do routing in Fresh apps. Additionally custom patterns can be configured per route.
---
Routing defines which middlewares and routes should respond to a particular
request.
```ts
const app = new App()
.get("/", () => new Response("hello")) // Responds to: GET /
.get("/other", () => new Response("other")) // Responds to: GET /other
.post("/upload", () => new Response("upload")); // Responds to: POST /upload
.get("/books/:id", (ctx) => {
// Responds to: GET /books/my-book, /books/cool-book, etc
const id = ctx.params.id
return new Response(`Book id: ${id}`));
})
.get("/blog/:post/comments", () => {
// 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}`)
})
.get("/foo/*", (ctx) => {
// Responds to: GET /foo/bar, /foo/bar/baz, etc
return new Response("foo"));
})
```
Fresh supports the full
[`URLPattern`](https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API)
syntax for setting pathnames.
+47
View File
@@ -0,0 +1,47 @@
---
description: |
Fresh has built-in support for serving static files. This is useful for serving images, CSS, and other static assets.
---
Static assets placed in the `static/` directory are served at the root of the
webserver via the `staticFiles()` middleware. They are streamed directly from
disk for optimal performance with
[`ETag`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/ETag)
headers.
```ts
import { staticFiles } from "fresh";
const app = new App()
.use(staticFiles());
```
## Caching headers
By default, Fresh adds caching headers for the `src` and `srcset` attributes on
`<img>` and `<source>` tags.
```jsx
// Caching headers will be automatically added
<img src="/user.png" />;
```
You can always opt out of this behaviour per tag, by adding the
`data-fresh-disable-lock` attribute.
```jsx
// Opt-out of automatic caching headers
<img src="/user.png" data-fresh-disable-lock />;
```
## Adding caching headers manually
Use the `asset()` function to add caching headers manually. It will be served
with a cache lifetime of one year.
```jsx
import { asset } from "fresh/runtime";
// Adding caching headers manually
<a href={asset("/brochure.pdf")}>View brochure</a>;
```