docs: make 2.x the default version (#3369)
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
---
|
||||
description: |
|
||||
Fresh optimize assets ahead of time, which makes pages load way quicker.
|
||||
---
|
||||
|
||||
Fresh enables you to pre-optimize frontend assets before the code is deployed.
|
||||
During that process the code for Islands will be compressed and optimized, so
|
||||
that Fresh can send as little code as possible to the browser. Depending on the
|
||||
amount of code an island needs, this process can take several seconds if done on
|
||||
the fly server-side.
|
||||
|
||||
Doing those optimizations ahead-of-time and deploying the already optimized
|
||||
assets alongside with your code, allows Fresh to treat them as like any other
|
||||
static file and can serve it immediately without any further processing. On
|
||||
pages with islands, having to do no processing greatly speeds up page load
|
||||
times.
|
||||
|
||||
Plugins can build static assets during ahead-of-time builds. This can be used to
|
||||
pre-process or generate CSS files, for example.
|
||||
|
||||
## Creating an optimized build
|
||||
|
||||
To have Fresh optimize all the assets, run one of the following commands:
|
||||
|
||||
```sh Terminal
|
||||
# As a task in newer Fresh projects
|
||||
deno task build
|
||||
# or invoke it manually
|
||||
deno run -A dev.ts build
|
||||
```
|
||||
|
||||
This will create a `_fresh` folder in the project directory. That folder
|
||||
contains the optimized assets and a `snapshot.json` file which includes some
|
||||
metadata for Fresh.
|
||||
|
||||
Any other static files generated by plugins will be stored in the
|
||||
`_fresh/static` subfolder. They will be served the same as other
|
||||
[static files](/docs/1.x/concepts/static-files.md).
|
||||
|
||||
> [info]: The `_fresh` folder should not be committed to the repository. Add an
|
||||
> entry in the `.gitignore` file to ensure that it is not committed. Create that
|
||||
> file at the root of your git repository if not present.
|
||||
>
|
||||
> ```gitignore .gitignore
|
||||
> # Ignore fresh build directory
|
||||
> _fresh/
|
||||
> ```
|
||||
|
||||
## Running Fresh with optimized assets
|
||||
|
||||
When Fresh is started in non-development mode (usually via `main.ts`), Fresh
|
||||
will automatically pick up optimized assets when a `_fresh` folder exists. If
|
||||
found, Fresh will print the following message to the terminal:
|
||||
|
||||
```sh Terminal output
|
||||
Using snapshot found at /path/to/project/_fresh
|
||||
```
|
||||
|
||||
## Deploying an optimized Fresh project
|
||||
|
||||
If you are deploying a Fresh project to Deno Deploy, you can use ahead-of-time
|
||||
builds to optimize the assets before deploying them. This will make your
|
||||
application load quicker.
|
||||
|
||||
Open the Deno Deploy dashboard for your project and head to the "Git
|
||||
Integration" section in the project settings. Enter `deno task build` in the
|
||||
"Build command" field and save. This will switch your Deno Deploy project to use
|
||||
ahead-of-time builds.
|
||||
|
||||
## Migrating existing projects with Plugins
|
||||
|
||||
If you're using Fresh plugins, extract them into a `fresh.config.ts` file, so
|
||||
that both the `dev.ts` and `main.ts` script have access to them.
|
||||
|
||||
```ts fresh.config.ts
|
||||
import { defineConfig } from "$fresh/server.ts";
|
||||
import twindPlugin from "$fresh/plugins/twind.ts";
|
||||
import twindConfig from "./twind.config.ts";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [twindPlugin(twindConfig)],
|
||||
});
|
||||
```
|
||||
|
||||
```ts main.ts
|
||||
import { start } from "$fresh/server.ts";
|
||||
import manifest from "./fresh.gen.ts";
|
||||
import config from "./fresh.config.ts";
|
||||
|
||||
await start(manifest, config);
|
||||
```
|
||||
|
||||
```ts dev.ts
|
||||
import dev from "$fresh/dev.ts";
|
||||
import config from "./fresh.config.ts";
|
||||
|
||||
await dev(import.meta.url, "./main.ts", config);
|
||||
```
|
||||
@@ -0,0 +1,106 @@
|
||||
---
|
||||
description: |
|
||||
Add a global app wrapper to provide common meta tags or context for application routes.
|
||||
---
|
||||
|
||||
An app wrapper is defined in an `_app.tsx` file in `routes/` folder and is
|
||||
typically used to create the outer structure of an HTML document. 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 { PageProps } from "$fresh/server.ts";
|
||||
|
||||
export default function App({ Component, state }: PageProps) {
|
||||
// do something with state here
|
||||
return (
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>My Fresh app</title>
|
||||
</head>
|
||||
<body>
|
||||
<Component />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Async app wrapper
|
||||
|
||||
Similar to routes and layouts, the app wrapper can be made asynchronous. This
|
||||
changes the function signature so that the first argument is the `Request`
|
||||
instance and the second one is the `FreshContext`.
|
||||
|
||||
```tsx routes/_app.tsx
|
||||
import { FreshContext } from "$fresh/server.ts";
|
||||
|
||||
export default async function App(req: Request, ctx: FreshContext) {
|
||||
const data = await loadData();
|
||||
|
||||
return (
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>My Fresh app</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Hello {data.name}</h1>
|
||||
<ctx.Component />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Define helper
|
||||
|
||||
To make it quicker to type the async app wrapper, Fresh includes a `defineApp`
|
||||
helper which already infers the correct types for you.
|
||||
|
||||
```tsx routes/_app.tsx
|
||||
import { defineApp } from "$fresh/server.ts";
|
||||
|
||||
export default defineApp(async (req, ctx) => {
|
||||
const data = await loadData();
|
||||
|
||||
return (
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>My Fresh app</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Hello {data.name}</h1>
|
||||
<ctx.Component />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
## Disabling the app wrapper
|
||||
|
||||
Rendering the app wrapper can be skipped on a route or layout basis. To do that,
|
||||
set `skipAppWrapper: true` to the layout or route config.
|
||||
|
||||
```tsx routes/my-special-route.tsx
|
||||
import { RouteConfig } from "$fresh/server.ts";
|
||||
|
||||
export const config: RouteConfig = {
|
||||
skipAppWrapper: true, // Skip the app wrapper during rendering
|
||||
};
|
||||
|
||||
export default function Page() {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
description: |
|
||||
Fresh's architecture is designed to make it easy to build fast, scalable, and reliable applications.
|
||||
---
|
||||
|
||||
Fresh is designed to make it easy to build fast, scalable, and reliable
|
||||
applications. To do this, it makes opinionated decisions about how one should
|
||||
build web applications. These decisions are backed by strong empirical data
|
||||
gathered from experts in the field. Some examples of these principles are:
|
||||
|
||||
- Page load times should be reduced to a minimum.
|
||||
- The work performed on the client should be minimized.
|
||||
- Errors should have a small blast radius - stuff should gracefully degrade.
|
||||
|
||||
The single biggest architecture decision that Fresh makes is its usage of the
|
||||
[islands architecture][islands] pattern. This means that Fresh applications ship
|
||||
pure HTML to the client by default. Parts of a server-rendered page can then be
|
||||
independently re-hydrated with interactive widgets (islands). This means that
|
||||
the client is only responsible for rendering parts of the page that are
|
||||
interactive enough to warrant the extra effort. Any content that is purely
|
||||
static does not have related client-side JavaScript and is thus very
|
||||
lightweight.
|
||||
|
||||
<!-- TODO(lucacasonato): elaborate on request handling, form actions, etc. -->
|
||||
|
||||
[islands]: https://www.patterns.dev/posts/islands-architecture/
|
||||
@@ -0,0 +1,75 @@
|
||||
---
|
||||
description: |
|
||||
Data fetching in Fresh happens inside of route handler functions. These can pass route data to the page via page props.
|
||||
---
|
||||
|
||||
Server side data fetching in Fresh is accomplished through asynchronous handler
|
||||
functions. These handler functions can call a `ctx.render()` function with the
|
||||
data to be rendered as an argument. This data can then be retrieved by the page
|
||||
component through the `data` property on the `props`.
|
||||
|
||||
Here is an example:
|
||||
|
||||
```tsx routes/projects/[id].tsx
|
||||
interface Project {
|
||||
name: string;
|
||||
stars: number;
|
||||
}
|
||||
|
||||
export const handler: Handlers<Project> = {
|
||||
async GET(_req, ctx) {
|
||||
const project = await db.projects.findOne({ id: ctx.params.id });
|
||||
if (!project) {
|
||||
return ctx.renderNotFound({
|
||||
message: "Project does not exist",
|
||||
});
|
||||
}
|
||||
return ctx.render(project);
|
||||
},
|
||||
};
|
||||
|
||||
export default function ProjectPage(props: PageProps<Project>) {
|
||||
return (
|
||||
<div>
|
||||
<h1>{props.data.name}</h1>
|
||||
<p>{props.data.stars} stars</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The type parameter on the `PageProps`, `Handlers`, `Handler`, and `FreshContext`
|
||||
can be used to enforce a TypeScript type to use for the render data. Fresh
|
||||
enforces during type checking that the types in all of these fields are
|
||||
compatible within a single page.
|
||||
|
||||
## Asynchronous routes
|
||||
|
||||
As a shortcut for combining a `GET` handler with a route, you can define your
|
||||
route as `async`. An `async` route (a route that returns a promise) will be
|
||||
called with the `Request` and a `RouteContext` (similar to a `HandlerContext`).
|
||||
Here is the above example rewritten using this shortcut:
|
||||
|
||||
```tsx routes/projects/[id].tsx
|
||||
interface Project {
|
||||
name: string;
|
||||
stars: number;
|
||||
}
|
||||
|
||||
export default async function ProjectPage(_req, ctx: FreshContext) {
|
||||
const project: Project | null = await db.projects.findOne({
|
||||
id: ctx.params.id,
|
||||
});
|
||||
|
||||
if (!project) {
|
||||
return <h1>Project not found</h1>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1>{project.name}</h1>
|
||||
<p>{project.stars} stars</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,87 @@
|
||||
---
|
||||
description: |
|
||||
Fresh can be deployed to a variety of platforms easily.
|
||||
---
|
||||
|
||||
While Fresh is designed to be deployed to [Deno Deploy][deno-deploy], it can be
|
||||
deployed to any system or platform that can run a Deno based web server.
|
||||
|
||||
Here are instructions for specific providers / systems:
|
||||
|
||||
- [Deno Deploy](#deno-deploy)
|
||||
- [Docker](#docker)
|
||||
- [Self Contained Executable](#self-contained-executable)
|
||||
|
||||
## Deno Deploy
|
||||
|
||||
The recommended way to deploy Fresh is by using Deno Deploy. Deno Deploy
|
||||
provides a GitHub integration that can deploy your Fresh projects to its
|
||||
globally distributed edge network in seconds, automatically.
|
||||
|
||||
View [the getting started guide][deploy-to-production] for instructions on how
|
||||
to deploy Fresh to Deno Deploy.
|
||||
|
||||
## Docker
|
||||
|
||||
You can deploy Fresh to any platform that can run Docker containers. Docker is a
|
||||
tool to containerize projects and portably run them on any supported platform.
|
||||
|
||||
When packaging your Fresh app for Docker, it is important that you set the
|
||||
`DENO_DEPLOYMENT_ID` environment variable in your container. This variable needs
|
||||
to be set to an opaque string ID that represents the version of your application
|
||||
that is currently being run. This could be a Git commit hash, or a hash of all
|
||||
files in your project. It is critical for the function of Fresh that this ID
|
||||
changes when _any_ file in your project changes - if it doesn't, incorrect
|
||||
caching **will** cause your project to not function correctly.
|
||||
|
||||
Here is an example `Dockerfile` for a Fresh project:
|
||||
|
||||
```dockerfile Dockerfile
|
||||
FROM denoland/deno:1.38.3
|
||||
|
||||
ARG GIT_REVISION
|
||||
ENV DENO_DEPLOYMENT_ID=${GIT_REVISION}
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY . .
|
||||
RUN deno cache main.ts
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["run", "-A", "main.ts"]
|
||||
```
|
||||
|
||||
To build your Docker image inside of a Git repository:
|
||||
|
||||
```sh Terminal
|
||||
$ docker build --build-arg GIT_REVISION=$(git rev-parse HEAD) -t my-fresh-app .
|
||||
```
|
||||
|
||||
Then run your Docker container:
|
||||
|
||||
```sh Terminal
|
||||
$ docker run -t -i -p 80:8000 my-fresh-app
|
||||
```
|
||||
|
||||
To deploy to a cloud provider, push it to a container registry and follow their
|
||||
documentation.
|
||||
|
||||
- [Amazon Web Services][aws-container-registry]
|
||||
- [Google Cloud][gcp-container-registry]
|
||||
|
||||
## Self Contained Executable
|
||||
|
||||
With Deno 2.1, you can create a self-contained executable of your Fresh project
|
||||
that includes all assets and dependencies. This executable can run on any
|
||||
platform without requiring Deno to be installed.
|
||||
|
||||
```sh Terminal
|
||||
$ deno task build
|
||||
$ deno compile --include static --include _fresh --include deno.json -A main.ts
|
||||
```
|
||||
|
||||
[aws-container-registry]: https://docs.aws.amazon.com/AmazonECS/latest/userguide/create-container-image.html#create-container-image-push-ecr
|
||||
[gcp-container-registry]: https://cloud.google.com/container-registry/docs/pushing-and-pulling
|
||||
[deno-deploy]: https://deno.com/deploy
|
||||
[deploy-to-production]: /docs/1.x/getting-started/deploy-to-production
|
||||
@@ -0,0 +1,82 @@
|
||||
---
|
||||
description: |
|
||||
Error pages can be used to customize the page that is shown when an error occurs in the application.
|
||||
---
|
||||
|
||||
Fresh supports customizing the `404 Not Found`, and the
|
||||
`500 Internal Server Error` pages. These are shown when a request is made but no
|
||||
matching route exists, and when a middleware, route handler, or page component
|
||||
throws an error respectively.
|
||||
|
||||
### 404: Not Found
|
||||
|
||||
The 404 page can be customized by creating a `_404.tsx` file in the `routes/`
|
||||
folder. The file must have a default export that is a regular Preact component.
|
||||
A props object of type `PageProps` is passed in as an argument.
|
||||
|
||||
```tsx routes/_404.tsx
|
||||
import { PageProps } from "$fresh/server.ts";
|
||||
|
||||
export default function NotFoundPage({ url }: PageProps) {
|
||||
return <p>404 not found: {url.pathname}</p>;
|
||||
}
|
||||
```
|
||||
|
||||
#### Manually render 404 pages
|
||||
|
||||
The `_404.tsx` file will be invoked automatically when no route matches the URL.
|
||||
In some cases, one needs to manually trigger the rendering of the 404 page, for
|
||||
example when the route did match, but the requested resource does not exist.
|
||||
This can be achieved with `ctx.renderNotFound`.
|
||||
|
||||
```tsx routes/blog/[slug].tsx
|
||||
import { Handlers, PageProps } from "$fresh/server.ts";
|
||||
|
||||
export const handler: Handlers = {
|
||||
async GET(req, ctx) {
|
||||
const blogpost = await fetchBlogpost(ctx.params.slug);
|
||||
if (!blogpost) {
|
||||
return ctx.renderNotFound({
|
||||
custom: "prop",
|
||||
});
|
||||
}
|
||||
return ctx.render({ blogpost });
|
||||
},
|
||||
};
|
||||
|
||||
export default function BlogpostPage({ data }) {
|
||||
return (
|
||||
<article>
|
||||
<h1>{data.blogpost.title}</h1>
|
||||
{/* rest of your page */}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
This can also be achieved by throwing an error, if you're uninterested in
|
||||
passing specific data to your 404 page:
|
||||
|
||||
```tsx routes/missing-page.tsx
|
||||
import { Handlers } from "$fresh/server.ts";
|
||||
|
||||
export const handler: Handlers = {
|
||||
GET(_req, _ctx) {
|
||||
throw new Deno.errors.NotFound();
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### 500: Internal Server Error
|
||||
|
||||
The 500 page can be customized by creating a `_500.tsx` file in the `routes/`
|
||||
folder. The file must have a default export that is a regular Preact component.
|
||||
A props object of type `PageProps` is passed in as an argument.
|
||||
|
||||
```tsx routes/_500.tsx
|
||||
import { PageProps } from "$fresh/server.ts";
|
||||
|
||||
export default function Error500Page({ error }: PageProps) {
|
||||
return <p>500 internal error: {(error as Error).message}</p>;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,120 @@
|
||||
---
|
||||
description: |
|
||||
Robustly handle user inputs using HTML `<form>` elements client side, and form
|
||||
submission handlers server side.
|
||||
---
|
||||
|
||||
For stronger resiliency and user experience, Fresh relies on native browser
|
||||
support for form submissions with the HTML `<form>` element.
|
||||
|
||||
In the browser, a `<form>` submit will send an HTML action (usually `GET` or
|
||||
`POST`) to the server, which responds with a new page to render.
|
||||
|
||||
## POST request with `application/x-www-form-urlencoded`
|
||||
|
||||
Forms typically submit as a `GET` request with data encoded in the URL's search
|
||||
parameters, or as a `POST` request with either an
|
||||
`application/x-www-form-urlencoded` or `multipart/form-data` body.
|
||||
|
||||
This example demonstrates how to handle `application/x-www-form-urlencoded`
|
||||
`<form>` submissions:
|
||||
|
||||
```tsx routes/subscribe.tsx
|
||||
import { Handlers } from "$fresh/server.ts";
|
||||
|
||||
export const handler: Handlers = {
|
||||
async GET(req, ctx) {
|
||||
return await ctx.render();
|
||||
},
|
||||
async POST(req, ctx) {
|
||||
const form = await req.formData();
|
||||
const email = form.get("email")?.toString();
|
||||
|
||||
// Add email to list.
|
||||
|
||||
// Redirect user to thank you page.
|
||||
const headers = new Headers();
|
||||
headers.set("location", "/thanks-for-subscribing");
|
||||
return new Response(null, {
|
||||
status: 303, // See Other
|
||||
headers,
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
export default function Subscribe() {
|
||||
return (
|
||||
<>
|
||||
<form method="post">
|
||||
<input type="email" name="email" value="" />
|
||||
<button type="submit">Subscribe</button>
|
||||
</form>
|
||||
</>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
When the user submits the form, Deno will retrieve the `email` value using the
|
||||
request's `formData()` method, add the email to a list, and redirect the user to
|
||||
a thank you page.
|
||||
|
||||
## Handling file uploads
|
||||
|
||||
File uploads can be handled in a very similar manner to the example above. Note
|
||||
that this time, we have to explicitly declare the form's encoding to be
|
||||
`multipart/form-data`.
|
||||
|
||||
```tsx routes/subscribe.tsx
|
||||
import { Handlers, type PageProps } from "$fresh/server.ts";
|
||||
|
||||
interface Props {
|
||||
message: string | null;
|
||||
}
|
||||
|
||||
export const handler: Handlers<Props> = {
|
||||
async GET(req, ctx) {
|
||||
return await ctx.render({
|
||||
message: null,
|
||||
});
|
||||
},
|
||||
async POST(req, ctx) {
|
||||
const form = await req.formData();
|
||||
const file = form.get("my-file") as File;
|
||||
|
||||
if (!file) {
|
||||
return ctx.render({
|
||||
message: `Please try again`,
|
||||
});
|
||||
}
|
||||
|
||||
const name = file.name;
|
||||
const contents = await file.text();
|
||||
|
||||
console.log(contents);
|
||||
|
||||
return ctx.render({
|
||||
message: `${name} uploaded!`,
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
export default function Upload(props: PageProps<Props>) {
|
||||
const { message } = props.data;
|
||||
return (
|
||||
<>
|
||||
<form method="post" encType="multipart/form-data">
|
||||
<input type="file" name="my-file" />
|
||||
<button type="submit">Upload</button>
|
||||
</form>
|
||||
{message ? <p>{message}</p> : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## A note of caution
|
||||
|
||||
These examples are simplified to demonstrate how Deno and Fresh handle HTTP
|
||||
requests. In the Real World™, you'll want to validate your data (_especially the
|
||||
file type_) and protect against cross-site request forgery. Consider yourself
|
||||
warned.
|
||||
@@ -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>;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,125 @@
|
||||
---
|
||||
description: |
|
||||
Add a layout to provide common meta tags, context for application sub routes, and common layout.
|
||||
---
|
||||
|
||||
A layout is defined in a `_layout.tsx` file in any sub directory (at any level)
|
||||
under the `routes/` folder. It must contain a default export that is a regular
|
||||
Preact component. Only one such layout is allowed per sub directory.
|
||||
|
||||
```txt-files Project structure
|
||||
<project root>
|
||||
└── routes
|
||||
├── sub
|
||||
│ ├── page.tsx
|
||||
│ └── index.tsx
|
||||
├── other
|
||||
│ ├── _layout.tsx # will be applied on top of `routes/_layout.tsx`
|
||||
│ └── page.tsx
|
||||
├── _layout.tsx # will be applied to all routes
|
||||
└── _app.tsx
|
||||
```
|
||||
|
||||
The component to be wrapped is received via props, in addition to a few other
|
||||
things. This allows for the introduction of a global container functioning as a
|
||||
template which can be conditioned based on state and params. Note that any state
|
||||
set by middleware is available via `props.state`.
|
||||
|
||||
```tsx routes/sub/_layout.tsx
|
||||
import { PageProps } from "$fresh/server.ts";
|
||||
|
||||
export default function Layout({ Component, state }: PageProps) {
|
||||
// do something with state here
|
||||
return (
|
||||
<div class="layout">
|
||||
<Component />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Async layouts
|
||||
|
||||
In case you need to fetch data asynchronously before rendering the layout, you
|
||||
can use an async layout to do so.
|
||||
|
||||
```tsx routes/sub/_layout.tsx
|
||||
import { FreshContext } from "$fresh/server.ts";
|
||||
|
||||
export default async function Layout(req: Request, ctx: FreshContext) {
|
||||
// do something with state here
|
||||
const data = await loadData();
|
||||
|
||||
return (
|
||||
<div class="layout">
|
||||
<p>{data.greeting}</p>
|
||||
<ctx.Component />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Define helper
|
||||
|
||||
To make it a little quicker to write async layouts, Fresh ships with a
|
||||
`defineLayout` helper which automatically infers the correct types for the
|
||||
function arguments.
|
||||
|
||||
```tsx routes/greet/_layout.tsx
|
||||
import { defineLayout } from "$fresh/server.ts";
|
||||
|
||||
export default defineLayout(async (req, ctx) => {
|
||||
const data = await loadData();
|
||||
|
||||
return (
|
||||
<div class="layout">
|
||||
<p>{data.greeting}</p>
|
||||
<ctx.Component />
|
||||
</div>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
## Opting out of layout inheritance
|
||||
|
||||
Sometimes you want to opt out of the layout inheritance mechanism for a
|
||||
particular route. This can be done via route configuration. Picture a directory
|
||||
structure like this:
|
||||
|
||||
```txt-files Project structure
|
||||
└── <root>/routes
|
||||
├── sub
|
||||
│ ├── _layout_.tsx
|
||||
│ ├── special.tsx # should not inherit layouts
|
||||
│ └── index.tsx
|
||||
└── _layout.tsx
|
||||
```
|
||||
|
||||
To make `routes/sub/special.tsx` opt out of rendering layouts we can set
|
||||
`skipInheritedLayouts: true`.
|
||||
|
||||
```tsx routes/sub/special.tsx
|
||||
import { RouteConfig } from "$fresh/server.ts";
|
||||
|
||||
export const config: RouteConfig = {
|
||||
skipInheritedLayouts: true, // Skip already inherited layouts
|
||||
};
|
||||
|
||||
export default function MyPage() {
|
||||
return <p>Hello world</p>;
|
||||
}
|
||||
```
|
||||
|
||||
You can skip already inherited layouts inside a layout file:
|
||||
|
||||
```tsx routes/special/_layout.tsx
|
||||
import { LayoutConfig } from "$fresh/server.ts";
|
||||
|
||||
export const config: LayoutConfig = {
|
||||
skipInheritedLayouts: true, // Skip already inherited layouts
|
||||
};
|
||||
|
||||
export default function MyPage() {
|
||||
return <p>Hello world</p>;
|
||||
}
|
||||
```
|
||||
@@ -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" },
|
||||
});
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,228 @@
|
||||
---
|
||||
description: |
|
||||
Partials allow areas of a page to be updated without causing the browser to reload the page. They enable optimized fine grained UI updates and can be used to do client-side navigation.
|
||||
---
|
||||
|
||||
Partials allow areas of the page to be updated with new content by the server
|
||||
without causing the browser to reload the page. They make your website feel more
|
||||
app-like because only the parts of the page that need to be updated will be
|
||||
updated.
|
||||
|
||||
## Enabling partials
|
||||
|
||||
Partials are enabled by adding a `f-client-nav` attribute to an HTML element and
|
||||
wrapping one or more areas in the page with a
|
||||
`<Partial name="my-partial">`-component.
|
||||
|
||||
The quickest way to get started is to enable partials for every page in
|
||||
`routes/_app.tsx` by making the following changes.
|
||||
|
||||
```diff routes/_app.tsx
|
||||
import { PageProps } from "$fresh/server.ts";
|
||||
+ import { Partial } from "$fresh/runtime.ts";
|
||||
|
||||
export default function App({ Component }: PageProps) {
|
||||
return (
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>My Fresh app</title>
|
||||
</head>
|
||||
- <body>
|
||||
+ <body f-client-nav>
|
||||
+ <Partial name="body">
|
||||
<Component />
|
||||
+ </Partial>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
By adding the `f-client-nav` attribute, we enable partials for every element
|
||||
beneath the `<body>`-tag. To mark an area of the page as a partial we wrap it
|
||||
with a `<Partial>`-component with a unique name.
|
||||
|
||||
Behind the scenes, when the user clicks an `<a>`-tag, Fresh fetches the new page
|
||||
and only pulls out the relevant content out of the HTML response. When it finds
|
||||
a matching partial area it will update the content inside the partial.
|
||||
|
||||
> [info]: The `name` prop of the `<Partial>` component is expected to be unique
|
||||
> among Partials. That's how Fresh knows which parts of the response need to go
|
||||
> on the current page.
|
||||
|
||||
> [info]: Passing `f-client-nav={false}` disables client side navigation for all
|
||||
> elements below the current node.
|
||||
|
||||
### Optimizing partial requests
|
||||
|
||||
By default, with `f-client-nav` set, Fresh fetches the full next page and only
|
||||
picks out the relevant parts of the response. We can optimize this pattern
|
||||
further by only rendering the parts we need, instead of always rendering the
|
||||
full page. This is done by adding the `f-partial` attribute to a link.
|
||||
|
||||
```diff routes/_app.tsx
|
||||
- <a href="/docs/routes">Routes</a>
|
||||
+ <a href="/docs/routes" f-partial="/partials/docs/routes">Routes</a>
|
||||
```
|
||||
|
||||
When the `f-partial` attribute is present, Fresh will navigate to the page URL
|
||||
defined in the `href` attribute, but fetch the updated UI from the URL specified
|
||||
in `f-partial` instead. This can be a highly optimized route that only delivers
|
||||
the content you care about.
|
||||
|
||||
Let's use a typical documentation page layout as an example. It often features a
|
||||
main content area and a sidebar of links to switch between pages of the
|
||||
documentation (marked green here).
|
||||
|
||||

|
||||
|
||||
The code for such a page (excluding styling) might look like this:
|
||||
|
||||
```tsx routes/docs/[id].tsx
|
||||
export default defineRoute(async (req, ctx) => {
|
||||
const content = await loadContent(ctx.params.id);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<aside>
|
||||
<a href="/docs/page1">Page 1</a>
|
||||
<a href="/docs/page2">Page 2</a>
|
||||
</aside>
|
||||
<Partial name="docs-content">
|
||||
{content}
|
||||
</Partial>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
An optimal route that only renders the content instead of the outer layout with
|
||||
the sidebar might look like this respectively.
|
||||
|
||||
```tsx routes/partials/docs/[id].tsx
|
||||
import { defineRoute, RouteConfig } from "$fresh/server.ts";
|
||||
import { Partial } from "$fresh/runtime.ts";
|
||||
|
||||
// We only want to render the content, so disable
|
||||
// the `_app.tsx` template as well as any potentially
|
||||
// inherited layouts
|
||||
export const config: RouteConfig = {
|
||||
skipAppWrapper: true,
|
||||
skipInheritedLayouts: true,
|
||||
};
|
||||
|
||||
export default defineRoute(async (req, ctx) => {
|
||||
const content = await loadContent(ctx.params.id);
|
||||
|
||||
// Only render the new content
|
||||
return (
|
||||
<Partial name="docs-content">
|
||||
{content}
|
||||
</Partial>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
By adding the `f-partial` attribute we tell Fresh to fetch the content from our
|
||||
newly added `/partials/docs/[id].tsx` route.
|
||||
|
||||
```diff routes/docs/[id].tsx
|
||||
<aside>
|
||||
- <a href="/docs/page1">Page 1</a>
|
||||
- <a href="/docs/page2">Page 2</a>
|
||||
+ <a href="/docs/page1" f-partial="/partials/docs/page1">Page 1</a>
|
||||
+ <a href="/docs/page2" f-partial="/partials/docs/page2">Page 2</a>
|
||||
</aside>
|
||||
```
|
||||
|
||||
With this in place, Fresh will navigate to the new page when clicking any of the
|
||||
two links and _only_ load the content rendered by our optimized partial route.
|
||||
|
||||
> Currently, `f-partial` is scoped to `<a>`, `<button>` and `<form>` elements.
|
||||
> This might be extended to more elements in the future.
|
||||
|
||||
## Sending multiple Partials at the same time
|
||||
|
||||
A neat aspect of partials in Fresh is that a response can return as many
|
||||
partials as desired. That way you can update multiple unrelated areas on your
|
||||
page in one single HTTP response. A scenario where this is useful are online
|
||||
shops for example.
|
||||
|
||||
```tsx routes/partials/cart.tsx
|
||||
export default function AddToCartPartial() {
|
||||
return (
|
||||
<>
|
||||
<Partial name="cart-items" mode="append">
|
||||
{/* Render the new cart item here */}
|
||||
</Partial>
|
||||
<Partial name="total-price">
|
||||
<p>Total: {totalPrice} €</p>
|
||||
</Partial>
|
||||
</>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Both partials will be applied to the current page.
|
||||
|
||||
## Replacement mode
|
||||
|
||||
By default the whole content inside a partial will be replaced, but there are
|
||||
scenarios where you want to prepend or append new content instead. This can be
|
||||
achieved by adding the `mode` prop to a `Partial` component.
|
||||
|
||||
- `replace` - Swap out the content of the existing partial (default)
|
||||
- `prepend` - Insert the new content before the existing content
|
||||
- `append` - Insert the new content after the existing content
|
||||
|
||||
Personally, we’ve found that the `append` mode is really useful when you have an
|
||||
UI which displays log messages or similar list-like data.
|
||||
|
||||
```tsx routes/log.tsx
|
||||
export default function LogView() {
|
||||
const lines = getNewLogLines();
|
||||
|
||||
return (
|
||||
<Partial name="logs-list" mode="append">
|
||||
{lines.map((line) => {
|
||||
return <li key={line}>{line}</li>;
|
||||
})}
|
||||
</Partial>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
> [info]: When picking the `prepend` or `append` mode, make sure to add keys to
|
||||
> the elements.
|
||||
|
||||
## Bypassing or disabling Partials
|
||||
|
||||
If you want to exempt a particular element from triggering a partial request
|
||||
like on a particular link, form or button, you can opt out of it by setting
|
||||
`f-client-nav={false}` on the element or one of the ancestor elements.
|
||||
|
||||
```tsx routes/index.tsx
|
||||
<body f-client-nav>
|
||||
{/* This will cause a partial navigation */}
|
||||
<a href="/docs/page1">With partials</a>
|
||||
|
||||
{/* This WONT cause a partial navigation */}
|
||||
<a href="/docs/page1" f-client-nav={false}>No partials</a>
|
||||
|
||||
{/* This WONT cause a partial navigation on any elements below */}
|
||||
<div f-client-nav={false}>
|
||||
<div>
|
||||
<a href="/docs/page1">No partials</a>
|
||||
</div>
|
||||
</div>
|
||||
</body>;
|
||||
```
|
||||
|
||||
Whenever an element is clicked Fresh checks if it has the `f-client-nav`
|
||||
attribute and if it is set to `true`. If the element itself doesn't have such an
|
||||
attribute, it will check if any of the ancestor elements has it. If an element
|
||||
was found with a truthy `f-client-nav` attribute a partial request will be
|
||||
triggered. If there is no such attribute or if it's set to `false`, no partial
|
||||
request will occur.
|
||||
@@ -0,0 +1,242 @@
|
||||
---
|
||||
description: Plugins can add new functionality to Fresh without requiring significant complexity.
|
||||
---
|
||||
|
||||
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:
|
||||
|
||||
```ts main.ts
|
||||
import { start } from "$fresh/server.ts";
|
||||
import manifest from "./fresh.gen.ts";
|
||||
|
||||
import twindPlugin from "$fresh/plugins/twind.ts";
|
||||
import twindConfig from "./twind.config.js";
|
||||
|
||||
await start(manifest, {
|
||||
plugins: [
|
||||
// This line configures Fresh to use the first-party twind plugin.
|
||||
twindPlugin(twindConfig),
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Currently, the only available first-party plugin is the Twind plugin.
|
||||
Third-party plugins are also supported - they can be imported from any HTTP
|
||||
server, like any other Deno module.
|
||||
|
||||
Plugin hooks are executed in the order that the plugins are defined in the
|
||||
`plugins` array. This means that the first plugin in the array will be executed
|
||||
first, and the last plugin in the array will be executed last. For many plugins,
|
||||
this does not matter, but for some plugins it may.
|
||||
|
||||
## Creating a plugin
|
||||
|
||||
Fresh plugins are in essence a collection of hooks that allow the plugin to hook
|
||||
into various systems inside of Fresh.
|
||||
|
||||
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 its name. Names must only contain the
|
||||
characters `a`-`z`, and `_`.
|
||||
|
||||
```ts my-plugin.ts
|
||||
import { Plugin } from "$fresh/server.ts";
|
||||
|
||||
const plugin: Plugin = {
|
||||
name: "my_plugin",
|
||||
};
|
||||
```
|
||||
|
||||
A plugin containing only a name is technically valid, but not very useful. To be
|
||||
able to do anything with a plugin, it must register some hooks, middlewares, or
|
||||
routes.
|
||||
|
||||
### Hook: `render`
|
||||
|
||||
The render hook allows plugins to:
|
||||
|
||||
- Control timing of the synchronous render of a page.
|
||||
- Inject additional CSS and JS into the rendered page.
|
||||
|
||||
This is commonly used to set thread local variables for the duration of the
|
||||
render (for example preact global context, preact option hooks, or for style
|
||||
libraries like Twind). After render is complete, the plugin can inject inline
|
||||
CSS and JS modules (with attached state) into the page.
|
||||
|
||||
The render hook is called with the
|
||||
[`PluginRenderContext`](https://deno.land/x/fresh/server.ts?s=PluginRenderContext)
|
||||
object, which contains a `render()` method. This method must be invoked during
|
||||
the render hook to actually render the page. It is a terminal error to not call
|
||||
the `render()` method during the render hook.
|
||||
|
||||
The `render()` method returns a
|
||||
[`PluginRenderFunctionResult`](https://deno.land/x/fresh/server.ts?s=PluginRenderFunctionResult)
|
||||
object which contains the HTML text of the rendered page, as well as a boolean
|
||||
indicating whether the page contains any islands that will be hydrated on the
|
||||
client.
|
||||
|
||||
The `render` hook needs to synchronously return a
|
||||
[`PluginRenderResult`](https://deno.land/x/fresh/server.ts?s=PluginRenderResult)
|
||||
object. Additional CSS and JS modules can be added to be injected into the page
|
||||
by adding them to `styles`, `links` and `scripts` arrays in this object. The
|
||||
plugin can also replace the HTML in side the `<body>`-element of the page by
|
||||
including a `htmlText` string in this object.
|
||||
|
||||
`styles` are injected into the `<head>` of the page as inline CSS. Each entry
|
||||
can define the CSS text to inject, as well as an optional `id` for the style
|
||||
tag, and an optional `media` attribute for the style tag.
|
||||
|
||||
`links` are injected into the `<head>` of the page as `<link>` tags. A link tag
|
||||
is created for each entry, with attributes from the entry's properties.
|
||||
|
||||
`scripts` define JavaScript/TypeScript modules to be injected into the page. The
|
||||
possibly loaded modules need to be defined up front in the `Plugin#entrypoints`
|
||||
property. Each defined module must be a JavaScript/TypeScript module that has a
|
||||
default export of a function that takes one (arbitrary) argument, and returns
|
||||
nothing (or a promise resolving to nothing). Fresh will call this function with
|
||||
the state defined in the `scripts` entry. The state can be any arbitrary JSON
|
||||
serializable JavaScript value.
|
||||
|
||||
For an example of a plugin that uses the `render` hook, see the first-party
|
||||
[Twind plugin](https://github.com/denoland/fresh/blob/1.x/plugins/twind.ts).
|
||||
|
||||
### Hook: `renderAsync`
|
||||
|
||||
This hook is largely the same as the `render` hook, with a couple of key
|
||||
differences to make asynchronous style and script generation possible. It must
|
||||
asynchronously return its
|
||||
[`PluginRenderResult`](https://deno.land/x/fresh/server.ts?s=PluginRenderResult),
|
||||
either from an `async/await` function or wrapped within a promise.
|
||||
|
||||
The render hook is called with the
|
||||
[`PluginAsyncRenderContext`](https://deno.land/x/fresh/server.ts?s=PluginAsyncRenderContext)
|
||||
object, which contains a `renderAsync()` method. This method must be invoked
|
||||
during the render hook to actually render the page. It is a terminal error to
|
||||
not call the `renderAsync()` method during the render hook.
|
||||
|
||||
This is useful for when plugins are generating styles and scripts with
|
||||
asynchronous dependencies based on the `htmlText`. Unlike the synchronous render
|
||||
hook, async render hooks for multiple pages can be running at the same time.
|
||||
This means that unlike the synchronous render hook, you can not use global
|
||||
variables to propagate state between the render hook and the renderer.
|
||||
|
||||
The `renderAsync` hooks start before any page rendering occurs, and finish after
|
||||
all rendering is complete -- they wrap around the underlying JSX->string
|
||||
rendering, plugin `render` hooks, and the
|
||||
[`RenderFunction`](https://deno.land/x/fresh/server.ts?s=RenderFunction) that
|
||||
may be provided to Fresh's `start` entrypoint in the `main.ts` file.
|
||||
|
||||
### Hook: `buildStart`
|
||||
|
||||
This hook is run at the start of the Fresh
|
||||
[ahead-of-time build task](/docs/1.x/concepts/ahead-of-time-builds). It may be
|
||||
synchronous or asynchronous.
|
||||
|
||||
The build start hook is called with the
|
||||
[`ResolvedFreshConfig`](https://deno.land/x/fresh/src/server/types.ts?s=ResolvedFreshConfig)
|
||||
object, which contains the full Fresh configuration.
|
||||
|
||||
This hook may be used to generate precompiled static assets. Any files saved to
|
||||
the `static` subfolder of `config.build.outDir` (typically `_fresh`) will be
|
||||
served the same as other [static files](/docs/1.x/concepts/static-files).
|
||||
|
||||
### Hook: `buildEnd`
|
||||
|
||||
This hook is run at the end of the Fresh
|
||||
[ahead-of-time build task](/docs/1.x/concepts/ahead-of-time-builds). It may be
|
||||
synchronous or asynchronous.
|
||||
|
||||
### Routes and Middlewares
|
||||
|
||||
You can create routes and middlewares that get loaded and rendered like the
|
||||
normal [routes](/docs/1.x/concepts/routes) and
|
||||
[middlewares](/docs/1.x/concepts/middleware).
|
||||
|
||||
The plugin routes and middlewares need a defined path in the format of a file
|
||||
name without a filetype inside the routes directory(E.g. `blog/index`,
|
||||
`blog/[slug]`).
|
||||
|
||||
For more examples see the [Concepts: Routing](/docs/1.x/concepts/routing) page.
|
||||
|
||||
To create a middleware you need to create a `MiddlewareHandler` function.
|
||||
|
||||
And to create a route you can create both a Handler and/or component.
|
||||
|
||||
Below is an example plugin that creates a route and middleware
|
||||
|
||||
```ts my-route-and-middleware-plugin.ts
|
||||
import { MiddlewareHandlerContext, Plugin } from "$fresh/server.ts";
|
||||
import { handler as testMiddleware } from "./sample_routes/_middleware.ts";
|
||||
import { SimpleRoute } from "./sample_routes/simple-route.tsx";
|
||||
export type { Options };
|
||||
|
||||
interface Options {
|
||||
title: string;
|
||||
}
|
||||
export type PluginMiddlewareState = {
|
||||
num: number;
|
||||
test: string;
|
||||
};
|
||||
|
||||
const twoPointlessMiddlewares = [
|
||||
async (
|
||||
_req: Request,
|
||||
ctx: MiddlewareHandlerContext<PluginMiddlewareState>,
|
||||
) => {
|
||||
ctx.state.num = ctx.state.num === undefined ? 1 : ctx.state.num + 1;
|
||||
return await ctx.next();
|
||||
},
|
||||
async (
|
||||
_req: Request,
|
||||
ctx: MiddlewareHandlerContext<PluginMiddlewareState>,
|
||||
) => {
|
||||
ctx.state.num = ctx.state.num === undefined ? 1 : ctx.state.num + 1;
|
||||
return await ctx.next();
|
||||
},
|
||||
];
|
||||
|
||||
export default function routePlugin(
|
||||
options: Options,
|
||||
): Plugin<PluginMiddlewareState> {
|
||||
return {
|
||||
name: "routePlugin",
|
||||
middlewares: [{
|
||||
middleware: { handler: testMiddleware },
|
||||
path: "/",
|
||||
}, {
|
||||
middleware: {
|
||||
handler: twoPointlessMiddlewares,
|
||||
},
|
||||
path: "lots-of-middleware",
|
||||
}],
|
||||
routes: [
|
||||
{ path: "no-leading-slash-here", component: SimpleRoute },
|
||||
],
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
### Islands
|
||||
|
||||
Islands from plugins can be loaded by specifying a list of file paths in your
|
||||
plugin. Those files will be treated by Fresh as if they had been placed inside
|
||||
the `islands/` directory. They will be processed and bundled for the browser in
|
||||
the same way.
|
||||
|
||||
```tsx my-island-plugin.ts
|
||||
import { Plugin } from "$fresh/server.ts";
|
||||
|
||||
export default function myIslandPlugin(): Plugin {
|
||||
return {
|
||||
name: "my-island-plugin",
|
||||
islands: {
|
||||
baseLocation: import.meta.url,
|
||||
paths: [
|
||||
"./plugin/MyPluginIsland.tsx",
|
||||
"./plugin/OtherPluginIsland.tsx",
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,187 @@
|
||||
---
|
||||
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 receive 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 { FreshContext, Handlers } from "$fresh/server.ts";
|
||||
|
||||
export const handler: Handlers = {
|
||||
GET(_req: Request, _ctx: FreshContext) {
|
||||
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 { FreshContext, Handlers, PageProps } from "$fresh/server.ts";
|
||||
|
||||
export const handler: Handlers = {
|
||||
async GET(_req: Request, ctx: FreshContext) {
|
||||
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>;
|
||||
}
|
||||
```
|
||||
|
||||
## Async route components
|
||||
|
||||
Having a separate route handler and component function is nice, when you want to
|
||||
test these in isolation, but can become a bit cumbersome to maintain. They
|
||||
require some additional indirection of declaring an interface for the component
|
||||
`Data` when you're passing it around through `ctx.render()`.
|
||||
|
||||
```tsx routes/page.tsx
|
||||
interface Data {
|
||||
foo: number;
|
||||
}
|
||||
|
||||
export const handler: Handlers<Data> = {
|
||||
async GET(req, ctx) {
|
||||
const value = await loadFooValue();
|
||||
return ctx.render({ foo: value });
|
||||
},
|
||||
};
|
||||
|
||||
export default function MyPage(props: PageProps<Data>) {
|
||||
return <p>foo is: {props.data.foo}</p>;
|
||||
}
|
||||
```
|
||||
|
||||
When a route has both a component and a `GET` handler, they are typically very
|
||||
closely coupled. With async route components you can merge the two together and
|
||||
avoid having to create the `Data` interface boilerplate.
|
||||
|
||||
```tsx routes/page.tsx
|
||||
// Async route component
|
||||
export default async function MyPage(req: Request, ctx: RouteContext) {
|
||||
const value = await loadFooValue();
|
||||
return <p>foo is: {value}</p>;
|
||||
}
|
||||
```
|
||||
|
||||
The code gets a little shorter with async route components. Conceptually, you
|
||||
can think of async route components inlining the `GET` handler into the
|
||||
component function. Note, that you can still add additional HTTP handlers in the
|
||||
same file like before.
|
||||
|
||||
```tsx routes/page.tsx
|
||||
export const handler: Handlers = {
|
||||
async POST(req) {
|
||||
// ... do something here
|
||||
},
|
||||
};
|
||||
|
||||
export default async function MyPage(req: Request, ctx: RouteContext) {
|
||||
const value = await loadFooValue();
|
||||
return <p>foo is: {value}</p>;
|
||||
}
|
||||
```
|
||||
|
||||
### Returning Response objects
|
||||
|
||||
Quite often a route handler needs to render a 404 page or bail out of rendering
|
||||
in another manner. This can be done by returning a `Response` object.
|
||||
|
||||
```tsx route/page.tsx
|
||||
// Async route component
|
||||
export default async function MyPage(req: Request, ctx: RouteContext) {
|
||||
const value = await loadFooValue();
|
||||
|
||||
// Return 404 if `value` is null
|
||||
if (value === null) {
|
||||
return ctx.renderNotFound();
|
||||
}
|
||||
|
||||
// Returning a response object directly works too
|
||||
if (value === "redirect") {
|
||||
const headers = new Headers();
|
||||
headers.set("location", "/some-other-page");
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers,
|
||||
});
|
||||
}
|
||||
|
||||
return <p>foo is: {value}</p>;
|
||||
}
|
||||
```
|
||||
|
||||
### Define helper
|
||||
|
||||
To make it a little quicker to write async routes, Fresh ships with a
|
||||
`defineRoute` helper which automatically infers the correct types for the
|
||||
function arguments.
|
||||
|
||||
```tsx routes/hello.tsx
|
||||
import { defineRoute } from "$fresh/server.ts";
|
||||
|
||||
export default defineRoute(async (req, ctx) => {
|
||||
const data = await loadData();
|
||||
|
||||
return (
|
||||
<div class="page">
|
||||
<h1>Hello {data.name}</h1>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
```
|
||||
@@ -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.
|
||||
@@ -0,0 +1,212 @@
|
||||
---
|
||||
description: |
|
||||
The ability to configure the core Fresh server leads to its flexibility.
|
||||
---
|
||||
|
||||
In this page we discuss how the server can be configured during startup.
|
||||
|
||||
The signature of the primary method looks like this:
|
||||
|
||||
```ts main.ts
|
||||
export async function start(manifest: Manifest, config: FreshConfig = {});
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
`Manifest` comes from `fresh.gen.ts`, so nothing to do there. `config` is where
|
||||
things get interesting.
|
||||
[`FreshConfig`](https://deno.land/x/fresh/server.ts?s=FreshConfig) looks like
|
||||
this:
|
||||
|
||||
```ts fresh 🍋
|
||||
export interface FreshConfig {
|
||||
build?: {
|
||||
/**
|
||||
* The directory to write generated files to when `dev.ts build` is run.
|
||||
* This can be an absolute path, a file URL or a relative path.
|
||||
*/
|
||||
outDir?: string;
|
||||
/**
|
||||
* This sets the target environment for the generated code. Newer
|
||||
* language constructs will be transformed to match the specified
|
||||
* support range. See https://esbuild.github.io/api/#target
|
||||
* @default {"es2022"}
|
||||
*/
|
||||
target?: string | string[];
|
||||
};
|
||||
render?: RenderFunction;
|
||||
plugins?: Plugin[];
|
||||
staticDir?: string;
|
||||
router?: RouterOptions;
|
||||
server?: Partial<Deno.ServeTlsOptions>;
|
||||
}
|
||||
```
|
||||
|
||||
And for completeness here are the remaining two types:
|
||||
|
||||
```ts fresh 🍋
|
||||
export type RenderFunction = (
|
||||
ctx: RenderContext,
|
||||
render: InnerRenderFunction,
|
||||
) => void | Promise<void>;
|
||||
|
||||
export interface RouterOptions {
|
||||
/**
|
||||
* Controls whether Fresh will append a trailing slash to the URL.
|
||||
* @default {false}
|
||||
*/
|
||||
trailingSlash?: boolean;
|
||||
/**
|
||||
* Configures the pattern of files to ignore in islands and routes.
|
||||
*
|
||||
* By default Fresh will ignore test files,
|
||||
* for example files with a `.test.ts` or a `_test.ts` suffix.
|
||||
*
|
||||
* @default {/(?:[^/]*_|[^/]*\.|)test\.(?:ts|tsx|mts|js|mjs|jsx|)\/*$/}
|
||||
*/
|
||||
ignoreFilePattern?: RegExp;
|
||||
/**
|
||||
* Serve fresh from a base path instead of from the root.
|
||||
* "/foo/bar" -> http://localhost:8000/foo/bar
|
||||
* @default {undefined}
|
||||
*/
|
||||
basePath?: string;
|
||||
}
|
||||
```
|
||||
|
||||
## Build
|
||||
|
||||
### outDir
|
||||
|
||||
As the comment suggests, this can be used to configure where generated files are
|
||||
written:
|
||||
|
||||
```tsx dev.ts
|
||||
await dev(import.meta.url, "./main.ts", {
|
||||
build: {
|
||||
outDir: Deno.env.get("FRESH_TEST_OUTDIR") ?? undefined,
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### target
|
||||
|
||||
This should be a valid ES Build target.
|
||||
|
||||
```tsx dev.ts
|
||||
await dev(import.meta.url, "./main.ts", {
|
||||
build: {
|
||||
target: "es2015",
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## Plugins
|
||||
|
||||
See the [docs](/docs/1.x/concepts/plugins) on this topic for more detail. But as
|
||||
a quick example, you can do something like this to load plugins:
|
||||
|
||||
```ts main.ts
|
||||
await start(manifest, { plugins: [twindPlugin(twindConfig)] });
|
||||
```
|
||||
|
||||
## StaticDir
|
||||
|
||||
This allows you to specify the location where your site's static assets are
|
||||
stored. Here's an example:
|
||||
|
||||
```ts main.ts
|
||||
await start(manifest, { staticDir: "./custom_static" });
|
||||
```
|
||||
|
||||
## Render
|
||||
|
||||
This is by far the most complicated option currently available. It allows you to
|
||||
configure how your components get rendered.
|
||||
|
||||
## RouterOptions
|
||||
|
||||
### TrailingSlash
|
||||
|
||||
By default Fresh uses URLs like `https://www.example.com/about`. If you'd like,
|
||||
you can configure this to `https://www.example.com/about/` by using the
|
||||
`trailingSlash` setting.
|
||||
|
||||
```ts main.ts
|
||||
await start(manifest, { router: { trailingSlash: true } });
|
||||
```
|
||||
|
||||
### ignoreFilePattern
|
||||
|
||||
By default Fresh ignores test files which are co-located next routes and
|
||||
islands. If you want, you can change the pattern Fresh uses ignore these files
|
||||
|
||||
### basePath
|
||||
|
||||
This setting allows you to serve a Fresh app from sub-path of a domain. A value
|
||||
of `/foo/bar` would serve the app from `http://localhost:8000/foo/bar` instead
|
||||
of `http://localhost:8000/` for example.
|
||||
|
||||
The `basePath` will be automatically applied to absolute links in your app. For
|
||||
example, when the `basePath` is `/foo/bar`, linking to `/about` will
|
||||
automatically become `/foo/bar/about`.
|
||||
|
||||
```tsx
|
||||
<a href="/about">About</a>;
|
||||
```
|
||||
|
||||
Rendered HTML:
|
||||
|
||||
```html
|
||||
<a href="/foo/bar/about">About</a>
|
||||
```
|
||||
|
||||
The `basePath` is also applied to the `src` and `srcset` attribute of
|
||||
`<img>`-tags, the `href` attribute of `<link>` and the `src` attribute of
|
||||
`<script>` tags.
|
||||
|
||||
## Server
|
||||
|
||||
Now that Deno has stabilized
|
||||
[Deno.serve](https://docs.deno.com/api/deno/~/Deno.serve) and Fresh has switched
|
||||
to using this API, all server configuration options are embedded in `server`
|
||||
inside the `FreshConfig`. The fully expanded set of parameters looks like this:
|
||||
|
||||
```ts
|
||||
server: {
|
||||
/** Server private key in PEM format */
|
||||
cert: string;
|
||||
|
||||
/** Cert chain in PEM format */
|
||||
key: string;
|
||||
|
||||
/** The port to listen on.
|
||||
*
|
||||
* @default {8000} */
|
||||
port?: number;
|
||||
|
||||
/** A literal IP address or host name that can be resolved to an IP address.
|
||||
*
|
||||
* __Note about `0.0.0.0`__ While listening `0.0.0.0` works on all platforms,
|
||||
* the browsers on Windows don't work with the address `0.0.0.0`.
|
||||
* You should show the message like `server running on localhost:8080` instead of
|
||||
* `server running on 0.0.0.0:8080` if your program supports Windows.
|
||||
*
|
||||
* @default {"0.0.0.0"} */
|
||||
hostname?: string;
|
||||
|
||||
/** An {@linkcode AbortSignal} to close the server and all connections. */
|
||||
signal?: AbortSignal;
|
||||
|
||||
/** Sets `SO_REUSEPORT` on POSIX systems. */
|
||||
reusePort?: boolean;
|
||||
|
||||
/** The handler to invoke when route handlers throw an error. */
|
||||
onError?: (error: unknown) => Response | Promise<Response>;
|
||||
|
||||
/** The callback which is called when the server starts listening. */
|
||||
onListen?: (params: { hostname: string; port: number }) => void;
|
||||
}
|
||||
```
|
||||
|
||||
Use these to configure your server as you see fit.
|
||||
@@ -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,128 @@
|
||||
---
|
||||
description: |
|
||||
New versions of Fresh are regularly released. This page explains how to update your project.
|
||||
---
|
||||
|
||||
Fresh consists of multiple pieces which are independently versioned and
|
||||
released.
|
||||
|
||||
- Fresh (https://deno.land/x/fresh)
|
||||
- Preact (https://esm.sh/preact)
|
||||
- preact-render-to-string (https://esm.sh/preact-render-to-string)
|
||||
|
||||
Some plugins also have their own dependencies that can be updated independently.
|
||||
|
||||
- Twind (https://esm.sh/twind) (for the twind plugin)
|
||||
|
||||
For the most part these pieces can be updated independently. Certain versions of
|
||||
Fresh may require a minimum version of a given dependency. This is documented
|
||||
below.
|
||||
|
||||
| Fresh version | Preact | preact-render-to-string | Deno |
|
||||
| ------------- | ----------------- | ----------------------- | --------- |
|
||||
| 1.0.0-1.0.2 | >=10.8.1 <11.0.0 | >=5.2.0 <6.0.0 | >= 1.23.0 |
|
||||
| 1.1.0-1.1.5 | >=10.8.1 <11.0.0 | >=5.2.0 <6.0.0 | >= 1.25.0 |
|
||||
| 1.2.0 | >=10.15.0 <11.0.0 | >=6.1.0 | >= 1.25.0 |
|
||||
|
||||
## Updating dependencies
|
||||
|
||||
To update your dependencies, you have two options:
|
||||
|
||||
- Run the Fresh updater to update your project dependencies.
|
||||
- Manually update the dependency versions in your `deno.json` file.
|
||||
|
||||
### Auto updater
|
||||
|
||||
The auto updater is a command line tool that will update your project's
|
||||
`deno.json` file to the latest versions of Fresh and its dependencies. It may
|
||||
also contain code mods for your project that will update your code to the latest
|
||||
recommended patterns for Fresh projects.
|
||||
|
||||
To run the auto updater, run the following command from the root of your
|
||||
project:
|
||||
|
||||
```sh Terminal
|
||||
$ deno run -A -r https://fresh.deno.dev/update
|
||||
```
|
||||
|
||||
You will be prompted to confirm the changes that will be made to your project.
|
||||
|
||||
### Manual update
|
||||
|
||||
To manually update your project's dependencies, you can edit the `deno.json`
|
||||
file in the root of your projects directory. Dependency versions are encoded
|
||||
into the URLs in this file. For example, here is how to update a project from
|
||||
Fresh 1.0.2 to 1.1.3, and update Preact to the latest version:
|
||||
|
||||
```diff deno.json
|
||||
{
|
||||
"imports": {
|
||||
- "$fresh/": "https://deno.land/x/fresh@1.0.2/",
|
||||
+ "$fresh/": "https://deno.land/x/fresh@1.1.5/",
|
||||
|
||||
- "preact": "https://esm.sh/preact@10.8.1",
|
||||
- "preact/": "https://esm.sh/preact@10.8.1/",
|
||||
+ "preact": "https://esm.sh/preact@10.11.0",
|
||||
+ "preact/": "https://esm.sh/preact@10.11.0/",
|
||||
|
||||
- "preact-render-to-string": "https://esm.sh/*preact-render-to-string@5.2.0",
|
||||
+ "preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.1.0",
|
||||
|
||||
"twind": "https://esm.sh/twind@0.16.17",
|
||||
"twind/": "https://esm.sh/twind@0.16.17/"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Automatic update checks
|
||||
|
||||
Fresh will periodically check if a new Fresh version is available if it's
|
||||
running outside of CI. This happens once per day and can be disabled by setting
|
||||
the `FRESH_NO_UPDATE_CHECK=true` environment variable.
|
||||
|
||||
## Code mods
|
||||
|
||||
Code mods are small scripts that can be run to update your project's code to
|
||||
match the latest recommended patterns for Fresh projects. Code mods can be run
|
||||
through the auto updater. Sometimes the code mod can not cover all cases, so you
|
||||
may need to manually update some code. This section explains the code mods
|
||||
currently available.
|
||||
|
||||
### Classical JSX -> Automatic JSX
|
||||
|
||||
> This code mod is only available in Fresh 1.1.0 and above.
|
||||
|
||||
The classical JSX transform that relies on a `/** @jsx h */` pragma is no longer
|
||||
the recommended way to use JSX in Fresh projects. Instead, starting with version
|
||||
1.1.0, Fresh projects should use the automatic JSX transform that requires no
|
||||
JSX pragma or preact import.
|
||||
|
||||
```diff routes/hello-world.tsx
|
||||
- /** @jsx h */
|
||||
- import { h } from "preact";
|
||||
|
||||
export default function Page() {
|
||||
return <div>Hello world!</div>;
|
||||
}
|
||||
```
|
||||
|
||||
This code mod will update your deno.json file to include the relevant compiler
|
||||
options to enable the automatic JSX transform. It will then go through your
|
||||
project and remove any `/** @jsx h */` pragmas and `import { h } from "preact"`
|
||||
statements.
|
||||
|
||||
### Classic twind -> Twind plugin
|
||||
|
||||
> This code mod is only available in Fresh 1.1.0 and above.
|
||||
|
||||
Fresh version 1.1.0 introduced a new plugin for using twind with Fresh. This
|
||||
plugin is much nicer to use than the raw twind integration that was previously
|
||||
available.
|
||||
|
||||
This code mod will update your project to use the new twind plugin. It will
|
||||
update your `main.ts` file to import the twind plugin and add it to the plugins
|
||||
array. It will also update your files to remove many unnecessary uses of the
|
||||
`tw` function, and remove unnecessary twind imports. While the code mod can
|
||||
handle most cases, you may need to manually update some code. Additionally you
|
||||
will need to manually update your `twind.config.ts` if you use a custom
|
||||
configuration.
|
||||
Reference in New Issue
Block a user