www: cleanup miscellaneous doc items (#1419)

This commit is contained in:
Reed von Redwitz
2023-07-07 16:07:40 +02:00
committed by GitHub
parent 7aad800ced
commit f737e1c4e3
14 changed files with 449 additions and 39 deletions
+28
View File
@@ -0,0 +1,28 @@
---
description: |
Add a global application wrapper to provide common meta tags or context for application routes.
---
An application wrapper is defined in an `_app.tsx` file in `routes/` folder. It
must contain a default export that is a regular Preact component. Only one such
wrapper is allowed per application.
The component to be wrapped is received via props, in addition to a few other
things. This allows for the introduction of a global container functioning as a
template which can be conditioned based on state and params. Note that any state
set by middleware is available via `props.state`.
```tsx
// routes/_app.tsx
import { AppProps } from "$fresh/server.ts";
export default function App({ Component, state }: AppProps) {
//do something with state here
return (
<div class="wrapper">
<Component />
</div>
);
}
```
+117
View File
@@ -0,0 +1,117 @@
---
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 client. This is different from all other
components in Fresh, as they are usually just rendered on the server.
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/MyIsland.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.
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.
## Passing JSX to islands
Islands support passing JSX elements via the `children` property. This allows
you to pass static content rendered by the server to an island in the browser.
```jsx
// route/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>
);
}
```
We can deduce which parts were rendered by the server and which parts where
rendered by an island from the HTML alone. It contains all the information we
need, which allows us to skip the work of having to send a serialized version of
`props.children` to the browser.
### 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.
```jsx
// route/index.tsx
import MyIsland from "../islands/my-island.tsx";
import OtherIsland from "../islands/other-island.tsx";
export default function Home() {
return (
<MyIsland>
<OtherIsland foo="this prop will be serialized">
<p>This text is rendered on the server</p>
</OtherIsland>
</MyIsland>
);
}
```
In essence, fresh allows you to mix static and interactive parts in your app in
a way that's most optimal for your use app. We'll keep sending only the
JavaScript that is needed for the islands to the browser.
```jsx
// route/index.tsx
import MyIsland from "../islands/my-island.tsx";
import OtherIsland from "../islands/other-island.tsx";
export default function Home() {
return (
<MyIsland>
<div>
<h1>Rendered by server</h1>
<OtherIsland>
<p>also rendered by server</p>
</OtherIsland>
</div>
</MyIsland>
);
}
```
+178
View File
@@ -0,0 +1,178 @@
---
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/concepts/app-wrapper.md) wrapper and normal
[routes](/docs/concepts/routes.md).
```ts
// routes/_middleware.ts
import { MiddlewareHandlerContext } from "$fresh/server.ts";
interface State {
data: string;
}
export async function handler(
req: Request,
ctx: MiddlewareHandlerContext<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:
```
└── 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();
},
];
```
## Middleware Destination
To set the stage for this section, `MiddlewareHandlerContext` looks like this:
```ts
export interface MiddlewareHandlerContext<State = Record<string, unknown>>
extends ConnInfo {
next: () => Promise<Response>;
state: State;
destination: router.DestinationKind;
}
```
and `router.DestinationKind` is defined like this:
```ts
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
import { MiddlewareHandlerContext } from "$fresh/server.ts";
export async function handler(req: Request, ctx: MiddlewareHandlerContext) {
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:
```
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.
+90
View File
@@ -0,0 +1,90 @@
---
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.
---
At their core, routes describe how a request for a given path should be handled,
and what the response should be. To do this, routes have two main parts: the
handler, and the component. A route can have either one, or both, but never
neither.
The handler is a function that is called for every request to the route. It
needs to return a response that is then sent to the client. The response could
be anything: a plain text string, a JSON object, an HTML page, a WebSocket
connection, a streaming file, or pretty much anything else. The handler is
passed a `render` function that it can call to invoke rendering a component.
The component is the template for a page. It is a JSX element that is rendered
on the server. The page component gets passed props that can be used by it to
determine exactly what should be rendered. By default components receives props
consisting of: the request URL, the matching route (as a string), the matches
from the URL pattern match, any state set by middleware, and any data passed to
the handler's `render` function.
## Handler route
Let's look at a basic route that returns a plain text string:
```tsx
// routes/plain.tsx
import { HandlerContext, Handlers } from "$fresh/server.ts";
export const handler: Handlers = {
GET(_req: Request, _ctx: HandlerContext) {
return new Response("Hello World");
},
};
```
To define a handler, one needs to export a `handler` function or object from the
route module. If the handler is an object, each key in the object is the name of
the HTTP method that the handler should be called for. For example the `GET`
handler above is called for `GET` requests. If the handler is a function, it is
called for all requests regardless of the method. If an HTTP method does not
have a corresponding handler, a 405 HTTP error is returned.
## Component route
Now, let's render some HTML using the route component:
```tsx
// routes/html.tsx
import { PageProps } from "$fresh/server.ts";
export default function Page(props: PageProps) {
return <div>You are on the page '{props.url.href}'.</div>;
}
```
The page component needs to be the default export of the route module. It is
passed props that can be used to render the page.
As you can see in the second example, if no handler is explicitly defined a
default handler is used that just renders out the page component if present. You
can also override the default handler though to modify how exactly rendering
should work.
## Mixed handler and component route
In the below example, a custom handler is used to add a custom header to the
response after rendering the page component.
```tsx
// routes/html.tsx
import { HandlerContext, Handlers, PageProps } from "$fresh/server.ts";
export const handler: Handlers = {
async GET(_req: Request, ctx: HandlerContext) {
const resp = await ctx.render();
resp.headers.set("X-Custom-Header", "Hello World");
return resp;
},
};
export default function Page(props: PageProps) {
return <div>You are on the page '{props.url.href}'.</div>;
}
```
+2 -4
View File
@@ -9,16 +9,14 @@ wrapper is allowed per application.
The component to be wrapped is received via props, in addition to a few other
things. This allows for the introduction of a global container functioning as a
template which can be conditioned based on state and params. Note that any state
set by middleware is available via `props.state`.
template which can be conditioned based on state and params.
```tsx
// routes/_app.tsx
import { AppProps } from "$fresh/server.ts";
export default function App({ Component, state }: AppProps) {
//do something with state here
export default function App({ Component }: AppProps) {
return (
<div class="wrapper">
<Component />
+3 -3
View File
@@ -54,7 +54,7 @@ Islands support passing JSX elements via the `children` property. This allows
you to pass static content rendered by the server to an island in the browser.
```jsx
// file: /route/index.tsx
// route/index.tsx
import MyIsland from "../islands/my-island.tsx";
export default function Home() {
@@ -78,7 +78,7 @@ like a normal Preact component, but still receive the serialized props if any
were present.
```jsx
// file: /route/index.tsx
// route/index.tsx
import MyIsland from "../islands/my-island.tsx";
import OtherIsland from "../islands/other-island.tsx";
@@ -98,7 +98,7 @@ a way that's most optimal for your use app. We'll keep sending only the
JavaScript that is needed for the islands to the browser.
```jsx
// file: /route/index.tsx
// route/index.tsx
import MyIsland from "../islands/my-island.tsx";
import OtherIsland from "../islands/other-island.tsx";
+12 -12
View File
@@ -10,10 +10,7 @@ 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/concepts/app-wrapper.md) wrapper and normal
[routes](/docs/concepts/routes.md).
be used to pass arbitrary data to downstream (or upstream) handlers.
```ts
// routes/_middleware.ts
@@ -50,11 +47,15 @@ specific first).
For example, take a project with the following routes:
- `routes/_middleware.ts`
- `routes/index.ts`
- `routes/admin/_middleware.ts`
- `routes/admin/index.ts`
- `routes/admin/signin.ts`
```
└── routes
   ├── _middleware.ts
   ├── index.ts
   └── admin
      ├── _middleware.ts
      └── index.ts
      └── signin.ts
```
For a request to `/` the request will flow like this:
@@ -113,9 +114,8 @@ and `router.DestinationKind` is defined like this:
export type DestinationKind = "internal" | "static" | "route" | "notFound";
```
This is useful for 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`.
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
+1 -3
View File
@@ -2,8 +2,6 @@
description: Plugins can add new functionality to Fresh without requiring significant complexity.
---
> Plugins are only available in Fresh 1.1 and above.
Plugins can dynamically add new functionality to Fresh without exposing
significant complexity to the user. Users can add plugins by importing and
initializing them in their `main.ts` file:
@@ -42,7 +40,7 @@ available (explained below).
A Fresh plugin is just a JavaScript object that conforms to the
[Plugin](https://deno.land/x/fresh/server.ts?s=Plugin) interface. The only
required property of a plugin is it's name. Names must only contain the
required property of a plugin is its name. Names must only contain the
characters `a`-`z`, and `_`.
```ts
+2 -2
View File
@@ -18,8 +18,8 @@ The component is the template for a page. It is a JSX element that is rendered
on the server. The page component gets passed props that can be used by it to
determine exactly what should be rendered. By default components receives props
consisting of: the request URL, the matching route (as a string), the matches
from the URL pattern match, any state set by middleware, and any data passed to
the handler's `render` function.
from the URL pattern match, and any data passed to the handler's `render`
function.
## Handler route
+1 -1
View File
@@ -42,7 +42,7 @@ export default function Page() {
```
Fresh also does this automatically for `src` and `srcset` attributes in `<img>`
and `<source>` HTML tags. These will automatically use "locked" paths if fresh
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.
+4 -4
View File
@@ -35,7 +35,7 @@ full files are available at the bottom for reference.
`POST` (create) is used to create a resource.
```tsx
// /routes/api/index.ts
// routes/api/index.ts
export const handler: Handlers<User | null> = {
async POST(req, _ctx) {
const user = await req.json() as User;
@@ -72,7 +72,7 @@ You should receive the same thing back:
method. You can use `GET` to fetch database content, markdown, or static files.
```tsx
// /routes/api/[id].ts
// routes/api/[id].ts
export const handler: Handlers<User | null> = {
async GET(_req, ctx) {
const id = ctx.params.id;
@@ -103,7 +103,7 @@ The short version of it: `PUT` requires the entire object to be submitted, while
An example of an update endpoint using `PUT`:
```tsx
// /routes/api/[id].ts
// routes/api/[id].ts
export const handler: Handlers<User | null> = {
async PUT(req, ctx) {
const id = ctx.params.id;
@@ -153,7 +153,7 @@ No need to send in the id in this case.
`DELETE` (delete) is used to delete a resource.
```tsx
// /routes/api/[id].ts
// routes/api/[id].ts
export const handler: Handlers<User | null> = {
async DELETE(_req, ctx) {
const id = ctx.params.id;
+1
View File
@@ -15,6 +15,7 @@ The following file uses
handle the three cases. It's assumed this file is called `[slug].tsx`:
```ts
// routes/[slug].tsx
import { Handlers, PageProps } from "$fresh/server.ts";
import { extract } from "$std/front_matter/yaml.ts";
import { CSS, render } from "$gfm";
@@ -12,6 +12,7 @@ All of this content is lifted from this great
Imagine we have `Counter.tsx` like this:
```ts
// islands/Counter.tsx
import { useSignal } from "@preact/signals";
import { Button } from "../components/Button.tsx";
@@ -49,6 +50,7 @@ here, yet.
But we can switch things up by looking at a `SynchronizedSlider.tsx` like this:
```ts
// islands/SynchronizedSlider.tsx
import { Signal } from "@preact/signals";
interface SliderProps {
@@ -74,6 +76,7 @@ export default function SynchronizedSlider(props: SliderProps) {
Now if we were to do the following...
```ts
// routes/index.tsx
export default function Home() {
const sliderSignal = useSignal(50);
return (
@@ -93,17 +96,15 @@ they would all use the same value.
We can also create a `signal` in a utility file and export it for consumption
across multiple places.
`./utils/cart.ts`
```ts
// utils/cart.ts
import { signal } from "@preact/signals";
export const cart = signal<string[]>([]);
```
`./islands/AddToCart.tsx`
```ts
// islands/AddToCart.tsx
import { Button } from "../components/Button.tsx";
import { cart } from "../utils/cart.ts";
@@ -125,9 +126,8 @@ export default function AddToCart(props: AddToCartProps) {
}
```
`./islands/Cart.tsx`
```ts
// islands/Cart.tsx
import { Button } from "../components/Button.tsx";
import { cart } from "../utils/cart.ts";
import * as icons from "../components/Icons.tsx";
+4 -4
View File
@@ -45,11 +45,11 @@ const toc: RawTableOfContents = {
link: "latest",
pages: [
["architecture", "Architecture", "link:latest"],
["routes", "Routes", "link:latest"],
["routes", "Routes", "link:canary"],
["forms", "Forms", "link:latest"],
["islands", "Interactive islands", "link:latest"],
["islands", "Interactive islands", "link:canary"],
["static-files", "Static files", "link:latest"],
["middleware", "Route middleware", "link:latest"],
["middleware", "Route middleware", "link:canary"],
["error-pages", "Error pages", "link:latest"],
["routing", "Routing", "link:latest"],
["data-fetching", "Data fetching", "link:latest"],
@@ -57,7 +57,7 @@ const toc: RawTableOfContents = {
["plugins", "Plugins", "link:latest"],
["updating", "Updating Fresh", "link:latest"],
["app-wrapper", "Application wrapper", "link:latest"],
["server-configuration", "Server configuration", "link:latest"],
["server-configuration", "Server configuration", "link:canary"],
],
},
integrations: {