docs: make 2.x the default version (#3369)
This commit is contained in:
@@ -86,7 +86,8 @@
|
|||||||
"imagescript": "https://deno.land/x/imagescript@1.3.0/mod.ts",
|
"imagescript": "https://deno.land/x/imagescript@1.3.0/mod.ts",
|
||||||
"marked": "npm:marked@^15.0.11",
|
"marked": "npm:marked@^15.0.11",
|
||||||
"marked-mangle": "npm:marked-mangle@^1.1.9",
|
"marked-mangle": "npm:marked-mangle@^1.1.9",
|
||||||
"prismjs": "npm:prismjs@^1.29.0"
|
"prismjs": "npm:prismjs@^1.29.0",
|
||||||
|
"vite": "npm:vite@^7.1.5"
|
||||||
},
|
},
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"lib": ["dom", "dom.asynciterable", "deno.ns", "deno.unstable"],
|
"lib": ["dom", "dom.asynciterable", "deno.ns", "deno.unstable"],
|
||||||
|
|||||||
@@ -103,7 +103,9 @@
|
|||||||
"npm:vite-plugin-inspect@^11.3.2": "11.3.3_vite@7.1.4__@types+node@24.3.0__picomatch@4.0.3_@types+node@24.3.0_@types+node@24.2.0",
|
"npm:vite-plugin-inspect@^11.3.2": "11.3.3_vite@7.1.4__@types+node@24.3.0__picomatch@4.0.3_@types+node@24.3.0_@types+node@24.2.0",
|
||||||
"npm:vite@*": "7.1.4_@types+node@24.3.0_picomatch@4.0.3_@types+node@24.2.0",
|
"npm:vite@*": "7.1.4_@types+node@24.3.0_picomatch@4.0.3_@types+node@24.2.0",
|
||||||
"npm:vite@7.1.4": "7.1.4_@types+node@24.3.0_picomatch@4.0.3_@types+node@24.2.0",
|
"npm:vite@7.1.4": "7.1.4_@types+node@24.3.0_picomatch@4.0.3_@types+node@24.2.0",
|
||||||
"npm:vite@^7.1.4": "7.1.4_@types+node@24.3.0_picomatch@4.0.3_@types+node@24.2.0"
|
"npm:vite@7.1.5": "7.1.5_@types+node@24.2.0_picomatch@4.0.3",
|
||||||
|
"npm:vite@^7.1.4": "7.1.4_@types+node@24.3.0_picomatch@4.0.3_@types+node@24.2.0",
|
||||||
|
"npm:vite@^7.1.5": "7.1.5_@types+node@24.2.0_picomatch@4.0.3"
|
||||||
},
|
},
|
||||||
"jsr": {
|
"jsr": {
|
||||||
"@astral/astral@0.5.3": {
|
"@astral/astral@0.5.3": {
|
||||||
@@ -3800,6 +3802,13 @@
|
|||||||
"picomatch@4.0.3"
|
"picomatch@4.0.3"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
"tinyglobby@0.2.15_picomatch@4.0.3": {
|
||||||
|
"integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
|
||||||
|
"dependencies": [
|
||||||
|
"fdir",
|
||||||
|
"picomatch@4.0.3"
|
||||||
|
]
|
||||||
|
},
|
||||||
"to-regex-range@5.0.1": {
|
"to-regex-range@5.0.1": {
|
||||||
"integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
|
"integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
|
||||||
"dependencies": [
|
"dependencies": [
|
||||||
@@ -3935,7 +3944,7 @@
|
|||||||
"picomatch@4.0.3",
|
"picomatch@4.0.3",
|
||||||
"postcss",
|
"postcss",
|
||||||
"rollup",
|
"rollup",
|
||||||
"tinyglobby"
|
"tinyglobby@0.2.14_picomatch@4.0.3"
|
||||||
],
|
],
|
||||||
"optionalDependencies": [
|
"optionalDependencies": [
|
||||||
"fsevents"
|
"fsevents"
|
||||||
@@ -3954,7 +3963,26 @@
|
|||||||
"picomatch@4.0.3",
|
"picomatch@4.0.3",
|
||||||
"postcss",
|
"postcss",
|
||||||
"rollup",
|
"rollup",
|
||||||
"tinyglobby"
|
"tinyglobby@0.2.14_picomatch@4.0.3"
|
||||||
|
],
|
||||||
|
"optionalDependencies": [
|
||||||
|
"fsevents"
|
||||||
|
],
|
||||||
|
"optionalPeers": [
|
||||||
|
"@types/node@24.2.0"
|
||||||
|
],
|
||||||
|
"bin": true
|
||||||
|
},
|
||||||
|
"vite@7.1.5_@types+node@24.2.0_picomatch@4.0.3": {
|
||||||
|
"integrity": "sha512-4cKBO9wR75r0BeIWWWId9XK9Lj6La5X846Zw9dFfzMRw38IlTk2iCcUt6hsyiDRcPidc55ZParFYDXi0nXOeLQ==",
|
||||||
|
"dependencies": [
|
||||||
|
"@types/node@24.2.0",
|
||||||
|
"esbuild",
|
||||||
|
"fdir",
|
||||||
|
"picomatch@4.0.3",
|
||||||
|
"postcss",
|
||||||
|
"rollup",
|
||||||
|
"tinyglobby@0.2.15_picomatch@4.0.3"
|
||||||
],
|
],
|
||||||
"optionalDependencies": [
|
"optionalDependencies": [
|
||||||
"fsevents"
|
"fsevents"
|
||||||
@@ -4135,7 +4163,8 @@
|
|||||||
"npm:prismjs@^1.29.0",
|
"npm:prismjs@^1.29.0",
|
||||||
"npm:rollup@^4.50.0",
|
"npm:rollup@^4.50.0",
|
||||||
"npm:tailwindcss@^4.1.10",
|
"npm:tailwindcss@^4.1.10",
|
||||||
"npm:ts-morph@26"
|
"npm:ts-morph@26",
|
||||||
|
"npm:vite@^7.1.5"
|
||||||
],
|
],
|
||||||
"members": {
|
"members": {
|
||||||
"packages/build-id": {
|
"packages/build-id": {
|
||||||
|
|||||||
+1
-1
@@ -35,7 +35,7 @@ metadata for Fresh.
|
|||||||
|
|
||||||
Any other static files generated by plugins will be stored in the
|
Any other static files generated by plugins will be stored in the
|
||||||
`_fresh/static` subfolder. They will be served the same as other
|
`_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
|
> [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
|
> 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)
|
- [Deno Deploy](#deno-deploy)
|
||||||
- [Docker](#docker)
|
- [Docker](#docker)
|
||||||
|
- [Self Contained Executable](#self-contained-executable)
|
||||||
|
|
||||||
## Deno Deploy
|
## 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
|
[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
|
[gcp-container-registry]: https://cloud.google.com/container-registry/docs/pushing-and-pulling
|
||||||
[deno-deploy]: https://deno.com/deploy
|
[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
|
||||||
@@ -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.
|
||||||
@@ -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`.
|
set by middleware is available via `props.state`.
|
||||||
|
|
||||||
```tsx routes/sub/_layout.tsx
|
```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
|
// do something with state here
|
||||||
return (
|
return (
|
||||||
<div class="layout">
|
<div class="layout">
|
||||||
<Component />
|
<Component />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
})
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Async layouts
|
## 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.
|
can use an async layout to do so.
|
||||||
|
|
||||||
```tsx routes/sub/_layout.tsx
|
```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
|
// do something with state here
|
||||||
const data = await loadData();
|
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 (
|
return (
|
||||||
<div class="layout">
|
<div class="layout">
|
||||||
<p>{data.greeting}</p>
|
<p>{data.greeting}</p>
|
||||||
@@ -78,22 +99,21 @@ To make `routes/sub/special.tsx` opt out of rendering layouts we can set
|
|||||||
`skipInheritedLayouts: true`.
|
`skipInheritedLayouts: true`.
|
||||||
|
|
||||||
```tsx routes/sub/special.tsx
|
```tsx routes/sub/special.tsx
|
||||||
import { type RouteConfig } from "fresh";
|
import { RouteConfig } from "$fresh/server.ts";
|
||||||
import { define } from "../../utils.ts";
|
|
||||||
|
|
||||||
export const config: RouteConfig = {
|
export const config: RouteConfig = {
|
||||||
skipInheritedLayouts: true, // Skip already inherited layouts
|
skipInheritedLayouts: true, // Skip already inherited layouts
|
||||||
};
|
};
|
||||||
|
|
||||||
export default define.layout(() => {
|
export default function MyPage() {
|
||||||
return <p>Hello world</p>;
|
return <p>Hello world</p>;
|
||||||
});
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
You can skip already inherited layouts inside a layout file:
|
You can skip already inherited layouts inside a layout file:
|
||||||
|
|
||||||
```tsx routes/special/_layout.tsx
|
```tsx routes/special/_layout.tsx
|
||||||
import { type LayoutConfig } from "fresh";
|
import { LayoutConfig } from "$fresh/server.ts";
|
||||||
|
|
||||||
export const config: LayoutConfig = {
|
export const config: LayoutConfig = {
|
||||||
skipInheritedLayouts: true, // Skip already inherited layouts
|
skipInheritedLayouts: true, // Skip already inherited layouts
|
||||||
@@ -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
|
main content area and a sidebar of links to switch between pages of the
|
||||||
documentation (marked green here).
|
documentation (marked green here).
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
The code for such a page (excluding styling) might look like this:
|
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`
|
### Hook: `buildStart`
|
||||||
|
|
||||||
This hook is run at the start of the Fresh
|
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.
|
synchronous or asynchronous.
|
||||||
|
|
||||||
The build start hook is called with the
|
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
|
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
|
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`
|
### Hook: `buildEnd`
|
||||||
|
|
||||||
This hook is run at the end of the Fresh
|
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.
|
synchronous or asynchronous.
|
||||||
|
|
||||||
### Routes and Middlewares
|
### Routes and Middlewares
|
||||||
|
|
||||||
You can create routes and middlewares that get loaded and rendered like the
|
You can create routes and middlewares that get loaded and rendered like the
|
||||||
normal [routes](/docs/concepts/routes) and
|
normal [routes](/docs/1.x/concepts/routes) and
|
||||||
[middlewares](/docs/concepts/middleware).
|
[middlewares](/docs/1.x/concepts/middleware).
|
||||||
|
|
||||||
The plugin routes and middlewares need a defined path in the format of a file
|
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`,
|
name without a filetype inside the routes directory(E.g. `blog/index`,
|
||||||
`blog/[slug]`).
|
`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.
|
To create a middleware you need to create a `MiddlewareHandler` function.
|
||||||
|
|
||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
+2
-2
@@ -103,8 +103,8 @@ await dev(import.meta.url, "./main.ts", {
|
|||||||
|
|
||||||
## Plugins
|
## Plugins
|
||||||
|
|
||||||
See the [docs](/docs/concepts/plugins) on this topic for more detail. But as a
|
See the [docs](/docs/1.x/concepts/plugins) on this topic for more detail. But as
|
||||||
quick example, you can do something like this to load plugins:
|
a quick example, you can do something like this to load plugins:
|
||||||
|
|
||||||
```ts main.ts
|
```ts main.ts
|
||||||
await start(manifest, { plugins: [twindPlugin(twindConfig)] });
|
await start(manifest, { plugins: [twindPlugin(twindConfig)] });
|
||||||
@@ -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 />;
|
||||||
|
```
|
||||||
@@ -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"
|
||||||
|
```
|
||||||
+2
-2
@@ -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
|
building blocks of an implementation. As such, it is limited in functionality
|
||||||
and purposefully leaves out things like
|
and purposefully leaves out things like
|
||||||
[password resets](https://supabase.com/docs/guides/auth/server-side/email-based-auth-with-pkce-flow-for-ssr),
|
[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
|
well as validating input form data. You can find the
|
||||||
[full code here](https://github.com/morlinbrot/supa-fresh-pkce), where the
|
[full code here](https://github.com/morlinbrot/supa-fresh-pkce), where the
|
||||||
missing functionality is implemented.
|
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,
|
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
|
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
|
```ts routes/_middleware.ts
|
||||||
import { FreshContext } from "$fresh/server.ts";
|
import { FreshContext } from "$fresh/server.ts";
|
||||||
+1
-1
@@ -170,7 +170,7 @@ user 2 deleted
|
|||||||
|
|
||||||
Options can be used for some advanced cases, including implementing preflight
|
Options can be used for some advanced cases, including implementing preflight
|
||||||
request checks for complex CORS use cases. See more on the
|
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
|
## Full File Reference
|
||||||
|
|
||||||
@@ -89,4 +89,4 @@ requests.
|
|||||||
|
|
||||||
Of course there's no reason why you need to use middleware in order to solve
|
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
|
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.
|
||||||
+2
-2
@@ -3,8 +3,8 @@ description: |
|
|||||||
Sometimes URL based routing isn't enough.
|
Sometimes URL based routing isn't enough.
|
||||||
---
|
---
|
||||||
|
|
||||||
The page on [routing](/docs/concepts/routing) hints at complex routing based on
|
The page on [routing](/docs/1.x/concepts/routing) hints at complex routing based
|
||||||
URL patterns using a `RouteConfig` object. Let's dive into this in a bit more
|
on URL patterns using a `RouteConfig` object. Let's dive into this in a bit more
|
||||||
detail.
|
detail.
|
||||||
|
|
||||||
A `RouteConfig` has a `routeOverride` string property, which makes use of the
|
A `RouteConfig` has a `routeOverride` string property, which makes use of the
|
||||||
+1
-1
@@ -10,7 +10,7 @@ will now install the Tailwind CSS plugin instead of twind like it did before.
|
|||||||
## Requirements before migrating
|
## Requirements before migrating
|
||||||
|
|
||||||
The tailwind plugin requires Fresh's
|
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
|
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
|
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.
|
configured to use ahead of time builds, then you're good to go.
|
||||||
@@ -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
|
For more on how these work, see the page about
|
||||||
[server configuration](/docs/concepts/server-configuration).
|
[server configuration](/docs/1.x/concepts/server-configuration).
|
||||||
+2
-2
@@ -51,8 +51,8 @@ The new page will be visible at `http://localhost:8000/about`.
|
|||||||
[_Concepts: Routes_][concepts-routes] documentation page. The following
|
[_Concepts: Routes_][concepts-routes] documentation page. The following
|
||||||
pages in the _Getting Started_ guide will also explain more features of routes. -->
|
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
|
[jsx]: https://react.dev/learn/writing-markup-with-jsx
|
||||||
[preact]: https://preactjs.com/
|
[preact]: https://preactjs.com/
|
||||||
|
|
||||||
<!-- [concepts-routes]: /docs/concepts/routes -->
|
<!-- [concepts-routes]: /docs/1.x/concepts/routes -->
|
||||||
+1
-1
@@ -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
|
The [_Concepts: Routing_][concepts-routing] page has more information about
|
||||||
dynamic routes, especially about how to create more advanced dynamic routes.
|
dynamic routes, especially about how to create more advanced dynamic routes.
|
||||||
|
|
||||||
[concepts-routing]: /docs/concepts/routing
|
[concepts-routing]: /docs/1.x/concepts/routing
|
||||||
+2
-2
@@ -75,5 +75,5 @@ rendering.
|
|||||||
|
|
||||||
<!-- TODO(lucacasonato): link to todo app example when that is built again -->
|
<!-- TODO(lucacasonato): link to todo app example when that is built again -->
|
||||||
|
|
||||||
[custom-handlers]: /docs/getting-started/custom-handlers
|
[custom-handlers]: /docs/1.x/getting-started/custom-handlers
|
||||||
[concepts-forms]: /docs/concepts/forms
|
[concepts-forms]: /docs/1.x/concepts/forms
|
||||||
@@ -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/).
|
||||||
@@ -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
|
||||||
@@ -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
|
|
||||||
@@ -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>;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
@@ -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];
|
|
||||||
```
|
|
||||||
@@ -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.
|
|
||||||
@@ -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>;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
@@ -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.
|
|
||||||
@@ -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.
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
## 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.
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
## 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:
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
## Next steps
|
|
||||||
|
|
||||||
TODO
|
|
||||||
@@ -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);
|
app.appWrapper(AppWrapper);
|
||||||
```
|
```
|
||||||
|
|
||||||
Every [`ctx.render()`](/docs/canary/concepts/context#render-1) call will include
|
Every [`ctx.render()`](/docs/concepts/context#render-1) call will include the
|
||||||
the app wrapper component by default, unless opted out.
|
app wrapper component by default, unless opted out.
|
||||||
|
|
||||||
Note that only one app wrapper component is supported per
|
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
|
## 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
|
```ts main.ts
|
||||||
const app = new App()
|
const app = new App()
|
||||||
@@ -36,7 +36,7 @@ const app = new App()
|
|||||||
|
|
||||||
## `.use()`
|
## `.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.
|
matched left to right.
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
@@ -261,14 +261,13 @@ TODO
|
|||||||
|
|
||||||
## `.appWrapper()`
|
## `.appWrapper()`
|
||||||
|
|
||||||
Set the [App Wrapper](/docs/canary/advanced/app-wrapper) component. This is
|
Set the [App Wrapper](/docs/advanced/app-wrapper) component. This is where the
|
||||||
where the outer HTML, typically up until the `<body>`-tag is rendered.
|
outer HTML, typically up until the `<body>`-tag is rendered.
|
||||||
|
|
||||||
## `.layout()`
|
## `.layout()`
|
||||||
|
|
||||||
Set a [Layout](/docs/canary/advanced/layouts) component at the specified path.
|
Set a [Layout](/docs/advanced/layouts) component at the specified path. The app
|
||||||
The app wrapper component and prior layouts are inherited by default unless
|
wrapper component and prior layouts are inherited by default unless opted out.
|
||||||
opted out.
|
|
||||||
|
|
||||||
## `.onError()`
|
## `.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.
|
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
|
Use the `.fsRoutes()` helper on the [`App`](/docs/concepts/app) instance to
|
||||||
to specify where file based routes should be inserted. It adds routes based on
|
specify where file based routes should be inserted. It adds routes based on the
|
||||||
the structure in the `routes/` folder in your project (or any other folder you
|
structure in the `routes/` folder in your project (or any other folder you have
|
||||||
have specified when instantiating the
|
specified when instantiating the [`fresh()` vite plugin](/docs/advanced/vite).
|
||||||
[`fresh()` vite plugin](/docs/canary/advanced/vite). in `vite.config.ts`). When
|
in `vite.config.ts`). When you add a new file there, it will register a new
|
||||||
you add a new file there, it will register a new route automatically.
|
route automatically.
|
||||||
|
|
||||||
```ts main.ts
|
```ts main.ts
|
||||||
import { App, staticFiles } from "fresh";
|
import { App, staticFiles } from "fresh";
|
||||||
@@ -86,7 +86,7 @@ export const config: RouteConfig = {
|
|||||||
|
|
||||||
## Route Groups
|
## 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
|
[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
|
situation where you want your routes to inherit from a layout other than what's
|
||||||
suggested by the URL segment.
|
suggested by the URL segment.
|
||||||
@@ -3,6 +3,34 @@ description: |
|
|||||||
This chapter goes over some fundamental concepts of Fresh.
|
This chapter goes over some fundamental concepts of Fresh.
|
||||||
---
|
---
|
||||||
|
|
||||||
This chapter goes over some fundamental concepts of Fresh. It covers the
|
The way Fresh works is that it receives a
|
||||||
overarching architecture design of Fresh applications, as well as reference
|
[`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request), passes it
|
||||||
documentation about the various features of Fresh.
|
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
@@ -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. 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
|
Islands enable client side interactivity in Fresh and they are rendered both on
|
||||||
components that are rendered on the server and then hydrated on the client. This
|
the server and in the client.
|
||||||
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
|
Islands are defined by creating a file in the `islands/` folder or a
|
||||||
project. The name of this file must be a PascalCase or kebab-case name of the
|
`(_islands)` folder somewhere in the `routes/` directory. The name of this file
|
||||||
island.
|
must be a PascalCase or kebab-case name of the island.
|
||||||
|
|
||||||
```tsx islands/my-island.tsx
|
```tsx islands/my-island.tsx
|
||||||
import { useSignal } from "@preact/signals";
|
import { useSignal } from "@preact/signals";
|
||||||
@@ -20,127 +18,74 @@ export default function MyIsland() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
Counter is at {count}.{" "}
|
<p>Count: {count}</p>
|
||||||
<button onClick={() => (count.value += 1)}>+</button>
|
<button onClick={() => (count.value += 1)}>+</button>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
An island can be used in a page like a regular Preact component. Fresh will take
|
An island can be used anywhere like a regular Preact component. Fresh will take
|
||||||
care of automatically re-hydrating the island on the client.
|
care of making it interactive on the client.
|
||||||
|
|
||||||
```tsx route/index.tsx
|
```tsx main.tsx
|
||||||
import MyIsland from "../islands/my-island.tsx";
|
import { App, staticFiles } from "fresh";
|
||||||
|
import MyIsland from "./islands/my-island.tsx";
|
||||||
|
|
||||||
export default function Home() {
|
const app = new App()
|
||||||
return <MyIsland />;
|
.use(staticFiles())
|
||||||
}
|
.get("/", (ctx) => ctx.render(<MyIsland />));
|
||||||
```
|
```
|
||||||
|
|
||||||
## Passing JSX to islands
|
## Passing props 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.
|
Passing props to islands is supported, but only if the props are serializable.
|
||||||
Fresh can serialize the following types of values:
|
Fresh can serialize the following types of values:
|
||||||
|
|
||||||
- Primitive types `string`, `boolean`, `bigint`, and `null`
|
- Primitive types `string`, `number`, `boolean`, `bigint`, `undefined`, and
|
||||||
- Most `number`s (`Infinity`, `-Infinity`, and `NaN` are silently converted to
|
`null`
|
||||||
`null`)
|
- `Infinity`, `-Infinity`, `-0`, and `NaN`
|
||||||
|
- `Uint8Array`
|
||||||
|
- `URL`
|
||||||
|
- `Date`
|
||||||
|
- `RegExp`
|
||||||
|
- `JSX` Elements
|
||||||
|
- Collections `Map` and `Set`
|
||||||
- Plain objects with string keys and serializable values
|
- Plain objects with string keys and serializable values
|
||||||
- Arrays containing serializable values
|
- Arrays containing serializable values
|
||||||
- Uint8Array
|
|
||||||
- JSX Elements (restricted to `props.children`)
|
|
||||||
- Preact Signals (if the inner value is serializable)
|
- Preact Signals (if the inner value is serializable)
|
||||||
|
|
||||||
Circular references are supported. If an object or signal is referenced multiple
|
Circular references are supported. If an object or signal is referenced multiple
|
||||||
times, it is only serialized once and the references are restored upon
|
times, it is only serialized once and the references are restored upon
|
||||||
deserialization. Passing complex objects like `Date`, custom classes, or
|
deserialization.
|
||||||
functions is not supported.
|
|
||||||
|
|
||||||
During server side rendering, Fresh annotates the HTML with special comments
|
> [warn]: Passing functions to an island is not supported.
|
||||||
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
|
> ```tsx routes/example.tsx
|
||||||
requiring hydration for the static children of interactive islands. No
|
> export default function () {
|
||||||
Javascript is sent to the client when no interactivity is needed.
|
> // WRONG
|
||||||
|
> return <MyIsland onClick={() => console.log("hey")} />;
|
||||||
|
> }
|
||||||
|
> ```
|
||||||
|
|
||||||
```html Response body
|
### Passing JSX
|
||||||
<!--frsh-myisland_default:default:0-->
|
|
||||||
<div>
|
A powerful feature of Fresh is that you can pass server-rendered JSX to an
|
||||||
Counter is at 0.
|
island via props.
|
||||||
<button>+</button>
|
|
||||||
<!--frsh-slot-myisland_default:children-->
|
```tsx routes/index.tsx
|
||||||
<p>This text is rendered on the server</p>
|
import { staticFiles } from "fresh";
|
||||||
<!--/frsh-slot-myisland_default:children-->
|
import MyIsland from "../islands/my-island.tsx";
|
||||||
</div>
|
|
||||||
<!--/frsh-myisland_default:default:0-->
|
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
|
### 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
|
like a normal Preact component, but still receive the serialized props if any
|
||||||
were present.
|
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
|
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
|
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.
|
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
|
```tsx route/index.tsx
|
||||||
import MyIsland from "../islands/my-island.tsx";
|
import MyIsland from "../islands/my-island.tsx";
|
||||||
import OtherIsland from "../islands/other-island.tsx";
|
import OtherIsland from "../islands/other-island.tsx";
|
||||||
|
|
||||||
export default function Home() {
|
// Later...
|
||||||
return (
|
<div>
|
||||||
<div>
|
<MyIsland>
|
||||||
<MyIsland>
|
<OtherIsland foo="this prop will be serialized" />
|
||||||
<OtherIsland foo="this prop will be serialized" />
|
</MyIsland>
|
||||||
</MyIsland>
|
<p>Some more server rendered text</p>
|
||||||
<p>Some more server rendered text</p>
|
</div>;
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Rendering islands on client only
|
## Rendering islands on client only
|
||||||
|
|
||||||
When using client-only APIs, like `EventSource` or `navigator.getUserMedia`,
|
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:
|
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:
|
||||||
```
|
|
||||||
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
|
```tsx islands/my-island.tsx
|
||||||
import { IS_BROWSER } from "$fresh/runtime.ts";
|
import { IS_BROWSER } from "fresh/runtime";
|
||||||
|
|
||||||
export function MyIsland() {
|
export function MyIsland() {
|
||||||
// Return any prerenderable JSX here which makes sense for your island
|
// Return any prerenderable JSX here which makes sense for your island
|
||||||
|
|||||||
@@ -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`.
|
set by middleware is available via `props.state`.
|
||||||
|
|
||||||
```tsx routes/sub/_layout.tsx
|
```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
|
// do something with state here
|
||||||
return (
|
return (
|
||||||
<div class="layout">
|
<div class="layout">
|
||||||
<Component />
|
<Component />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
})
|
||||||
```
|
```
|
||||||
|
|
||||||
## Async layouts
|
## 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.
|
can use an async layout to do so.
|
||||||
|
|
||||||
```tsx routes/sub/_layout.tsx
|
```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
|
// do something with state here
|
||||||
const data = await loadData();
|
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 (
|
return (
|
||||||
<div class="layout">
|
<div class="layout">
|
||||||
<p>{data.greeting}</p>
|
<p>{data.greeting}</p>
|
||||||
@@ -99,21 +78,22 @@ To make `routes/sub/special.tsx` opt out of rendering layouts we can set
|
|||||||
`skipInheritedLayouts: true`.
|
`skipInheritedLayouts: true`.
|
||||||
|
|
||||||
```tsx routes/sub/special.tsx
|
```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 = {
|
export const config: RouteConfig = {
|
||||||
skipInheritedLayouts: true, // Skip already inherited layouts
|
skipInheritedLayouts: true, // Skip already inherited layouts
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function MyPage() {
|
export default define.layout(() => {
|
||||||
return <p>Hello world</p>;
|
return <p>Hello world</p>;
|
||||||
}
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
You can skip already inherited layouts inside a layout file:
|
You can skip already inherited layouts inside a layout file:
|
||||||
|
|
||||||
```tsx routes/special/_layout.tsx
|
```tsx routes/special/_layout.tsx
|
||||||
import { LayoutConfig } from "$fresh/server.ts";
|
import { type LayoutConfig } from "fresh";
|
||||||
|
|
||||||
export const config: LayoutConfig = {
|
export const config: LayoutConfig = {
|
||||||
skipInheritedLayouts: true, // Skip already inherited layouts
|
skipInheritedLayouts: true, // Skip already inherited layouts
|
||||||
|
|||||||
@@ -3,220 +3,86 @@ description: |
|
|||||||
Add middleware routes to intercept requests or responses for analytics purposes, access control, or anything else.
|
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
|
A middleware is a function that receives a [`Context`](/docs/concepts/context)
|
||||||
request in order for you to perform custom logic before or after the route
|
object with the
|
||||||
handler. This allows modifying or checking requests and responses. Common
|
[`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) and
|
||||||
use-cases for this are logging, authentication, and performance monitoring.
|
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
|
```tsx main.ts
|
||||||
used to trigger child handlers. The `ctx` also has a `state` property that can
|
const app = new App<{ greeting: string }>()
|
||||||
be used to pass arbitrary data to downstream (or upstream) handlers. This
|
.use((ctx) => {
|
||||||
`state` is included in `PageProps` by default, which is available to both the
|
// Middleware to pass data
|
||||||
special [\_app](/docs/concepts/app-wrapper.md) wrapper and normal
|
ctx.state.greeting = "Hello world";
|
||||||
[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
|
|
||||||
return ctx.next();
|
return ctx.next();
|
||||||
},
|
})
|
||||||
async function middleware2(req, ctx) {
|
.use(async (ctx) => {
|
||||||
// do something
|
// Middleware to add a HTTP header
|
||||||
return ctx.next();
|
const res = await ctx.next();
|
||||||
},
|
res.headers.set("server", "fresh server");
|
||||||
];
|
return res;
|
||||||
```
|
})
|
||||||
|
// A handler is a form of middleware that responds. Here we
|
||||||
It should be noted that `middleware` has access to route parameters. If you're
|
// render HTML and return it.
|
||||||
running a fictitious `routes/[tenant]/admin/_middleware.ts` like this:
|
.get("/", (ctx) => {
|
||||||
|
return ctx.render(<h1>{ctx.state.greeting}</h1>);
|
||||||
```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" },
|
|
||||||
});
|
});
|
||||||
}
|
```
|
||||||
|
|
||||||
|
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
@@ -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.
|
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
|
Routing defines which middlewares and routes should respond to a particular
|
||||||
handled by. Fresh routes requests based on their URL path. By default routes
|
request.
|
||||||
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
|
```ts main.ts
|
||||||
in other frameworks, namely Next.js. File names are used to determine which
|
const app = new App()
|
||||||
route a given request should be handled by. The pattern is determined based on
|
.get("/", () => new Response("hello")) // Responds to: GET /
|
||||||
the path of the file on disk, relative to the `routes/` directory.
|
.get("/other", () => new Response("other")) // Responds to: GET /other
|
||||||
|
.post("/upload", () => new Response("upload")) // Responds to: POST /upload
|
||||||
File names are mapped to route patterns as follows:
|
.get("/books/:id", (ctx) => {
|
||||||
|
// Responds to: GET /books/my-book, /books/cool-book, etc
|
||||||
- File extensions are ignored.
|
const id = ctx.params.id;
|
||||||
- Literals in the file path are treated as string literals to match.
|
return new Response(`Book id: ${id}`);
|
||||||
- Files named `<path>/index.<ext>` behave identically to a file named
|
})
|
||||||
`<path>.<ext>`.
|
.get("/blog/:post/comments", () => {
|
||||||
- Path segments can be made dynamic by surrounding an identifier with `[` and
|
// Responds to: GET /blog/my-post/comments, /blog/hello/comments, etc
|
||||||
`]`.
|
const post = ctx.params.post;
|
||||||
- Paths where the last path segment follows the structure `[...<ident>]` are
|
return new Response(`Blog post comments for post: ${post}`);
|
||||||
treated as having a wildcard suffix.
|
})
|
||||||
|
.get("/foo/*", (ctx) => {
|
||||||
Here is a table of file names, which route patterns they map to, and which paths
|
// Responds to: GET /foo/bar, /foo/bar/baz, etc
|
||||||
they might match:
|
return new Response("foo");
|
||||||
|
});
|
||||||
| 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
|
Fresh supports the full
|
||||||
|
[`URLPattern`](https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API)
|
||||||
When working with [layouts](/docs/concepts/layouts) or
|
syntax for setting pathnames.
|
||||||
[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.
|
|
||||||
|
|||||||
@@ -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.
|
|
||||||
@@ -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 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
|
Static assets placed in the `static/` directory are served at the root of the
|
||||||
project root. These assets are served at the root of the webserver, with a
|
webserver via the `staticFiles()` middleware. They are streamed directly from
|
||||||
higher priority than routes. This means that if a given request matches a file
|
disk for optimal performance with
|
||||||
in the `static/` folder, it is always served, even if there is a route that
|
[`ETag`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/ETag)
|
||||||
would also match the request.
|
headers.
|
||||||
|
|
||||||
Static asset responses automatically get a `content-type` header assigned based
|
```ts main.ts
|
||||||
on the file extension of the file on disk. Assets are also automatically
|
import { staticFiles } from "fresh";
|
||||||
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
|
const app = new App()
|
||||||
`If-None-Match` header for incoming requests.
|
.use(staticFiles());
|
||||||
|
```
|
||||||
|
|
||||||
### Caching
|
## Caching headers
|
||||||
|
|
||||||
By default, no caching headers are added to assets. This can be disadvantageous
|
By default, Fresh adds caching headers for the `src` and `srcset` attributes on
|
||||||
in many scenarios, so Fresh makes it easy to serve assets with long cache
|
`<img>` and `<source>` tags.
|
||||||
lifetimes too.
|
|
||||||
|
|
||||||
The first approach to do this is manual. The client runtime exports an `asset`
|
```tsx main.tsx
|
||||||
function that takes an absolute path to the static asset and returns a "locked"
|
// Caching headers will be automatically added
|
||||||
version of this path that contains a build ID for cache busting. When the asset
|
app.get("/user", (ctx) => ctx.render(<img src="/user.png" />));
|
||||||
is requested at this "locked" path, it will be served with a cache lifetime of
|
```
|
||||||
one year.
|
|
||||||
|
|
||||||
```tsx routes/page.tsx
|
You can always opt out of this behaviour per tag, by adding the
|
||||||
import { asset } from "$fresh/runtime.ts";
|
`data-fresh-disable-lock` attribute.
|
||||||
|
|
||||||
export default function Page() {
|
```tsx main.tsx
|
||||||
return (
|
// Opt-out of automatic caching headers
|
||||||
<p>
|
app.get(
|
||||||
<a href={asset("/brochure.pdf")}>View brochure</a>
|
"/user",
|
||||||
</p>
|
(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 />;
|
|
||||||
```
|
|
||||||
|
|||||||
@@ -11,13 +11,13 @@ current page within a set of pages.
|
|||||||
- `aria-current="page"` - Added to links with an exact path match, enhancing
|
- `aria-current="page"` - Added to links with an exact path match, enhancing
|
||||||
accessibility by indicating the current page to assistive technologies.
|
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 current links where applicable.
|
||||||
|
|
||||||
## Styling with CSS
|
## Styling with CSS
|
||||||
|
|
||||||
The `aria-current` attribute is easily styled with CSS using attribute
|
The aria-current attribute is easily styled with CSS using attribute selectors,
|
||||||
selectors, providing a native way to visually differentiate the active link.
|
providing a native way to visually differentiate the active link.
|
||||||
|
|
||||||
```css static/styles.css
|
```css static/styles.css
|
||||||
/* Give links pointing to the current page a green color */
|
/* 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
|
In Tailwindcss or similar CSS frameworks, you can apply styles to elements with
|
||||||
elements with the aria-current attribute using bracket notation in your class
|
the `aria-current` attribute using bracket notation in your class definitions.
|
||||||
definitions. However, the specific syntax varies slightly between Tailwind and
|
For Tailwindcss, use the syntax:
|
||||||
Twind. For Tailwind, use the syntax:
|
|
||||||
|
|
||||||
```tsx component/Menu.tsx
|
```tsx components/Menu.tsx
|
||||||
function Menu() {
|
function Menu() {
|
||||||
return (
|
return (
|
||||||
<a href="/foo" class="aria-[current]:text-green-600">
|
<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`
|
### Replacing `dev.ts` with `vite.config.ts`
|
||||||
|
|
||||||
Delete `dev.ts` and create a `vite.config.ts` file instead. Pass your custom
|
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
|
```ts vite.config.ts
|
||||||
import { defineConfig } from "vite";
|
import { defineConfig } from "vite";
|
||||||
@@ -217,9 +217,9 @@ Same is true for handlers:
|
|||||||
|
|
||||||
All the various context interfaces have been consolidated and simplified:
|
All the various context interfaces have been consolidated and simplified:
|
||||||
|
|
||||||
| Fresh 1.x | Fresh 2.x |
|
| Fresh 1.x | Fresh 2.x |
|
||||||
| --------------------------------------------- | ------------------------------------------ |
|
| --------------------------------------------- | ----------------------------------- |
|
||||||
| `AppContext`, `LayoutContext`, `RouteContext` | [`Context`](/docs/canary/concepts/context) |
|
| `AppContext`, `LayoutContext`, `RouteContext` | [`Context`](/docs/concepts/context) |
|
||||||
|
|
||||||
### Context methods
|
### Context methods
|
||||||
|
|
||||||
@@ -281,7 +281,7 @@ const app = new App()
|
|||||||
|
|
||||||
The `createHandler` function was often used to launch Fresh for tests. This can
|
The `createHandler` function was often used to launch Fresh for tests. This can
|
||||||
be now done via vite's `createBuilder` function. See the
|
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
|
## Getting help
|
||||||
|
|
||||||
@@ -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
|
in islands. While this generally desired, it can create issues in certain
|
||||||
situations.
|
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
|
```tsx routes/dynamic-html.tsx
|
||||||
should not be used lightly.
|
<div dangerouslySetInnerHTML={{ __html: "<h1>This is raw HTML</h1>" }} />;
|
||||||
|
|
||||||
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`:
|
This will output:
|
||||||
|
|
||||||
```tsx components/json-ld.tsx
|
```html Response body
|
||||||
export default function JsonLd() {
|
<div>
|
||||||
return (
|
<h1>This is raw HTML</h1>
|
||||||
<script
|
</div>
|
||||||
type="application/ld+json"
|
|
||||||
dangerouslySetInnerHTML={{ __html: json }}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## 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
|
> [warn]: Setting arbitrary HTML can be dangerous, hence the
|
||||||
individually styled with CSS. We can build a simple Preact syntax highlighter
|
> `dangerouslySetInnerHTML` naming. Make sure you trust the source. Rendering
|
||||||
like so:
|
> 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
|
||||||
```tsx components/code.tsx
|
> trust.
|
||||||
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.
|
|
||||||
|
|||||||
@@ -5,12 +5,120 @@ description: |
|
|||||||
data, handle user interactions, and deploy it.
|
data, handle user interactions, and deploy it.
|
||||||
---
|
---
|
||||||
|
|
||||||
In this chapter of the Fresh documentation, you'll be introduced to the
|
Let's set up your first Fresh project. To create a new project, run this
|
||||||
framework. You'll learn how to create a new project, run it locally, edit and
|
command:
|
||||||
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
|
```sh Terminal
|
||||||
[Deno](https://docs.deno.com/runtime/#install-deno) installed on your system and
|
deno run -Ar jsr:@fresh/init
|
||||||
set up your
|
```
|
||||||
[Editor to work with Deno](https://docs.deno.com/runtime/getting_started/setup_your_environment/).
|
|
||||||
|
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.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
## 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.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
## 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:
|
||||||
|
|
||||||
|

|
||||||
|
|||||||
@@ -5,30 +5,70 @@ description: |
|
|||||||
and personalized web applications.
|
and personalized web applications.
|
||||||
---
|
---
|
||||||
|
|
||||||
Fresh is a full stack modern web framework for JavaScript and TypeScript
|
Fresh is a small, fast and extensible full stack web framework built on Web
|
||||||
developers. It's designed for building high-quality, performant, and
|
Standards. It's designed for building high-quality, performant, and personalized
|
||||||
personalized web applications. You can use it to create your home page, a blog,
|
web applications.
|
||||||
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
|
```tsx main.tsx
|
||||||
that renders pages on demand on the server. These server rendered pages can
|
import { App } from "fresh";
|
||||||
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
|
const app = new App()
|
||||||
it is intended to be deployed to an edge runtime like [Deno Deploy][deno-deploy]
|
.get("/", () => new Response("hello world"))
|
||||||
for the best experience.
|
.get("/jsx", (ctx) => ctx.render(<h1>render JSX!</h1>));
|
||||||
|
|
||||||
Some stand out features:
|
app.listen();
|
||||||
|
```
|
||||||
|
|
||||||
- Zero config necessary
|
## Quick Start
|
||||||
- Tiny & fast (no client JS is required by the framework)
|
|
||||||
- Optional client side hydration of individual components
|
Create a new Fresh app by running:
|
||||||
- Highly resilient because of progressive enhancement and use of native browser
|
|
||||||
features
|
```sh Terminal
|
||||||
- TypeScript out of the box
|
deno run -Ar jsr:@fresh/init
|
||||||
- File-system routing à la Next.js
|
```
|
||||||
|
|
||||||
|
## 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
|
[preact]: https://preactjs.com
|
||||||
[deno]: https://deno.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
|
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.
|
features in Fresh itself are built using these APIs.
|
||||||
|
|
||||||
## Custom middlewares
|
## 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
|
TODO: Show more ways
|
||||||
@@ -10,8 +10,8 @@ write tests.
|
|||||||
|
|
||||||
## Testing middlewares
|
## Testing middlewares
|
||||||
|
|
||||||
To test [middlewares](/docs/canary/concepts/middleware) we're going to create a
|
To test [middlewares](/docs/concepts/middleware) we're going to create a dummy
|
||||||
dummy app and return the relevant info we want to check in a custom `/` handler.
|
app and return the relevant info we want to check in a custom `/` handler.
|
||||||
|
|
||||||
```ts middleware.test.ts
|
```ts middleware.test.ts
|
||||||
import { expect } from "@std/expect";
|
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
|
## Testing app wrapper or layouts
|
||||||
|
|
||||||
Both the [app wrapper](/docs/canary/advanced/app-wrapper) component and
|
Both the [app wrapper](/docs/advanced/app-wrapper) component and
|
||||||
[layouts](/docs/canary/advanced/layouts) can be tested in the same way.
|
[layouts](/docs/advanced/layouts) can be tested in the same way.
|
||||||
|
|
||||||
```tsx routes/_app.test.tsx
|
```tsx routes/_app.test.tsx
|
||||||
import { expect } from "@std/expect";
|
import { expect } from "@std/expect";
|
||||||
@@ -106,8 +106,8 @@ Deno.test("MyLayout - renders heading and content", async () => {
|
|||||||
|
|
||||||
## Testing with file routes and islands
|
## Testing with file routes and islands
|
||||||
|
|
||||||
[File routes](/docs/canary/concepts//file-routing) are collected by the
|
[File routes](/docs/concepts/file-routing) are collected by the
|
||||||
[`Builder`](/docs/canary/concepts/builder) class and not just by
|
[`Builder`](/docs/advanced/builder) class and not just by
|
||||||
[`App`](/docs/concepts/app) alone. We can generate a snapshot and re-use it for
|
[`App`](/docs/concepts/app) alone. We can generate a snapshot and re-use it for
|
||||||
many app instances in our test suite.
|
many app instances in our test suite.
|
||||||
|
|
||||||
+45
-42
@@ -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<
|
type RawTableOfContents = Record<
|
||||||
string,
|
string,
|
||||||
@@ -15,93 +18,93 @@ interface RawTableOfContentsEntry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const toc: RawTableOfContents = {
|
const toc: RawTableOfContents = {
|
||||||
canary: {
|
latest: {
|
||||||
label: "canary",
|
label: LATEST_VERSION_2.version,
|
||||||
content: {
|
content: {
|
||||||
introduction: {
|
introduction: {
|
||||||
title: "Introduction",
|
title: "Introduction",
|
||||||
link: "canary",
|
link: "latest",
|
||||||
},
|
},
|
||||||
"getting-started": {
|
"getting-started": {
|
||||||
title: "Getting Started",
|
title: "Getting Started",
|
||||||
link: "canary",
|
link: "latest",
|
||||||
},
|
},
|
||||||
concepts: {
|
concepts: {
|
||||||
title: "Concepts",
|
title: "Concepts",
|
||||||
link: "canary",
|
link: "latest",
|
||||||
pages: [
|
pages: [
|
||||||
["app", "App", "link:canary"],
|
["app", "App", "link:latest"],
|
||||||
["middleware", "Middlewares", "link:canary"],
|
["middleware", "Middlewares", "link:latest"],
|
||||||
["context", "Context", "link:canary"],
|
["context", "Context", "link:latest"],
|
||||||
|
|
||||||
["routing", "Routing", "link:canary"],
|
["routing", "Routing", "link:latest"],
|
||||||
|
|
||||||
["islands", "Islands", "link:canary"],
|
["islands", "Islands", "link:latest"],
|
||||||
["static-files", "Static files", "link:canary"],
|
["static-files", "Static files", "link:latest"],
|
||||||
|
|
||||||
["file-routing", "File routing", "link:canary"],
|
["file-routing", "File routing", "link:latest"],
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
advanced: {
|
advanced: {
|
||||||
title: "Advanced",
|
title: "Advanced",
|
||||||
link: "canary",
|
link: "latest",
|
||||||
pages: [
|
pages: [
|
||||||
["app-wrapper", "App wrapper", "link:canary"],
|
["app-wrapper", "App wrapper", "link:latest"],
|
||||||
["layouts", "Layouts", "link:canary"],
|
["layouts", "Layouts", "link:latest"],
|
||||||
["error-handling", "Error handling", "link:canary"],
|
["error-handling", "Error handling", "link:latest"],
|
||||||
["partials", "Partials", "link:canary"],
|
["partials", "Partials", "link:latest"],
|
||||||
["forms", "Forms", "link:canary"],
|
["forms", "Forms", "link:latest"],
|
||||||
["define", "Define Helpers", "link:canary"],
|
["define", "Define Helpers", "link:latest"],
|
||||||
["environment-variables", "Environment Variables", "link:canary"],
|
["environment-variables", "Environment Variables", "link:latest"],
|
||||||
["head", "Modifying <head>", "link:canary"],
|
["head", "Modifying <head>", "link:latest"],
|
||||||
["vite", "Vite Plugin Options", "link:canary"],
|
["vite", "Vite Plugin Options", "link:latest"],
|
||||||
["troubleshooting", "Troubleshooting", "link:canary"],
|
["troubleshooting", "Troubleshooting", "link:latest"],
|
||||||
["builder", "Builder (Legacy)", "link:canary"],
|
["builder", "Builder (Legacy)", "link:latest"],
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
deployment: {
|
deployment: {
|
||||||
title: "Deployment",
|
title: "Deployment",
|
||||||
link: "canary",
|
link: "latest",
|
||||||
pages: [
|
pages: [
|
||||||
["deno-deploy", "Deno Deploy", "link:canary"],
|
["deno-deploy", "Deno Deploy", "link:latest"],
|
||||||
["deno-compile", "deno compile", "link:canary"],
|
["deno-compile", "deno compile", "link:latest"],
|
||||||
["docker", "Docker", "link:canary"],
|
["docker", "Docker", "link:latest"],
|
||||||
["cloudflare-workers", "Cloudflare Workers", "link:canary"],
|
["cloudflare-workers", "Cloudflare Workers", "link:latest"],
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
testing: {
|
testing: {
|
||||||
title: "Testing",
|
title: "Testing",
|
||||||
link: "canary",
|
link: "latest",
|
||||||
},
|
},
|
||||||
plugins: {
|
plugins: {
|
||||||
title: "Plugins",
|
title: "Plugins",
|
||||||
link: "canary",
|
link: "latest",
|
||||||
pages: [
|
pages: [
|
||||||
["cors", "cors", "link:canary"],
|
["cors", "cors", "link:latest"],
|
||||||
["csrf", "csrf", "link:canary"],
|
["csrf", "csrf", "link:latest"],
|
||||||
["trailing-slashes", "trailingSlashes", "link:canary"],
|
["trailing-slashes", "trailingSlashes", "link:latest"],
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
examples: {
|
examples: {
|
||||||
title: "Examples",
|
title: "Examples",
|
||||||
link: "latest",
|
link: "latest",
|
||||||
pages: [
|
pages: [
|
||||||
["migration-guide", "Migration Guide", "link:canary"],
|
["migration-guide", "Migration Guide", "link:latest"],
|
||||||
["daisyui", "daisyUI", "link:canary"],
|
["daisyui", "daisyUI", "link:latest"],
|
||||||
["markdown", "Rendering Markdown", "link:canary"],
|
["markdown", "Rendering Markdown", "link:latest"],
|
||||||
["rendering-raw-html", "Rendering raw HTML", "link:canary"],
|
["rendering-raw-html", "Rendering raw HTML", "link:latest"],
|
||||||
[
|
[
|
||||||
"sharing-state-between-islands",
|
"sharing-state-between-islands",
|
||||||
"Sharing state between islands",
|
"Sharing state between islands",
|
||||||
"link:latest",
|
"link:latest",
|
||||||
],
|
],
|
||||||
["active-links", "Active links", "link:canary"],
|
["active-links", "Active links", "link:latest"],
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
latest: {
|
"1.x": {
|
||||||
label: FRESH_VERSIONS[0],
|
label: FRESH_VERSIONS_1x[0],
|
||||||
content: {
|
content: {
|
||||||
introduction: {
|
introduction: {
|
||||||
title: "Introduction",
|
title: "Introduction",
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user