docs: make 2.x the default version (#3369)

This commit is contained in:
Marvin Hagemeister
2025-09-09 14:36:51 +02:00
committed by GitHub
parent 2c315a9972
commit 79d8cfc3ed
109 changed files with 1589 additions and 1502 deletions
@@ -35,7 +35,7 @@ metadata for Fresh.
Any other static files generated by plugins will be stored in the
`_fresh/static` subfolder. They will be served the same as other
[static files](/docs/concepts/static-files.md).
[static files](/docs/1.x/concepts/static-files.md).
> [info]: The `_fresh` folder should not be committed to the repository. Add an
> entry in the `.gitignore` file to ensure that it is not committed. Create that
@@ -10,6 +10,7 @@ Here are instructions for specific providers / systems:
- [Deno Deploy](#deno-deploy)
- [Docker](#docker)
- [Self Contained Executable](#self-contained-executable)
## Deno Deploy
@@ -83,4 +84,4 @@ $ deno compile --include static --include _fresh --include deno.json -A main.ts
[aws-container-registry]: https://docs.aws.amazon.com/AmazonECS/latest/userguide/create-container-image.html#create-container-image-push-ecr
[gcp-container-registry]: https://cloud.google.com/container-registry/docs/pushing-and-pulling
[deno-deploy]: https://deno.com/deploy
[deploy-to-production]: /docs/getting-started/deploy-to-production
[deploy-to-production]: /docs/1.x/getting-started/deploy-to-production
+8
View File
@@ -0,0 +1,8 @@
---
description: |
This chapter goes over some fundamental concepts of Fresh.
---
This chapter goes over some fundamental concepts of Fresh. It covers the
overarching architecture design of Fresh applications, as well as reference
documentation about the various features of Fresh.
+228
View File
@@ -0,0 +1,228 @@
---
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. Islands are isolated Preact
components that are rendered on the server and then hydrated on the client. This
is different from all other components in Fresh, as they are usually rendered on
the server only.
Islands are defined by creating a file in the `islands/` folder in a Fresh
project. 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>
Counter is at {count}.{" "}
<button onClick={() => (count.value += 1)}>+</button>
</div>
);
}
```
An island can be used in a page like a regular Preact component. Fresh will take
care of automatically re-hydrating the island on the client.
```tsx route/index.tsx
import MyIsland from "../islands/my-island.tsx";
export default function Home() {
return <MyIsland />;
}
```
## Passing JSX to islands
Islands support passing JSX elements via the `children` property.
```tsx islands/my-island.tsx
import { useSignal } from "@preact/signals";
import { ComponentChildren } from "preact";
interface Props {
children: ComponentChildren;
}
export default function MyIsland({ children }: Props) {
const count = useSignal(0);
return (
<div>
Counter is at {count}.{" "}
<button onClick={() => (count.value += 1)}>+</button>
{children}
</div>
);
}
```
This allows you to pass static content rendered by the server to an island in
the browser.
```tsx routes/index.tsx
import MyIsland from "../islands/my-island.tsx";
export default function Home() {
return (
<MyIsland>
<p>This text is rendered on the server</p>
</MyIsland>
);
}
```
You can also create shared components in your `components/` directory, which can
be used in both static content and interactive islands. When these components
are used within islands, interactivity can be added, such as `onClick` handlers
(using an `onClick` handler on a button outside of an island will not fire).
```tsx islands/my-island.tsx
import { useSignal } from "@preact/signals";
import { ComponentChildren } from "preact";
import Card from "../components/Card.tsx";
import Button from "../components/Button.tsx";
interface Props {
children: ComponentChildren;
}
export default function MyIsland({ children }: Props) {
const count = useSignal(0);
return (
<Card>
Counter is at {count}.{" "}
<Button onClick={() => (count.value += 1)}>+</Button>
{children}
</Card>
);
}
```
## Passing other 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`, `boolean`, `bigint`, and `null`
- Most `number`s (`Infinity`, `-Infinity`, and `NaN` are silently converted to
`null`)
- Plain objects with string keys and serializable values
- Arrays containing serializable values
- Uint8Array
- JSX Elements (restricted to `props.children`)
- 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. Passing complex objects like `Date`, custom classes, or
functions is not supported.
During server side rendering, Fresh annotates the HTML with special comments
that indicate where each island will go. This gives the code sent to the client
enough information to put the islands where they are supposed to go without
requiring hydration for the static children of interactive islands. No
Javascript is sent to the client when no interactivity is needed.
```html Response body
<!--frsh-myisland_default:default:0-->
<div>
Counter is at 0.
<button>+</button>
<!--frsh-slot-myisland_default:children-->
<p>This text is rendered on the server</p>
<!--/frsh-slot-myisland_default:children-->
</div>
<!--/frsh-myisland_default:default:0-->
```
### 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.
```tsx islands/other-island.tsx
import { useSignal } from "@preact/signals";
import { ComponentChildren } from "preact";
interface Props {
children: ComponentChildren;
foo: string;
}
function randomNumber() {
return Math.floor(Math.random() * 100);
}
export default function OtherIsland({ children, foo }: Props) {
const number = useSignal(randomNumber());
return (
<div>
<p>String from props: {foo}</p>
<p>
<button onClick={() => (number.value = randomNumber())}>Random</button>
{" "}
number is: {number}.
</p>
</div>
);
}
```
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";
export default function Home() {
return (
<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 like:
```
An error occurred during route handling or page rendering. ReferenceError: EventSource is not defined
at Object.MyIsland (file:///Users/someuser/fresh-project/islandsmy-island.tsx:6:18)
at m (https://esm.sh/v129/preact-render-to-string@6.2.0/X-ZS8q/denonext/preact-render-to-string.mjs:2:2602)
at m (https://esm.sh/v129/preact-render-to-string@6.2.0/X-ZS8q/denonext/preact-render-to-string.mjs:2:2113)
....
```
Use the [`IS_BROWSER`](https://deno.land/x/fresh/runtime.ts?doc=&s=IS_BROWSER)
flag as a guard to fix the issue:
```tsx islands/my-island.tsx
import { IS_BROWSER } from "$fresh/runtime.ts";
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>;
}
```
@@ -26,16 +26,16 @@ 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 { define } from "../../utils.ts";
import { PageProps } from "$fresh/server.ts";
export default define.layout({ Component, state }) => {
export default function Layout({ Component, state }: PageProps) {
// do something with state here
return (
<div class="layout">
<Component />
</div>
);
})
}
```
## Async layouts
@@ -44,12 +44,33 @@ 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 { define } from "../../utils.ts";
import { FreshContext } from "$fresh/server.ts";
export default define.layout(async (ctx) => {
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 routes/greet/_layout.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>
@@ -78,22 +99,21 @@ To make `routes/sub/special.tsx` opt out of rendering layouts we can set
`skipInheritedLayouts: true`.
```tsx routes/sub/special.tsx
import { type RouteConfig } from "fresh";
import { define } from "../../utils.ts";
import { RouteConfig } from "$fresh/server.ts";
export const config: RouteConfig = {
skipInheritedLayouts: true, // Skip already inherited layouts
};
export default define.layout(() => {
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 { type LayoutConfig } from "fresh";
import { LayoutConfig } from "$fresh/server.ts";
export const config: LayoutConfig = {
skipInheritedLayouts: true, // Skip already inherited layouts
+222
View File
@@ -0,0 +1,222 @@
---
description: |
Add middleware routes to intercept requests or responses for analytics purposes, access control, or anything else.
---
A middleware is defined in a `_middleware.ts` file. It will intercept the
request in order for you to perform custom logic before or after the route
handler. This allows modifying or checking requests and responses. Common
use-cases for this are logging, authentication, and performance monitoring.
Each middleware gets passed a `next` function in the context argument that is
used to trigger child handlers. The `ctx` also has a `state` property that can
be used to pass arbitrary data to downstream (or upstream) handlers. This
`state` is included in `PageProps` by default, which is available to both the
special [\_app](/docs/1.x/concepts/app-wrapper.md) wrapper and normal
[routes](/docs/1.x/concepts/routes.md). `ctx.state` is normally set by modifying
its properties, e.g. `ctx.state.loggedIn = true`, but you can also replace the
entire object like `ctx.state = { loggedIn: true }`.
```ts routes/_middleware.ts
import { FreshContext } from "$fresh/server.ts";
interface State {
data: string;
}
export async function handler(
req: Request,
ctx: FreshContext<State>,
) {
ctx.state.data = "myData";
const resp = await ctx.next();
resp.headers.set("server", "fresh server");
return resp;
}
```
```ts routes/myHandler.ts
export const handler: Handlers<any, { data: string }> = {
GET(_req, ctx) {
return new Response(`middleware data is ${ctx.state.data}`);
},
};
```
Middlewares are scoped and can be layered. This means a project can have
multiple middlewares, each covering a different set of routes. If multiple
middlewares cover a route, they will all be run, in order of specificity (least
specific first).
For example, take a project with the following routes:
```txt-files Project Structure
└── <root>/routes
   ├── _middleware.ts
   ├── index.ts
   └── admin
      ├── _middleware.ts
      └── index.ts
      └── signin.ts
```
For a request to `/` the request will flow like this:
1. The `routes/_middleware.ts` middleware is invoked.
2. Calling `ctx.next()` will invoke the `routes/index.ts` handler.
For a request to `/admin` the request flows like this:
1. The `routes/_middleware.ts` middleware is invoked.
2. Calling `ctx.next()` will invoke the `routes/admin/_middleware.ts`
middleware.
3. Calling `ctx.next()` will invoke the `routes/admin/index.ts` handler.
For a request to `/admin/signin` the request flows like this:
1. The `routes/_middleware.ts` middleware is invoked.
2. Calling `ctx.next()` will invoke the `routes/admin/_middleware.ts`
middleware.
3. Calling `ctx.next()` will invoke the `routes/admin/signin.ts` handler.
A single middleware file can also define multiple middlewares (all for the same
route) by exporting an array of handlers instead of a single handler. For
example:
```ts routes/_middleware.ts
export const handler = [
async function middleware1(req, ctx) {
// do something
return ctx.next();
},
async function middleware2(req, ctx) {
// do something
return ctx.next();
},
];
```
It should be noted that `middleware` has access to route parameters. If you're
running a fictitious `routes/[tenant]/admin/_middleware.ts` like this:
```ts routes/[tenant]/admin/_middleware.ts
import { FreshContext } from "$fresh/server.ts";
export async function handler(_req: Request, ctx: FreshContext) {
const currentTenant = ctx.params.tenant;
// do something with the tenant
const resp = await ctx.next();
return resp;
}
```
and the request is to `mysaas.com/acme/admin/`, then `currentTenant` will have
the value of `acme` in your middleware.
## Middleware Destination
To set the stage for this section, let's focus on the part of `FreshContext`
that looks like this:
```ts fresh 🍋
export interface FreshContext<State = Record<string, unknown>> {
...
next: () => Promise<Response>;
state: State;
destination: router.DestinationKind;
remoteAddr: {
transport: "tcp" | "udp";
hostname: string;
port: number;
};
...
}
```
and `router.DestinationKind` is defined like this:
```ts fresh 🍋
export type DestinationKind = "internal" | "static" | "route" | "notFound";
```
This is useful if you want your middleware to only run when a request is headed
for a `route`, as opposed to something like `http://localhost:8001/favicon.ico`.
### Example
Initiate a new Fresh project (`deno run -A -r https://fresh.deno.dev/`) and then
create a `_middleware.ts` file in the `routes` folder like this:
```ts routes/_middleware.ts
import { FreshContext } from "$fresh/server.ts";
export async function handler(req: Request, ctx: FreshContext) {
console.log(ctx.destination);
console.log(req.url);
const resp = await ctx.next();
return resp;
}
```
If you start up your server (`deno task start`) you'll see the following:
```sh Terminal
Task start deno run -A --watch=static/,routes/ dev.ts
Watcher Process started.
The manifest has been generated for 4 routes and 1 islands.
🍋 Fresh ready
Local: http://localhost:8000/
route
http://localhost:8000/
internal
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/deserializer.js
internal
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/signals.js
internal
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/plugin-twind-main.js
internal
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/main.js
internal
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/island-counter.js
internal
http://localhost:8000/_frsh/refresh.js
static
http://localhost:8000/logo.svg?__frsh_c=3c7400558fc00915df88cb181036c0dbf73ab7f5
internal
http://localhost:8000/_frsh/alive
internal
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/chunk-PDMKJVJ5.js
internal
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/chunk-UGFDDSOV.js
internal
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/chunk-RCK7U3UF.js
```
That first `route` request is for when `Fresh` responds with the root level
`index.tsx` route. The rest, as you can see, are either `internal` or `static`
requests. You can use `ctx.destination` to filter these out if your middleware
is only supposed to deal with routes.
## Middleware Redirects
If you want to redirect a request from a middleware, you can do so by returning:
```ts routes/_middleware.ts
export function handler(req: Request): Response {
return Response.redirect("https://example.com", 307);
}
```
`307` stands for temporary redirect. You can also use `301` for permanent
redirect. You can also redirect to a relative path by doing:
```ts routes/_middleware.ts
export function handler(req: Request): Response {
return new Response("", {
status: 307,
headers: { Location: "/my/new/relative/path" },
});
}
```
@@ -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/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/1.x/fresh-partial-docs.png)
The code for such a page (excluding styling) might look like this:
@@ -130,7 +130,7 @@ may be provided to Fresh's `start` entrypoint in the `main.ts` file.
### Hook: `buildStart`
This hook is run at the start of the Fresh
[ahead-of-time build task](/docs/concepts/ahead-of-time-builds). It may be
[ahead-of-time build task](/docs/1.x/concepts/ahead-of-time-builds). It may be
synchronous or asynchronous.
The build start hook is called with the
@@ -139,25 +139,25 @@ object, which contains the full Fresh configuration.
This hook may be used to generate precompiled static assets. Any files saved to
the `static` subfolder of `config.build.outDir` (typically `_fresh`) will be
served the same as other [static files](/docs/concepts/static-files).
served the same as other [static files](/docs/1.x/concepts/static-files).
### Hook: `buildEnd`
This hook is run at the end of the Fresh
[ahead-of-time build task](/docs/concepts/ahead-of-time-builds). It may be
[ahead-of-time build task](/docs/1.x/concepts/ahead-of-time-builds). It may be
synchronous or asynchronous.
### Routes and Middlewares
You can create routes and middlewares that get loaded and rendered like the
normal [routes](/docs/concepts/routes) and
[middlewares](/docs/concepts/middleware).
normal [routes](/docs/1.x/concepts/routes) and
[middlewares](/docs/1.x/concepts/middleware).
The plugin routes and middlewares need a defined path in the format of a file
name without a filetype inside the routes directory(E.g. `blog/index`,
`blog/[slug]`).
For more examples see the [Concepts: Routing](/docs/concepts/routing) page.
For more examples see the [Concepts: Routing](/docs/1.x/concepts/routing) page.
To create a middleware you need to create a `MiddlewareHandler` function.
+151
View File
@@ -0,0 +1,151 @@
---
description: |
File based routing is the simplest way to do routing in Fresh apps. Additionally custom patterns can be configured per route.
---
Routing is the mechanism that determines what route a given incoming request is
handled by. Fresh routes requests based on their URL path. By default routes
specify which paths they are invoked for using the name of the file. Routes can
also define a custom [URL pattern][urlpattern] to match against for more
advanced use cases.
The file based routing in Fresh is very similar to the file based routing seen
in other frameworks, namely Next.js. File names are used to determine which
route a given request should be handled by. The pattern is determined based on
the path of the file on disk, relative to the `routes/` directory.
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/x.ts
import { RouteConfig } from "$fresh/server.ts";
export const config: RouteConfig = {
routeOverride: "/x/:module@:version/:path*",
};
// ...
```
## Route Groups
When working with [layouts](/docs/1.x/concepts/layouts) or
[middlewares](/docs/1.x/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 Example page layout
/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-files Project structure
<project root>
└── 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-files Project structure
└── <root>/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-files Project structure
> └── <root>/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
## Co-location
If you want to store components and islands closer to their routes, you may want
to use co-location.
When the name of a route group folder starts with an underscore, like
`(_components)`, Fresh will ignore that folder and it’s effectively treated as
private. This means you can use these private route folders to store components
related to a particular route.
Following the above example, say you have some components you only want to use
in your marketing pages, you could create a route group folder `(_components)`
to house these.
The one special name is `(_islands)` which tells Fresh to treat all files in
that folder as an island.
```txt-files Project structure
└── <root>/routes
   ├── (marketing)
   │ ├── _layout.tsx
   │ ├── about.tsx
   │ ├── career.tsx
│ ├── (_components)
   │ │ └── newsletter-cta.tsx
│ └── (_islands)
   │ └── interactive-stats.tsx # Fresh treats this as an island
   └── shop
├── (_components)
   │ └── product-card.tsx
└── (_islands)
   └── cart.tsx # Fresh treats this as an island
```
Combined together, this gives you the ability to organise your code on a feature
basis and put all related components, islands or anything else into a shared
folder.
+17
View File
@@ -0,0 +1,17 @@
---
description: |
Fresh's architecture is designed to leverage server components by default.
---
If you've read about Fresh's [architecture](/docs/1.x/concepts/architecture)
then you know that it's based on the islands architecture pattern. The flip side
of this is that everything else is, by default, a server component. When you
[create a route](/docs/1.x/getting-started/create-a-route), all of the
components used are rendered on the server. No JavaScript is sent to the client,
unless you specifically include something from the `/islands/` folder.
Internally, Fresh's rendering heavily leverages
[preact-render-to-string](https://github.com/preactjs/preact-render-to-string).
This is the exact library mentioned on Preact's
[Server-Side Rendering](https://preactjs.com/guide/v10/server-side-rendering/)
article.
@@ -103,8 +103,8 @@ await dev(import.meta.url, "./main.ts", {
## Plugins
See the [docs](/docs/concepts/plugins) on this topic for more detail. But as a
quick example, you can do something like this to load plugins:
See the [docs](/docs/1.x/concepts/plugins) on this topic for more detail. But as
a quick example, you can do something like this to load plugins:
```ts main.ts
await start(manifest, { plugins: [twindPlugin(twindConfig)] });
+55
View File
@@ -0,0 +1,55 @@
---
description: |
Fresh has built-in support for serving static files. This is useful for serving images, CSS, and other static assets.
---
Fresh automatically serves static assets placed in a `static/` directory in the
project root. These assets are served at the root of the webserver, with a
higher priority than routes. This means that if a given request matches a file
in the `static/` folder, it is always served, even if there is a route that
would also match the request.
Static asset responses automatically get a `content-type` header assigned based
on the file extension of the file on disk. Assets are also automatically
streamed from disk to the client to improve performance and efficiency for both
user and server.
Fresh also adds an `etag` header to assets automatically and handles the
`If-None-Match` header for incoming requests.
### Caching
By default, no caching headers are added to assets. This can be disadvantageous
in many scenarios, so Fresh makes it easy to serve assets with long cache
lifetimes too.
The first approach to do this is manual. The client runtime exports an `asset`
function that takes an absolute path to the static asset and returns a "locked"
version of this path that contains a build ID for cache busting. When the asset
is requested at this "locked" path, it will be served with a cache lifetime of
one year.
```tsx routes/page.tsx
import { asset } from "$fresh/runtime.ts";
export default function Page() {
return (
<p>
<a href={asset("/brochure.pdf")}>View brochure</a>
</p>
);
}
```
Fresh also does this automatically for `src` and `srcset` attributes in `<img>`
and `<source>` HTML tags. These will automatically use "locked" paths if Fresh
deems it safe to do so. You can always opt out of this behaviour per tag, by
adding the `data-fresh-disable-lock` attribute.
```tsx routes/user.tsx
{/* Locked URL source */}
<img src="/user.png" />;
{/* Preserve URL source and disable lock */}
<img src="/user.png" data-fresh-disable-lock />;
```
+79
View File
@@ -0,0 +1,79 @@
---
description: |
Style active links with ease in Fresh
---
Fresh automatically enhances the accessibility of `<a>` elements by adding the
aria-current attribute when rendering links that match the current URL. This
attribute is recognized by assistive technologies and clearly indicates the
current page within a set of pages.
- `aria-current="page"` - Added to links with an exact path match, enhancing
accessibility by indicating the current page to assistive technologies.
As we aim to improve accessibility, we encourage the use of `aria-current` for
styling current links where applicable.
## Styling with CSS
The `aria-current` attribute is easily styled with CSS using attribute
selectors, providing a native way to visually differentiate the active link.
```css static/styles.css
/* Give links pointing to the current page a green color */
a[aria-current="page"] {
color: green;
}
/* Color all ancestor links of the current page */
a[aria-current="true"] {
color: peachpuff;
}
```
## Tailwind / Twind
In Tailwind or similar CSS frameworks like Twind, you can apply styles to
elements with the aria-current attribute using bracket notation in your class
definitions. However, the specific syntax varies slightly between Tailwind and
Twind. For Tailwind, use the syntax:
```tsx component/Menu.tsx
function Menu() {
return (
<a href="/foo" class="aria-[current]:text-green-600">
Link to some page
</a>
);
}
```
For Twind, the syntax is:
```tsx component/Menu.tsx
function Menu() {
return (
<a href="/foo" class="[aria-current]:text-green-600">
Link to some page
</a>
);
}
```
### Twind Plugin
The original twind plugin (`import twindPlugin from "$fresh/plugins/twind.ts";`)
supports the above style:
```tsx routes/page.tsx
class="[aria-current='page']:text-green-600"
```
### TwindV1 Plugin
The new twind plugin (`import twindPlugin from "$fresh/plugins/twindv1.ts";`)
requires a slightly different syntax (note the position of the left bracket):
```tsx routes/page.tsx
class="aria-[current='page']:text-green-600"
```
@@ -24,7 +24,7 @@ The purpose of the example app we're building here is to showcase the basic
building blocks of an implementation. As such, it is limited in functionality
and purposefully leaves out things like
[password resets](https://supabase.com/docs/guides/auth/server-side/email-based-auth-with-pkce-flow-for-ssr),
[proper error handling](https://fresh.deno.dev/docs/concepts/error-pages) as
[proper error handling](https://fresh.deno.dev/docs/1.x/concepts/error-pages) as
well as validating input form data. You can find the
[full code here](https://github.com/morlinbrot/supa-fresh-pkce), where the
missing functionality is implemented.
@@ -226,7 +226,7 @@ we are writing next.
We can now write a middleware that will check the auth status of any request,
guarding any protected routes. You can read up on middlewares and where to put
them [in the docs](https://fresh.deno.dev/docs/concepts/middleware).
them [in the docs](https://fresh.deno.dev/docs/1.x/concepts/middleware).
```ts routes/_middleware.ts
import { FreshContext } from "$fresh/server.ts";
@@ -170,7 +170,7 @@ user 2 deleted
Options can be used for some advanced cases, including implementing preflight
request checks for complex CORS use cases. See more on the
[CORS documentation](/docs/examples/dealing-with-cors).
[CORS documentation](/docs/1.x/examples/dealing-with-cors).
## Full File Reference
@@ -89,4 +89,4 @@ requests.
Of course there's no reason why you need to use middleware in order to solve
this. The headers can be set directly in the
[handler](/docs/getting-started/custom-handlers) as well.
[handler](/docs/1.x/getting-started/custom-handlers) as well.
@@ -3,8 +3,8 @@ description: |
Sometimes URL based routing isn't enough.
---
The page on [routing](/docs/concepts/routing) hints at complex routing based on
URL patterns using a `RouteConfig` object. Let's dive into this in a bit more
The page on [routing](/docs/1.x/concepts/routing) hints at complex routing based
on URL patterns using a `RouteConfig` object. Let's dive into this in a bit more
detail.
A `RouteConfig` has a `routeOverride` string property, which makes use of the
@@ -10,7 +10,7 @@ will now install the Tailwind CSS plugin instead of twind like it did before.
## Requirements before migrating
The tailwind plugin requires Fresh's
[ahead of time builds](/docs/concepts/ahead-of-time-builds) to be set up,
[ahead of time builds](/docs/1.x/concepts/ahead-of-time-builds) to be set up,
otherwise it won't work. Make sure to switch your projects to ahead of time
builds in your project before continuing this guide. If your project is already
configured to use ahead of time builds, then you're good to go.
+83
View File
@@ -0,0 +1,83 @@
---
description: |
How to render raw HTML in Fresh.
---
Text content in Fresh is always escaped, whether serverside rendered or rendered
in islands. While this generally desired, it can create issues in certain
situations.
## Warning
The TL;DR is to use Preact's `dangerouslySetInnerHTML`. As the name implies, it
should not be used lightly.
Setting arbitrary HTML can be dangerous. Make sure you trust the source.
Rendering user-supplied HTML to the DOM makes your site vulnerable to cross-
site scripting. The markup must first be sanitizied, or better yet, something
you trust.
## Example: Rendering JSON-LD
Suppose we need to add some microdata markup to a page. The following will
result in **escaped characters, and will not work**:
```tsx components/json-ld.tsx
const json = `
{
"@context": "http://schema.org",
"@type": "PostalAddress",
"streetAddress": "8888 University Drive",
"addressLocality": "Burnaby",
"addressRegion": "British Columbia"
}
`;
export default function JsonLd() {
return <script type="application/ld+json">{json}</script>;
}
```
Instead, we can use `dangerouslySetInnerHTML`:
```tsx components/json-ld.tsx
export default function JsonLd() {
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: json }}
/>
);
}
```
## Another example: Code highlighting
Syntax highlighters parse strings into HTML tags, allowing them to be
individually styled with CSS. We can build a simple Preact syntax highlighter
like so:
```tsx components/code.tsx
import Prism from "https://esm.sh/prismjs@1.29.0";
interface Props {
code: string;
lang: string;
}
export default function Code({ code, lang }: Props) {
const parsed = Prism.highlight(code, Prism.languages[lang], lang);
return (
<pre data-lang={lang} className={`language-${lang}`}>
<code
dangerouslySetInnerHTML={{
__html: parsed,
}}
/>
</pre>
);
}
```
Of course, we will also have to add some CSS to make this look nice.
@@ -122,4 +122,4 @@ export interface FreshConfig {
```
For more on how these work, see the page about
[server configuration](/docs/concepts/server-configuration).
[server configuration](/docs/1.x/concepts/server-configuration).
@@ -51,8 +51,8 @@ The new page will be visible at `http://localhost:8000/about`.
[_Concepts: Routes_][concepts-routes] documentation page. The following
pages in the _Getting Started_ guide will also explain more features of routes. -->
[concepts-routing]: /docs/concepts/routing
[concepts-routing]: /docs/1.x/concepts/routing
[jsx]: https://react.dev/learn/writing-markup-with-jsx
[preact]: https://preactjs.com/
<!-- [concepts-routes]: /docs/concepts/routes -->
<!-- [concepts-routes]: /docs/1.x/concepts/routes -->
@@ -47,4 +47,4 @@ Navigating to `http://localhost:8000/greet/Luca` will now render a page showing
The [_Concepts: Routing_][concepts-routing] page has more information about
dynamic routes, especially about how to create more advanced dynamic routes.
[concepts-routing]: /docs/concepts/routing
[concepts-routing]: /docs/1.x/concepts/routing
@@ -75,5 +75,5 @@ rendering.
<!-- TODO(lucacasonato): link to todo app example when that is built again -->
[custom-handlers]: /docs/getting-started/custom-handlers
[concepts-forms]: /docs/concepts/forms
[custom-handlers]: /docs/1.x/getting-started/custom-handlers
[concepts-forms]: /docs/1.x/concepts/forms
+16
View File
@@ -0,0 +1,16 @@
---
description: |
In this chapter of the Fresh documentation, you'll be introduced to the
framework. Create a new project, run it locally, edit and create pages, fetch
data, handle user interactions, and deploy it.
---
In this chapter of the Fresh documentation, you'll be introduced to the
framework. You'll learn how to create a new project, run it locally, edit and
create pages, fetch data, handle user interactions, and how to then deploy the
project to [Deno Deploy](https://deno.com/deploy).
The documentation assumes you have the latest version
[Deno](https://docs.deno.com/runtime/#install-deno) installed on your system and
set up your
[Editor to work with Deno](https://docs.deno.com/runtime/getting_started/setup_your_environment/).
+35
View File
@@ -0,0 +1,35 @@
---
description: |
Fresh is a full stack modern web framework for JavaScript and TypeScript
developers, designed to build high-quality, performant,
and personalized web applications.
---
Fresh is a full stack modern web framework for JavaScript and TypeScript
developers. It's designed for building high-quality, performant, and
personalized web applications. You can use it to create your home page, a blog,
an e-commerce shop, a large web application like GitHub or Twitter and more.
At its core, Fresh is a combination of a routing framework and templating engine
that renders pages on demand on the server. These server rendered pages can
contain areas that are made interactive on the client (also known as the
[Island Architecture](https://jasonformat.com/islands-architecture)). Fresh uses
[Preact][preact] as the JSX rendering engine.
Fresh projects can be deployed manually to any platform with [Deno][deno], but
it is intended to be deployed to an edge runtime like [Deno Deploy][deno-deploy]
for the best experience.
Some stand out features:
- Zero config necessary
- Tiny & fast (no client JS is required by the framework)
- Optional client side hydration of individual components
- Highly resilient because of progressive enhancement and use of native browser
features
- TypeScript out of the box
- File-system routing à la Next.js
[preact]: https://preactjs.com
[deno]: https://deno.com
[deno-deploy]: https://deno.com/deploy
-36
View File
@@ -1,36 +0,0 @@
---
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
-135
View File
@@ -1,135 +0,0 @@
---
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 main.tsx
import { App, staticFiles } from "fresh";
import MyIsland from "./islands/my-island.tsx";
const app = new App()
.use(staticFiles())
.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`, `undefined`, and
`null`
- `Infinity`, `-Infinity`, `-0`, and `NaN`
- `Uint8Array`
- `URL`
- `Date`
- `RegExp`
- `JSX` Elements
- Collections `Map` and `Set`
- 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 routes/example.tsx
> export default function () {
> // WRONG
> return <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 { staticFiles } from "fresh";
import MyIsland from "../islands/my-island.tsx";
const app = new App()
.use(staticFiles())
.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 islands/other-island.tsx
export default (props: { foo: string }) => <>{props.foo}</>;
```
```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>;
}
```
-89
View File
@@ -1,89 +0,0 @@
---
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 main.ts
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 middleware/my-middleware.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
- [csrf()](/docs/canary/plugins/cors) - Set CSRF 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 middleware2 = define.middleware(async (ctx) => {
console.log("B");
return await ctx.next();
});
export default [middleware1, middleware2];
```
-32
View File
@@ -1,32 +0,0 @@
---
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 main.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.
-52
View File
@@ -1,52 +0,0 @@
---
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 main.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.
```tsx main.tsx
// Caching headers will be automatically added
app.get("/user", (ctx) => ctx.render(<img src="/user.png" />));
```
You can always opt out of this behaviour per tag, by adding the
`data-fresh-disable-lock` attribute.
```tsx main.tsx
// Opt-out of automatic caching headers
app.get(
"/user",
(ctx) => ctx.render(<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.
```tsx routes/about.tsx
import { asset } from "fresh/runtime";
export default function About() {
// Adding caching headers manually
return <a href={asset("/brochure.pdf")}>View brochure</a>;
}
```
-48
View File
@@ -1,48 +0,0 @@
---
description: |
Style active links with ease in Fresh
---
Fresh automatically enhances the accessibility of `<a>` elements by adding the
aria-current attribute when rendering links that match the current URL. This
attribute is recognized by assistive technologies and clearly indicates the
current page within a set of pages.
- `aria-current="page"` - Added to links with an exact path match, enhancing
accessibility by indicating the current page to assistive technologies.
As we aim to improve accessibility, we encourage the use of aria-current for
styling current links where applicable.
## Styling with CSS
The aria-current attribute is easily styled with CSS using attribute selectors,
providing a native way to visually differentiate the active link.
```css static/styles.css
/* Give links pointing to the current page a green color */
a[aria-current="page"] {
color: green;
}
/* Color all ancestor links of the current page */
a[aria-current="true"] {
color: peachpuff;
}
```
## Tailwindcss
In Tailwindcss or similar CSS frameworks, you can apply styles to elements with
the `aria-current` attribute using bracket notation in your class definitions.
For Tailwindcss, use the syntax:
```tsx components/Menu.tsx
function Menu() {
return (
<a href="/foo" class="aria-[current]:text-green-600">
Link to some page
</a>
);
}
```
@@ -1,32 +0,0 @@
---
description: |
How to render raw HTML in Fresh.
---
Text content in Fresh is always escaped, whether serverside rendered or rendered
in islands. While this generally desired, it can create issues in certain
situations.
To address this you can render raw HTML via Preact's `dangerouslySetInnerHTML`
prop:
```tsx routes/dynamic-html.tsx
<div dangerouslySetInnerHTML={{ __html: "<h1>This is raw HTML</h1>" }} />;
```
This will output:
```html Response body
<div>
<h1>This is raw HTML</h1>
</div>
```
A common use case for rendering raw HTML is syntax highlighting code blocks or
rendering markdown.
> [warn]: Setting arbitrary HTML can be dangerous, hence the
> `dangerouslySetInnerHTML` naming. Make sure you trust the source. Rendering
> user-supplied HTML to the DOM makes your site vulnerable to cross- site
> scripting. The markup must first be sanitizied, or better yet, something you
> trust.
-128
View File
@@ -1,128 +0,0 @@
---
description: |
In this chapter of the Fresh documentation, you'll be introduced to the
framework. Create a new project, run it locally, edit and create pages, fetch
data, handle user interactions, and deploy it.
---
Let's set up your first Fresh project. To create a new project, run this
command:
```sh Terminal
deno run -Ar jsr:@fresh/init
```
This will span a short wizard that guides you through the setup, like the
project name, if you want to use tailwindcss and if you're using vscode. Your
project folder should look like this:
```txt-files Project structure
<project root>
├── components/ # Store other components here. Can be named differently
│ └── Button.tsx
├── islands/ # Components that need JS to run client-side
│ └── Counter.tsx
├── routes/ # File system based routes
│   ├── api/
│   │ └── [name].tsx # API route for /api/:name
│   ├── _app.tsx # Renders the outer <html> content structure
│   └── index.tsx # Renders /
├── static/ # Contains static assets like css, logos, etc
│   └── ...
│
├── client.ts # Client entry file that's loaded on every page.
├── main.ts # The server entry file of your app
├── deno.json # Contains dependencies, tasks, etc
└── vite.config.ts # Vite configuration file
```
Run the `dev` task to launch your app in development mode:
```sh Terminal
deno task dev
```
Go to the URL printed in the terminal to view your app.
![Screenshot of the newly initialized Fresh app showing a counter](/docs/getting-started-1-init.jpg)
## Creating our first route
Let's create a new about page at `/about`. We can do that by adding a new file
at `routes/about.tsx`.
```tsx routes/about.tsx
import { define } from "../utils.ts";
export default define.page(() => {
return (
<main>
<h1>About</h1>
<p>This is the about page.</p>
</main>
);
});
```
If we navigate to `/about` in the browser we'll see our newly created page.
![Screenshot of the /about route](/docs/getting-started-2-about.png)
## Create an island
We're going to create a countdown component that requires JavaScript to function
in the browser.
Create a new file at `islands/Countdown.tsx`
```tsx islands/Countdown.tsx
import { useSignal } from "@preact/signals";
import { useEffect } from "preact/hooks";
export function Countdown(props: { target: string }) {
const count = useSignal(10);
useEffect(() => {
const timer = setInterval(() => {
if (count.value <= 0) {
clearInterval(timer);
}
count.value -= 1;
}, 1000);
return () => clearInterval(timer);
}, []);
if (count.value <= 0) {
return <p>Countdown: 🎉</p>;
}
return <p>Countdown: {count}</p>;
}
```
Let's add the countdown to our about page:
```tsx routes/about.tsx
import { define } from "../utils.ts";
import { Countdown } from "../islands/Countdown.tsx";
export default define.page(() => {
return (
<main>
<h1>About</h1>
<p>This is the about page.</p>
<Countdown />
</main>
);
});
```
Now, we can see our countdown in action:
![Screenshot of the countdown component](/docs/getting-started-3-cotuntdown.png)
## Next steps
TODO
-75
View File
@@ -1,75 +0,0 @@
---
description: |
Fresh is a full stack modern web framework for JavaScript and TypeScript
developers, designed to build high-quality, performant,
and personalized web applications.
---
Fresh is a small, fast and extensible full stack web framework built on Web
Standards. It's designed for building high-quality, performant, and personalized
web applications.
```tsx main.tsx
import { App } from "fresh";
const app = new App()
.get("/", () => new Response("hello world"))
.get("/jsx", (ctx) => ctx.render(<h1>render JSX!</h1>));
app.listen();
```
## Quick Start
Create a new Fresh app by running:
```sh Terminal
deno run -Ar jsr:@fresh/init
```
## Features
The core idea powering Fresh is to render server generated HTML pages and only
ship JavaScript for areas in the page that need to be interactive. This is often
referred to as the
[Island Architecture](https://jasonformat.com/islands-architecture).
- **Fast** 🚀 - Rendering is super fast thanks to [Preact][preact] and Deno's
[`precompile` transform](https://docs.deno.com/runtime/reference/jsx/#jsx-precompile-transform)
- **Lightweight** 🏎️ - Only ship the JavaScript you need
- **Extensible** 🧩 - Nearly every aspect can be customized
- **Powerful & small API** 🤗 - Familiar APIs make you productive quickly
- **Built-in OpenTelemetry** 📈 - Built-in support for OpenTelemetry
## When to use Fresh
Fresh is ideal for sites and apps that are primarily server rendered, like a
home page, an e-commerce shop or something like GitHub or Bluesky.
- Web APIs
- E-Commerce shops
- Portfolio sites
- Landing pages & Documentation
- CRUD apps
That said, if you want to build a Single-Page-App (=SPA), then Fresh is not the
right framework.
## Who is using Fresh?
Fresh powers [deno.com](https://deno.com) and [Deno Deploy][deno-deploy] among
many other projects at Deno. It's also used by [deco.cx](https://deco.cx/) for
e-commerce projects.
## Where to host Fresh apps?
Fresh is most often deployed on [Deno Deploy][deno-deploy] where it can be
deployed with 1-click and has out of the box integrations with metrics among
other things.
Fresh projects can be deployed manually to any platform with [Deno][deno] like
via docker containers too.
[preact]: https://preactjs.com
[deno]: https://deno.com
[deno-deploy]: https://deno.com/deploy
@@ -26,8 +26,8 @@ function AppWrapper({ Component }) {
app.appWrapper(AppWrapper);
```
Every [`ctx.render()`](/docs/canary/concepts/context#render-1) call will include
the app wrapper component by default, unless opted out.
Every [`ctx.render()`](/docs/concepts/context#render-1) call will include the
app wrapper component by default, unless opted out.
Note that only one app wrapper component is supported per
[`App`](/docs/canary/concepts/app) instance.
[`App`](/docs/concepts/app) instance.
@@ -18,7 +18,7 @@ Fresh supports two kind of error pages:
## Generic error pages
To add an error page use [`app.onError()`](/docs/canary/concepts/app#onerror).
To add an error page use [`app.onError()`](/docs/concepts/app#onerror).
```ts main.ts
const app = new App()
@@ -36,7 +36,7 @@ const app = new App()
## `.use()`
Add one or more [middlewares](/docs/canary/concepts/middleware). Middlewares are
Add one or more [middlewares](/docs/concepts/middleware). Middlewares are
matched left to right.
```ts
@@ -261,14 +261,13 @@ 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.
Set the [App Wrapper](/docs/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.
Set a [Layout](/docs/advanced/layouts) component at the specified path. The app
wrapper component and prior layouts are inherited by default unless opted out.
## `.onError()`
@@ -3,12 +3,12 @@ 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.
---
Use the `.fsRoutes()` helper on the [`App`](/docs/canary/concepts/app) instance
to specify where file based routes should be inserted. It adds routes based on
the structure in the `routes/` folder in your project (or any other folder you
have specified when instantiating the
[`fresh()` vite plugin](/docs/canary/advanced/vite). in `vite.config.ts`). When
you add a new file there, it will register a new route automatically.
Use the `.fsRoutes()` helper on the [`App`](/docs/concepts/app) instance to
specify where file based routes should be inserted. It adds routes based on the
structure in the `routes/` folder in your project (or any other folder you have
specified when instantiating the [`fresh()` vite plugin](/docs/advanced/vite).
in `vite.config.ts`). When you add a new file there, it will register a new
route automatically.
```ts main.ts
import { App, staticFiles } from "fresh";
@@ -86,7 +86,7 @@ export const config: RouteConfig = {
## Route Groups
When working with [layouts](/docs/concepts/layouts) or
When working with [layouts](/docs/advanced/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.
+31 -3
View File
@@ -3,6 +3,34 @@ description: |
This chapter goes over some fundamental concepts of Fresh.
---
This chapter goes over some fundamental concepts of Fresh. It covers the
overarching architecture design of Fresh applications, as well as reference
documentation about the various features 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/concepts/app) - Holds all the information about your app, like
routes, etc
- [**Middleware**](/docs/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/concepts/context) - Passed through every middleware. Use
this to share state, trigger redirects or render HTML.
- [**Routes**](/docs/concepts/routing) - Responds to a particular URL and runs
as chain of middlewares if it matches
- [**Islands**](/docs/concepts/islands) - Render interactive Preact components
on the client
Advanced concepts:
- [**App wrapper**](/docs/advanced/app-wrapper) - Responsible for the outer HTML
structure, usually up to the `<body>`-tag
- [**Layouts**](/docs/advanced/layouts) - Re-use a shared layout when calling
`ctx.render()` across routes
- [**Partials**](/docs/advanced/partials) - Stream in server generated content
on the current page
+65 -158
View File
@@ -3,14 +3,12 @@ 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. Islands are isolated Preact
components that are rendered on the server and then hydrated on the client. This
is different from all other components in Fresh, as they are usually rendered on
the server only.
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 in a Fresh
project. The name of this file must be a PascalCase or kebab-case name of the
island.
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";
@@ -20,127 +18,74 @@ export default function MyIsland() {
return (
<div>
Counter is at {count}.{" "}
<p>Count: {count}</p>
<button onClick={() => (count.value += 1)}>+</button>
</div>
);
}
```
An island can be used in a page like a regular Preact component. Fresh will take
care of automatically re-hydrating the island on the client.
An island can be used anywhere like a regular Preact component. Fresh will take
care of making it interactive on the client.
```tsx route/index.tsx
import MyIsland from "../islands/my-island.tsx";
```tsx main.tsx
import { App, staticFiles } from "fresh";
import MyIsland from "./islands/my-island.tsx";
export default function Home() {
return <MyIsland />;
}
const app = new App()
.use(staticFiles())
.get("/", (ctx) => ctx.render(<MyIsland />));
```
## Passing JSX to islands
Islands support passing JSX elements via the `children` property.
```tsx islands/my-island.tsx
import { useSignal } from "@preact/signals";
import { ComponentChildren } from "preact";
interface Props {
children: ComponentChildren;
}
export default function MyIsland({ children }: Props) {
const count = useSignal(0);
return (
<div>
Counter is at {count}.{" "}
<button onClick={() => (count.value += 1)}>+</button>
{children}
</div>
);
}
```
This allows you to pass static content rendered by the server to an island in
the browser.
```tsx routes/index.tsx
import MyIsland from "../islands/my-island.tsx";
export default function Home() {
return (
<MyIsland>
<p>This text is rendered on the server</p>
</MyIsland>
);
}
```
You can also create shared components in your `components/` directory, which can
be used in both static content and interactive islands. When these components
are used within islands, interactivity can be added, such as `onClick` handlers
(using an `onClick` handler on a button outside of an island will not fire).
```tsx islands/my-island.tsx
import { useSignal } from "@preact/signals";
import { ComponentChildren } from "preact";
import Card from "../components/Card.tsx";
import Button from "../components/Button.tsx";
interface Props {
children: ComponentChildren;
}
export default function MyIsland({ children }: Props) {
const count = useSignal(0);
return (
<Card>
Counter is at {count}.{" "}
<Button onClick={() => (count.value += 1)}>+</Button>
{children}
</Card>
);
}
```
## Passing other props to islands
## 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`, `boolean`, `bigint`, and `null`
- Most `number`s (`Infinity`, `-Infinity`, and `NaN` are silently converted to
`null`)
- Primitive types `string`, `number`, `boolean`, `bigint`, `undefined`, and
`null`
- `Infinity`, `-Infinity`, `-0`, and `NaN`
- `Uint8Array`
- `URL`
- `Date`
- `RegExp`
- `JSX` Elements
- Collections `Map` and `Set`
- Plain objects with string keys and serializable values
- Arrays containing serializable values
- Uint8Array
- JSX Elements (restricted to `props.children`)
- 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. Passing complex objects like `Date`, custom classes, or
functions is not supported.
deserialization.
During server side rendering, Fresh annotates the HTML with special comments
that indicate where each island will go. This gives the code sent to the client
enough information to put the islands where they are supposed to go without
requiring hydration for the static children of interactive islands. No
Javascript is sent to the client when no interactivity is needed.
> [warn]: Passing functions to an island is not supported.
>
> ```tsx routes/example.tsx
> export default function () {
> // WRONG
> return <MyIsland onClick={() => console.log("hey")} />;
> }
> ```
```html Response body
<!--frsh-myisland_default:default:0-->
<div>
Counter is at 0.
<button>+</button>
<!--frsh-slot-myisland_default:children-->
<p>This text is rendered on the server</p>
<!--/frsh-slot-myisland_default:children-->
</div>
<!--/frsh-myisland_default:default:0-->
### 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 { staticFiles } from "fresh";
import MyIsland from "../islands/my-island.tsx";
const app = new App()
.use(staticFiles())
.get("/", (ctx) => {
return ctx.render(
<MyIsland jsx={<h1>hello</h1>}>
<p>This text is rendered on the server</p>
</MyIsland>,
);
});
```
### Nesting islands
@@ -149,73 +94,35 @@ 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.
```tsx islands/other-island.tsx
import { useSignal } from "@preact/signals";
import { ComponentChildren } from "preact";
interface Props {
children: ComponentChildren;
foo: string;
}
function randomNumber() {
return Math.floor(Math.random() * 100);
}
export default function OtherIsland({ children, foo }: Props) {
const number = useSignal(randomNumber());
return (
<div>
<p>String from props: {foo}</p>
<p>
<button onClick={() => (number.value = randomNumber())}>Random</button>
{" "}
number is: {number}.
</p>
</div>
);
}
```
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 islands/other-island.tsx
export default (props: { foo: string }) => <>{props.foo}</>;
```
```tsx route/index.tsx
import MyIsland from "../islands/my-island.tsx";
import OtherIsland from "../islands/other-island.tsx";
export default function Home() {
return (
<div>
<MyIsland>
<OtherIsland foo="this prop will be serialized" />
</MyIsland>
<p>Some more server rendered text</p>
</div>
);
}
// 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 like:
```
An error occurred during route handling or page rendering. ReferenceError: EventSource is not defined
at Object.MyIsland (file:///Users/someuser/fresh-project/islandsmy-island.tsx:6:18)
at m (https://esm.sh/v129/preact-render-to-string@6.2.0/X-ZS8q/denonext/preact-render-to-string.mjs:2:2602)
at m (https://esm.sh/v129/preact-render-to-string@6.2.0/X-ZS8q/denonext/preact-render-to-string.mjs:2:2113)
....
```
Use the [`IS_BROWSER`](https://deno.land/x/fresh/runtime.ts?doc=&s=IS_BROWSER)
flag as a guard to fix the issue:
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.ts";
import { IS_BROWSER } from "fresh/runtime";
export function MyIsland() {
// Return any prerenderable JSX here which makes sense for your island
+10 -30
View File
@@ -26,16 +26,16 @@ 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";
import { define } from "../../utils.ts";
export default function Layout({ Component, state }: PageProps) {
export default define.layout({ Component, state }) => {
// do something with state here
return (
<div class="layout">
<Component />
</div>
);
}
})
```
## Async layouts
@@ -44,33 +44,12 @@ 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";
import { define } from "../../utils.ts";
export default async function Layout(req: Request, ctx: FreshContext) {
export default define.layout(async (ctx) => {
// 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 routes/greet/_layout.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>
@@ -99,21 +78,22 @@ 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";
import { type RouteConfig } from "fresh";
import { define } from "../../utils.ts";
export const config: RouteConfig = {
skipInheritedLayouts: true, // Skip already inherited layouts
};
export default function MyPage() {
export default define.layout(() => {
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";
import { type LayoutConfig } from "fresh";
export const config: LayoutConfig = {
skipInheritedLayouts: true, // Skip already inherited layouts
+79 -213
View File
@@ -3,220 +3,86 @@ description: |
Add middleware routes to intercept requests or responses for analytics purposes, access control, or anything else.
---
A middleware is defined in a `_middleware.ts` file. It will intercept the
request in order for you to perform custom logic before or after the route
handler. This allows modifying or checking requests and responses. Common
use-cases for this are logging, authentication, and performance monitoring.
A middleware is a function that receives a [`Context`](/docs/concepts/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.
Each middleware gets passed a `next` function in the context argument that is
used to trigger child handlers. The `ctx` also has a `state` property that can
be used to pass arbitrary data to downstream (or upstream) handlers. This
`state` is included in `PageProps` by default, which is available to both the
special [\_app](/docs/concepts/app-wrapper.md) wrapper and normal
[routes](/docs/concepts/routes.md). `ctx.state` is normally set by modifying its
properties, e.g. `ctx.state.loggedIn = true`, but you can also replace the
entire object like `ctx.state = { loggedIn: true }`.
```ts routes/_middleware.ts
import { FreshContext } from "$fresh/server.ts";
interface State {
data: string;
}
export async function handler(
req: Request,
ctx: FreshContext<State>,
) {
ctx.state.data = "myData";
const resp = await ctx.next();
resp.headers.set("server", "fresh server");
return resp;
}
```
```ts routes/myHandler.ts
export const handler: Handlers<any, { data: string }> = {
GET(_req, ctx) {
return new Response(`middleware data is ${ctx.state.data}`);
},
};
```
Middlewares are scoped and can be layered. This means a project can have
multiple middlewares, each covering a different set of routes. If multiple
middlewares cover a route, they will all be run, in order of specificity (least
specific first).
For example, take a project with the following routes:
```txt-files Project Structure
└── <root>/routes
   ├── _middleware.ts
   ├── index.ts
   └── admin
      ├── _middleware.ts
      └── index.ts
      └── signin.ts
```
For a request to `/` the request will flow like this:
1. The `routes/_middleware.ts` middleware is invoked.
2. Calling `ctx.next()` will invoke the `routes/index.ts` handler.
For a request to `/admin` the request flows like this:
1. The `routes/_middleware.ts` middleware is invoked.
2. Calling `ctx.next()` will invoke the `routes/admin/_middleware.ts`
middleware.
3. Calling `ctx.next()` will invoke the `routes/admin/index.ts` handler.
For a request to `/admin/signin` the request flows like this:
1. The `routes/_middleware.ts` middleware is invoked.
2. Calling `ctx.next()` will invoke the `routes/admin/_middleware.ts`
middleware.
3. Calling `ctx.next()` will invoke the `routes/admin/signin.ts` handler.
A single middleware file can also define multiple middlewares (all for the same
route) by exporting an array of handlers instead of a single handler. For
example:
```ts routes/_middleware.ts
export const handler = [
async function middleware1(req, ctx) {
// do something
```tsx main.ts
const app = new App<{ greeting: string }>()
.use((ctx) => {
// Middleware to pass data
ctx.state.greeting = "Hello world";
return ctx.next();
},
async function middleware2(req, ctx) {
// do something
return ctx.next();
},
];
```
It should be noted that `middleware` has access to route parameters. If you're
running a fictitious `routes/[tenant]/admin/_middleware.ts` like this:
```ts routes/[tenant]/admin/_middleware.ts
import { FreshContext } from "$fresh/server.ts";
export async function handler(_req: Request, ctx: FreshContext) {
const currentTenant = ctx.params.tenant;
// do something with the tenant
const resp = await ctx.next();
return resp;
}
```
and the request is to `mysaas.com/acme/admin/`, then `currentTenant` will have
the value of `acme` in your middleware.
## Middleware Destination
To set the stage for this section, let's focus on the part of `FreshContext`
that looks like this:
```ts fresh 🍋
export interface FreshContext<State = Record<string, unknown>> {
...
next: () => Promise<Response>;
state: State;
destination: router.DestinationKind;
remoteAddr: {
transport: "tcp" | "udp";
hostname: string;
port: number;
};
...
}
```
and `router.DestinationKind` is defined like this:
```ts fresh 🍋
export type DestinationKind = "internal" | "static" | "route" | "notFound";
```
This is useful if you want your middleware to only run when a request is headed
for a `route`, as opposed to something like `http://localhost:8001/favicon.ico`.
### Example
Initiate a new Fresh project (`deno run -A -r https://fresh.deno.dev/`) and then
create a `_middleware.ts` file in the `routes` folder like this:
```ts routes/_middleware.ts
import { FreshContext } from "$fresh/server.ts";
export async function handler(req: Request, ctx: FreshContext) {
console.log(ctx.destination);
console.log(req.url);
const resp = await ctx.next();
return resp;
}
```
If you start up your server (`deno task start`) you'll see the following:
```sh Terminal
Task start deno run -A --watch=static/,routes/ dev.ts
Watcher Process started.
The manifest has been generated for 4 routes and 1 islands.
🍋 Fresh ready
Local: http://localhost:8000/
route
http://localhost:8000/
internal
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/deserializer.js
internal
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/signals.js
internal
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/plugin-twind-main.js
internal
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/main.js
internal
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/island-counter.js
internal
http://localhost:8000/_frsh/refresh.js
static
http://localhost:8000/logo.svg?__frsh_c=3c7400558fc00915df88cb181036c0dbf73ab7f5
internal
http://localhost:8000/_frsh/alive
internal
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/chunk-PDMKJVJ5.js
internal
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/chunk-UGFDDSOV.js
internal
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/chunk-RCK7U3UF.js
```
That first `route` request is for when `Fresh` responds with the root level
`index.tsx` route. The rest, as you can see, are either `internal` or `static`
requests. You can use `ctx.destination` to filter these out if your middleware
is only supposed to deal with routes.
## Middleware Redirects
If you want to redirect a request from a middleware, you can do so by returning:
```ts routes/_middleware.ts
export function handler(req: Request): Response {
return Response.redirect("https://example.com", 307);
}
```
`307` stands for temporary redirect. You can also use `301` for permanent
redirect. You can also redirect to a relative path by doing:
```ts routes/_middleware.ts
export function handler(req: Request): Response {
return new Response("", {
status: 307,
headers: { Location: "/my/new/relative/path" },
})
.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 middleware/my-middleware.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/plugins/cors) - Set CORS HTTP headers
- [csrf()](/docs/plugins/cors) - Set CSRF HTTP headers
- [trailingSlash()](/docs/plugins/trailing-slashes) - Enforce trailing slashes
## Filesystem-based middlewares
With file system based routing you can define a middleware in a `_middleware.ts`
file inside the `routes/` folder or any of it's subfolders.
```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 middleware2 = define.middleware(async (ctx) => {
console.log("B");
return await ctx.next();
});
export default [middleware1, middleware2];
```
+24 -143
View File
@@ -3,149 +3,30 @@ description: |
File based routing is the simplest way to do routing in Fresh apps. Additionally custom patterns can be configured per route.
---
Routing is the mechanism that determines what route a given incoming request is
handled by. Fresh routes requests based on their URL path. By default routes
specify which paths they are invoked for using the name of the file. Routes can
also define a custom [URL pattern][urlpattern] to match against for more
advanced use cases.
Routing defines which middlewares and routes should respond to a particular
request.
The file based routing in Fresh is very similar to the file based routing seen
in other frameworks, namely Next.js. File names are used to determine which
route a given request should be handled by. The pattern is determined based on
the path of the file on disk, relative to the `routes/` directory.
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/x.ts
import { RouteConfig } from "$fresh/server.ts";
export const config: RouteConfig = {
routeOverride: "/x/:module@:version/:path*",
};
// ...
```ts main.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");
});
```
## 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 Example page layout
/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-files Project structure
<project root>
└── 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-files Project structure
└── <root>/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-files Project structure
> └── <root>/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
## Co-location
If you want to store components and islands closer to their routes, you may want
to use co-location.
When the name of a route group folder starts with an underscore, like
`(_components)`, Fresh will ignore that folder and it’s effectively treated as
private. This means you can use these private route folders to store components
related to a particular route.
Following the above example, say you have some components you only want to use
in your marketing pages, you could create a route group folder `(_components)`
to house these.
The one special name is `(_islands)` which tells Fresh to treat all files in
that folder as an island.
```txt-files Project structure
└── <root>/routes
   ├── (marketing)
   │ ├── _layout.tsx
   │ ├── about.tsx
   │ ├── career.tsx
│ ├── (_components)
   │ │ └── newsletter-cta.tsx
│ └── (_islands)
   │ └── interactive-stats.tsx # Fresh treats this as an island
   └── shop
├── (_components)
   │ └── product-card.tsx
└── (_islands)
   └── cart.tsx # Fresh treats this as an island
```
Combined together, this gives you the ability to organise your code on a feature
basis and put all related components, islands or anything else into a shared
folder.
Fresh supports the full
[`URLPattern`](https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API)
syntax for setting pathnames.
-17
View File
@@ -1,17 +0,0 @@
---
description: |
Fresh's architecture is designed to leverage server components by default.
---
If you've read about Fresh's [architecture](/docs/concepts/architecture) then
you know that it's based on the islands architecture pattern. The flip side of
this is that everything else is, by default, a server component. When you
[create a route](/docs/getting-started/create-a-route), all of the components
used are rendered on the server. No JavaScript is sent to the client, unless you
specifically include something from the `/islands/` folder.
Internally, Fresh's rendering heavily leverages
[preact-render-to-string](https://github.com/preactjs/preact-render-to-string).
This is the exact library mentioned on Preact's
[Server-Side Rendering](https://preactjs.com/guide/v10/server-side-rendering/)
article.
+38 -41
View File
@@ -3,53 +3,50 @@ description: |
Fresh has built-in support for serving static files. This is useful for serving images, CSS, and other static assets.
---
Fresh automatically serves static assets placed in a `static/` directory in the
project root. These assets are served at the root of the webserver, with a
higher priority than routes. This means that if a given request matches a file
in the `static/` folder, it is always served, even if there is a route that
would also match the request.
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.
Static asset responses automatically get a `content-type` header assigned based
on the file extension of the file on disk. Assets are also automatically
streamed from disk to the client to improve performance and efficiency for both
user and server.
```ts main.ts
import { staticFiles } from "fresh";
Fresh also adds an `etag` header to assets automatically and handles the
`If-None-Match` header for incoming requests.
const app = new App()
.use(staticFiles());
```
### Caching
## Caching headers
By default, no caching headers are added to assets. This can be disadvantageous
in many scenarios, so Fresh makes it easy to serve assets with long cache
lifetimes too.
By default, Fresh adds caching headers for the `src` and `srcset` attributes on
`<img>` and `<source>` tags.
The first approach to do this is manual. The client runtime exports an `asset`
function that takes an absolute path to the static asset and returns a "locked"
version of this path that contains a build ID for cache busting. When the asset
is requested at this "locked" path, it will be served with a cache lifetime of
one year.
```tsx main.tsx
// Caching headers will be automatically added
app.get("/user", (ctx) => ctx.render(<img src="/user.png" />));
```
```tsx routes/page.tsx
import { asset } from "$fresh/runtime.ts";
You can always opt out of this behaviour per tag, by adding the
`data-fresh-disable-lock` attribute.
export default function Page() {
return (
<p>
<a href={asset("/brochure.pdf")}>View brochure</a>
</p>
);
```tsx main.tsx
// Opt-out of automatic caching headers
app.get(
"/user",
(ctx) => ctx.render(<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.
```tsx routes/about.tsx
import { asset } from "fresh/runtime";
export default function About() {
// Adding caching headers manually
return <a href={asset("/brochure.pdf")}>View brochure</a>;
}
```
Fresh also does this automatically for `src` and `srcset` attributes in `<img>`
and `<source>` HTML tags. These will automatically use "locked" paths if Fresh
deems it safe to do so. You can always opt out of this behaviour per tag, by
adding the `data-fresh-disable-lock` attribute.
```tsx routes/user.tsx
{/* Locked URL source */}
<img src="/user.png" />;
{/* Preserve URL source and disable lock */}
<img src="/user.png" data-fresh-disable-lock />;
```
+8 -39
View File
@@ -11,13 +11,13 @@ current page within a set of pages.
- `aria-current="page"` - Added to links with an exact path match, enhancing
accessibility by indicating the current page to assistive technologies.
As we aim to improve accessibility, we encourage the use of `aria-current` for
As we aim to improve accessibility, we encourage the use of aria-current for
styling current links where applicable.
## Styling with CSS
The `aria-current` attribute is easily styled with CSS using attribute
selectors, providing a native way to visually differentiate the active link.
The aria-current attribute is easily styled with CSS using attribute selectors,
providing a native way to visually differentiate the active link.
```css static/styles.css
/* Give links pointing to the current page a green color */
@@ -31,14 +31,13 @@ a[aria-current="true"] {
}
```
## Tailwind / Twind
## Tailwindcss
In Tailwind or similar CSS frameworks like Twind, you can apply styles to
elements with the aria-current attribute using bracket notation in your class
definitions. However, the specific syntax varies slightly between Tailwind and
Twind. For Tailwind, use the syntax:
In Tailwindcss or similar CSS frameworks, you can apply styles to elements with
the `aria-current` attribute using bracket notation in your class definitions.
For Tailwindcss, use the syntax:
```tsx component/Menu.tsx
```tsx components/Menu.tsx
function Menu() {
return (
<a href="/foo" class="aria-[current]:text-green-600">
@@ -47,33 +46,3 @@ function Menu() {
);
}
```
For Twind, the syntax is:
```tsx component/Menu.tsx
function Menu() {
return (
<a href="/foo" class="[aria-current]:text-green-600">
Link to some page
</a>
);
}
```
### Twind Plugin
The original twind plugin (`import twindPlugin from "$fresh/plugins/twind.ts";`)
supports the above style:
```tsx routes/page.tsx
class="[aria-current='page']:text-green-600"
```
### TwindV1 Plugin
The new twind plugin (`import twindPlugin from "$fresh/plugins/twindv1.ts";`)
requires a slightly different syntax (note the position of the left bracket):
```tsx routes/page.tsx
class="aria-[current='page']:text-green-600"
```
@@ -46,7 +46,7 @@ production.
### Replacing `dev.ts` with `vite.config.ts`
Delete `dev.ts` and create a `vite.config.ts` file instead. Pass your custom
Fresh configuration to the [fresh vite plugin](/docs/canary/advanced/vite).
Fresh configuration to the [fresh vite plugin](/docs/advanced/vite).
```ts vite.config.ts
import { defineConfig } from "vite";
@@ -217,9 +217,9 @@ Same is true for handlers:
All the various context interfaces have been consolidated and simplified:
| Fresh 1.x | Fresh 2.x |
| --------------------------------------------- | ------------------------------------------ |
| `AppContext`, `LayoutContext`, `RouteContext` | [`Context`](/docs/canary/concepts/context) |
| Fresh 1.x | Fresh 2.x |
| --------------------------------------------- | ----------------------------------- |
| `AppContext`, `LayoutContext`, `RouteContext` | [`Context`](/docs/concepts/context) |
### Context methods
@@ -281,7 +281,7 @@ const app = new App()
The `createHandler` function was often used to launch Fresh for tests. This can
be now done via vite's `createBuilder` function. See the
[testing page](/docs/canary/testing) for more information.
[testing page](/docs/testing) for more information.
## Getting help
+16 -67
View File
@@ -7,77 +7,26 @@ Text content in Fresh is always escaped, whether serverside rendered or rendered
in islands. While this generally desired, it can create issues in certain
situations.
## Warning
To address this you can render raw HTML via Preact's `dangerouslySetInnerHTML`
prop:
The TL;DR is to use Preact's `dangerouslySetInnerHTML`. As the name implies, it
should not be used lightly.
Setting arbitrary HTML can be dangerous. Make sure you trust the source.
Rendering user-supplied HTML to the DOM makes your site vulnerable to cross-
site scripting. The markup must first be sanitizied, or better yet, something
you trust.
## Example: Rendering JSON-LD
Suppose we need to add some microdata markup to a page. The following will
result in **escaped characters, and will not work**:
```tsx components/json-ld.tsx
const json = `
{
"@context": "http://schema.org",
"@type": "PostalAddress",
"streetAddress": "8888 University Drive",
"addressLocality": "Burnaby",
"addressRegion": "British Columbia"
}
`;
export default function JsonLd() {
return <script type="application/ld+json">{json}</script>;
}
```tsx routes/dynamic-html.tsx
<div dangerouslySetInnerHTML={{ __html: "<h1>This is raw HTML</h1>" }} />;
```
Instead, we can use `dangerouslySetInnerHTML`:
This will output:
```tsx components/json-ld.tsx
export default function JsonLd() {
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: json }}
/>
);
}
```html Response body
<div>
<h1>This is raw HTML</h1>
</div>
```
## Another example: Code highlighting
A common use case for rendering raw HTML is syntax highlighting code blocks or
rendering markdown.
Syntax highlighters parse strings into HTML tags, allowing them to be
individually styled with CSS. We can build a simple Preact syntax highlighter
like so:
```tsx components/code.tsx
import Prism from "https://esm.sh/prismjs@1.29.0";
interface Props {
code: string;
lang: string;
}
export default function Code({ code, lang }: Props) {
const parsed = Prism.highlight(code, Prism.languages[lang], lang);
return (
<pre data-lang={lang} className={`language-${lang}`}>
<code
dangerouslySetInnerHTML={{
__html: parsed,
}}
/>
</pre>
);
}
```
Of course, we will also have to add some CSS to make this look nice.
> [warn]: Setting arbitrary HTML can be dangerous, hence the
> `dangerouslySetInnerHTML` naming. Make sure you trust the source. Rendering
> user-supplied HTML to the DOM makes your site vulnerable to cross- site
> scripting. The markup must first be sanitizied, or better yet, something you
> trust.
+116 -8
View File
@@ -5,12 +5,120 @@ description: |
data, handle user interactions, and deploy it.
---
In this chapter of the Fresh documentation, you'll be introduced to the
framework. You'll learn how to create a new project, run it locally, edit and
create pages, fetch data, handle user interactions, and how to then deploy the
project to [Deno Deploy](https://deno.com/deploy).
Let's set up your first Fresh project. To create a new project, run this
command:
The documentation assumes you have the latest version
[Deno](https://docs.deno.com/runtime/#install-deno) installed on your system and
set up your
[Editor to work with Deno](https://docs.deno.com/runtime/getting_started/setup_your_environment/).
```sh Terminal
deno run -Ar jsr:@fresh/init
```
This will span a short wizard that guides you through the setup, like the
project name, if you want to use tailwindcss and if you're using vscode. Your
project folder should look like this:
```txt-files Project structure
<project root>
├── components/ # Store other components here. Can be named differently
│ └── Button.tsx
├── islands/ # Components that need JS to run client-side
│ └── Counter.tsx
├── routes/ # File system based routes
│   ├── api/
│   │ └── [name].tsx # API route for /api/:name
│   ├── _app.tsx # Renders the outer <html> content structure
│   └── index.tsx # Renders /
├── static/ # Contains static assets like css, logos, etc
│   └── ...
│
├── client.ts # Client entry file that's loaded on every page.
├── main.ts # The server entry file of your app
├── deno.json # Contains dependencies, tasks, etc
└── vite.config.ts # Vite configuration file
```
Run the `dev` task to launch your app in development mode:
```sh Terminal
deno task dev
```
Go to the URL printed in the terminal to view your app.
![Screenshot of the newly initialized Fresh app showing a counter](/docs/getting-started-1-init.jpg)
## Creating our first route
Let's create a new about page at `/about`. We can do that by adding a new file
at `routes/about.tsx`.
```tsx routes/about.tsx
import { define } from "../utils.ts";
export default define.page(() => {
return (
<main>
<h1>About</h1>
<p>This is the about page.</p>
</main>
);
});
```
If we navigate to `/about` in the browser we'll see our newly created page.
![Screenshot of the /about route](/docs/getting-started-2-about.png)
## Create an island
We're going to create a countdown component that requires JavaScript to function
in the browser.
Create a new file at `islands/Countdown.tsx`
```tsx islands/Countdown.tsx
import { useSignal } from "@preact/signals";
import { useEffect } from "preact/hooks";
export function Countdown(props: { target: string }) {
const count = useSignal(10);
useEffect(() => {
const timer = setInterval(() => {
if (count.value <= 0) {
clearInterval(timer);
}
count.value -= 1;
}, 1000);
return () => clearInterval(timer);
}, []);
if (count.value <= 0) {
return <p>Countdown: 🎉</p>;
}
return <p>Countdown: {count}</p>;
}
```
Let's add the countdown to our about page:
```tsx routes/about.tsx
import { define } from "../utils.ts";
import { Countdown } from "../islands/Countdown.tsx";
export default define.page(() => {
return (
<main>
<h1>About</h1>
<p>This is the about page.</p>
<Countdown />
</main>
);
});
```
Now, we can see our countdown in action:
![Screenshot of the countdown component](/docs/getting-started-3-cotuntdown.png)
+60 -20
View File
@@ -5,30 +5,70 @@ description: |
and personalized web applications.
---
Fresh is a full stack modern web framework for JavaScript and TypeScript
developers. It's designed for building high-quality, performant, and
personalized web applications. You can use it to create your home page, a blog,
an e-commerce shop, a large web application like GitHub or Twitter and more.
Fresh is a small, fast and extensible full stack web framework built on Web
Standards. It's designed for building high-quality, performant, and personalized
web applications.
At its core, Fresh is a combination of a routing framework and templating engine
that renders pages on demand on the server. These server rendered pages can
contain areas that are made interactive on the client (also known as the
[Island Architecture](https://jasonformat.com/islands-architecture)). Fresh uses
[Preact][preact] as the JSX rendering engine.
```tsx main.tsx
import { App } from "fresh";
Fresh projects can be deployed manually to any platform with [Deno][deno], but
it is intended to be deployed to an edge runtime like [Deno Deploy][deno-deploy]
for the best experience.
const app = new App()
.get("/", () => new Response("hello world"))
.get("/jsx", (ctx) => ctx.render(<h1>render JSX!</h1>));
Some stand out features:
app.listen();
```
- Zero config necessary
- Tiny & fast (no client JS is required by the framework)
- Optional client side hydration of individual components
- Highly resilient because of progressive enhancement and use of native browser
features
- TypeScript out of the box
- File-system routing à la Next.js
## Quick Start
Create a new Fresh app by running:
```sh Terminal
deno run -Ar jsr:@fresh/init
```
## Features
The core idea powering Fresh is to render server generated HTML pages and only
ship JavaScript for areas in the page that need to be interactive. This is often
referred to as the
[Island Architecture](https://jasonformat.com/islands-architecture).
- **Fast** 🚀 - Rendering is super fast thanks to [Preact][preact] and Deno's
[`precompile` transform](https://docs.deno.com/runtime/reference/jsx/#jsx-precompile-transform)
- **Lightweight** 🏎️ - Only ship the JavaScript you need
- **Extensible** 🧩 - Nearly every aspect can be customized
- **Powerful & small API** 🤗 - Familiar APIs make you productive quickly
- **Built-in OpenTelemetry** 📈 - Built-in support for OpenTelemetry
## When to use Fresh
Fresh is ideal for sites and apps that are primarily server rendered, like a
home page, an e-commerce shop or something like GitHub or Bluesky.
- Web APIs
- E-Commerce shops
- Portfolio sites
- Landing pages & Documentation
- CRUD apps
That said, if you want to build a Single-Page-App (=SPA), then Fresh is not the
right framework.
## Who is using Fresh?
Fresh powers [deno.com](https://deno.com) and [Deno Deploy][deno-deploy] among
many other projects at Deno. It's also used by [deco.cx](https://deco.cx/) for
e-commerce projects.
## Where to host Fresh apps?
Fresh is most often deployed on [Deno Deploy][deno-deploy] where it can be
deployed with 1-click and has out of the box integrations with metrics among
other things.
Fresh projects can be deployed manually to any platform with [Deno][deno] like
via docker containers too.
[preact]: https://preactjs.com
[deno]: https://deno.com
@@ -3,7 +3,7 @@ description: "Extend fresh with plugins"
---
Fresh itself can be extended through the methods available on the
[`App`](/docs/canary/concepts/app) class or on the `Builder` class. Most of the
[`App`](/docs/concepts/app) class or on the `Builder` class. Most of the
features in Fresh itself are built using these APIs.
## Custom middlewares
@@ -20,6 +20,6 @@ const addXFreshHeader = define.middleware(async (ctx) => {
});
```
Learn more about [middlewares](/docs/canary/concepts/middleware).
Learn more about [middlewares](/docs/concepts/middleware).
TODO: Show more ways
@@ -10,8 +10,8 @@ write tests.
## Testing middlewares
To test [middlewares](/docs/canary/concepts/middleware) we're going to create a
dummy app and return the relevant info we want to check in a custom `/` handler.
To test [middlewares](/docs/concepts/middleware) we're going to create a dummy
app and return the relevant info we want to check in a custom `/` handler.
```ts middleware.test.ts
import { expect } from "@std/expect";
@@ -40,8 +40,8 @@ that adds a header to the returned response, you can assert against that too.
## Testing app wrapper or layouts
Both the [app wrapper](/docs/canary/advanced/app-wrapper) component and
[layouts](/docs/canary/advanced/layouts) can be tested in the same way.
Both the [app wrapper](/docs/advanced/app-wrapper) component and
[layouts](/docs/advanced/layouts) can be tested in the same way.
```tsx routes/_app.test.tsx
import { expect } from "@std/expect";
@@ -106,8 +106,8 @@ Deno.test("MyLayout - renders heading and content", async () => {
## Testing with file routes and islands
[File routes](/docs/canary/concepts//file-routing) are collected by the
[`Builder`](/docs/canary/concepts/builder) class and not just by
[File routes](/docs/concepts/file-routing) are collected by the
[`Builder`](/docs/advanced/builder) class and not just by
[`App`](/docs/concepts/app) alone. We can generate a snapshot and re-use it for
many app instances in our test suite.
+45 -42
View File
@@ -1,4 +1,7 @@
import FRESH_VERSIONS from "../versions.json" with { type: "json" };
import FRESH_VERSIONS_1x from "../versions.json" with { type: "json" };
import LATEST_VERSION_2 from "../packages/fresh/deno.json" with {
type: "json",
};
type RawTableOfContents = Record<
string,
@@ -15,93 +18,93 @@ interface RawTableOfContentsEntry {
}
const toc: RawTableOfContents = {
canary: {
label: "canary",
latest: {
label: LATEST_VERSION_2.version,
content: {
introduction: {
title: "Introduction",
link: "canary",
link: "latest",
},
"getting-started": {
title: "Getting Started",
link: "canary",
link: "latest",
},
concepts: {
title: "Concepts",
link: "canary",
link: "latest",
pages: [
["app", "App", "link:canary"],
["middleware", "Middlewares", "link:canary"],
["context", "Context", "link:canary"],
["app", "App", "link:latest"],
["middleware", "Middlewares", "link:latest"],
["context", "Context", "link:latest"],
["routing", "Routing", "link:canary"],
["routing", "Routing", "link:latest"],
["islands", "Islands", "link:canary"],
["static-files", "Static files", "link:canary"],
["islands", "Islands", "link:latest"],
["static-files", "Static files", "link:latest"],
["file-routing", "File routing", "link:canary"],
["file-routing", "File routing", "link:latest"],
],
},
advanced: {
title: "Advanced",
link: "canary",
link: "latest",
pages: [
["app-wrapper", "App wrapper", "link:canary"],
["layouts", "Layouts", "link:canary"],
["error-handling", "Error handling", "link:canary"],
["partials", "Partials", "link:canary"],
["forms", "Forms", "link:canary"],
["define", "Define Helpers", "link:canary"],
["environment-variables", "Environment Variables", "link:canary"],
["head", "Modifying <head>", "link:canary"],
["vite", "Vite Plugin Options", "link:canary"],
["troubleshooting", "Troubleshooting", "link:canary"],
["builder", "Builder (Legacy)", "link:canary"],
["app-wrapper", "App wrapper", "link:latest"],
["layouts", "Layouts", "link:latest"],
["error-handling", "Error handling", "link:latest"],
["partials", "Partials", "link:latest"],
["forms", "Forms", "link:latest"],
["define", "Define Helpers", "link:latest"],
["environment-variables", "Environment Variables", "link:latest"],
["head", "Modifying <head>", "link:latest"],
["vite", "Vite Plugin Options", "link:latest"],
["troubleshooting", "Troubleshooting", "link:latest"],
["builder", "Builder (Legacy)", "link:latest"],
],
},
deployment: {
title: "Deployment",
link: "canary",
link: "latest",
pages: [
["deno-deploy", "Deno Deploy", "link:canary"],
["deno-compile", "deno compile", "link:canary"],
["docker", "Docker", "link:canary"],
["cloudflare-workers", "Cloudflare Workers", "link:canary"],
["deno-deploy", "Deno Deploy", "link:latest"],
["deno-compile", "deno compile", "link:latest"],
["docker", "Docker", "link:latest"],
["cloudflare-workers", "Cloudflare Workers", "link:latest"],
],
},
testing: {
title: "Testing",
link: "canary",
link: "latest",
},
plugins: {
title: "Plugins",
link: "canary",
link: "latest",
pages: [
["cors", "cors", "link:canary"],
["csrf", "csrf", "link:canary"],
["trailing-slashes", "trailingSlashes", "link:canary"],
["cors", "cors", "link:latest"],
["csrf", "csrf", "link:latest"],
["trailing-slashes", "trailingSlashes", "link:latest"],
],
},
examples: {
title: "Examples",
link: "latest",
pages: [
["migration-guide", "Migration Guide", "link:canary"],
["daisyui", "daisyUI", "link:canary"],
["markdown", "Rendering Markdown", "link:canary"],
["rendering-raw-html", "Rendering raw HTML", "link:canary"],
["migration-guide", "Migration Guide", "link:latest"],
["daisyui", "daisyUI", "link:latest"],
["markdown", "Rendering Markdown", "link:latest"],
["rendering-raw-html", "Rendering raw HTML", "link:latest"],
[
"sharing-state-between-islands",
"Sharing state between islands",
"link:latest",
],
["active-links", "Active links", "link:canary"],
["active-links", "Active links", "link:latest"],
],
},
},
},
latest: {
label: FRESH_VERSIONS[0],
"1.x": {
label: FRESH_VERSIONS_1x[0],
content: {
introduction: {
title: "Introduction",