www: cleanup miscellaneous doc items (#1419)
This commit is contained in:
@@ -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>
|
||||
);
|
||||
}
|
||||
```
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
```
|
||||
@@ -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.
|
||||
@@ -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>;
|
||||
}
|
||||
```
|
||||
Reference in New Issue
Block a user