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

This commit is contained in:
Marvin Hagemeister
2025-09-09 14:36:51 +02:00
committed by GitHub
parent 2c315a9972
commit 79d8cfc3ed
109 changed files with 1589 additions and 1502 deletions
-33
View File
@@ -1,33 +0,0 @@
---
description: |
Add a global app wrapper to provide common meta tags or context for application routes.
---
The app wrapper component is a Preact component that represents the outer
structure of the HTML document, typically up until the `<body>`-tag. It is only
rendered on the server and never on the client. The passed `Component` value
represents the children of this component.
```tsx main.tsx
function AppWrapper({ Component }) {
return (
<html lang="en">
<head>
<meta charset="utf-8" />
<title>My App</title>
</head>
<body>
<Component />
</body>
</html>
);
}
app.appWrapper(AppWrapper);
```
Every [`ctx.render()`](/docs/canary/concepts/context#render-1) call will include
the app wrapper component by default, unless opted out.
Note that only one app wrapper component is supported per
[`App`](/docs/canary/concepts/app) instance.
-195
View File
@@ -1,195 +0,0 @@
---
description: |
The Builder class is used to generate optimized assets for production.
---
> [warn]: The `Builder` class was used during the alpha phase of Fresh 2 before
> the Fresh vite plugin was released. You can skip this page if you're using
> vite.
The `Builder` class is used to generate production assets of your app. You'll
typically find it being created inside your project's `dev.ts` file.
```ts dev.ts
import { Builder } from "fresh/dev";
const builder = new Builder({ target: "safari12" });
if (Deno.args.includes("build")) {
// This creates a production build
await builder.build();
} else {
// This starts a development server with live reload
await builder.listen(() => import("./main.ts"));
}
```
## Options
You can customize the builder by passing options.
```ts dev.ts
const builder = new Builder({
// Browser target for generated code. Maps to https://esbuild.github.io/api/#target
target?: string | string[];
// The root directory of the project. All other paths will be resolved
// against this if they're relative. (Default: `Deno.cwd()`)
root?: string;
// The path to your server entry point. (Default: `<root>/main.ts`)
serverEntry?: string;
// Where to write generated files when doing a production build.
// (default: `<root>/_fresh/`)
outDir?: string;
// Path to static file directory. (Default: `<root>/static/`)
staticDir?: string;
// Path to island directory. (Default: `<root>/islands`)
islandDir?: string;
// Path to routes directory. (Default: `<root>/routes`)
routeDir?: string;
// File paths which should be ignored
ignore?: RegExp[];
// Optionally generate production source maps
// See https://esbuild.github.io/api/#source-maps
sourceMap?: {
kind?: boolean | 'linked' | 'inline' | 'external' | 'both';
sourceRoot?: string;
sourcesContent?: boolean;
};
})
```
## Registering islands
The builder is where you'll register files that contain islands. This is the
same API that Fresh uses internally.
```ts dev.ts
const builder = new Builder();
// Path to local island
builder.registerIsland("path/to/my/Island.tsx");
// File urls work too
builder.registerIsland("file:///path/to/my/Island.tsx");
// Also islands from jsr
builder.registerIsland("jsr:@marvinh-test/fresh-island");
```
## Adding build plugins
The `Builder` has a very simple processing mechanism for static files.
```ts dev.ts
builder.onTransformStaticFile({
pluginName: "My cool plugin",
filter: /\.css$/,
}, (args) => {
// Prepend `body { background: red }` to every `.css` file
const code = `body { background: red } ${args.text}`;
return {
content: code,
map: undefined, // Optional: source maps
};
});
```
> [info]: Only static files in `static/` or the value you set `staticDir` to
> will be processed. The builder won't process anything else.
## Testing
Testing applications with the `Builder` class involves creating a build snapshot
and assigning that to each app instance.
```ts my-app.test.ts
// Best to do this once instead of for every test case for
// performance reasons.
const builder = new Builder();
const applySnapshot = await builder.build({ snapshot: "memory" });
function testApp() {
const app = new App()
.get("/", () => new Response("hello"))
.fsRoutes();
// Applies build snapshot to this app instance.
applySnapshot(app);
return app;
}
Deno.test("My Test", async () => {
const handler = testApp().handler();
const response = await handler(new Request("http://localhost"));
const text = await response.text();
if (text !== "hello") {
throw new Error("fail");
}
});
```
## Tailwindcss
[Tailwindcss](https://tailwindcss.com/) is a utility-first CSS framework that
generates CSS out of the class names that are used in JSX. Since we use
Tailwindcss ourselves here at Deno, Fresh ships with an official plugin for
that.
### Usage
1. Set `nodeModulesDir` in `deno.json` to `"auto"` or `"manual"`
```diff deno.json
{
"name": "@example/my-cool-project"
+ "nodeModulesDir": "auto",
"imports": {
...
}
}
```
2. Run `deno install jsr:@fresh/plugin-tailwind`
3. Update `dev.ts`:
```diff dev.ts
import { Builder } from "fresh/dev";
+ import { tailwind } from "@fresh/plugin-tailwind";
const builder = new Builder();
+ tailwind(builder);
```
4. Add `@import "tailwindcss";` at the top of your main stylesheet.
For more information on how to use tailwindcss, check out
[their documentation](https://tailwindcss.com/docs/styling-with-utility-classes).
### Options
You can customize the tailwind plugin via the following options:
```ts dev.ts
tailwind(builder, app, {
// Exclude certain files from processing
exclude: ["/admin/**", "*.temp.css"],
// Force optimization (defaults to production mode)
optimize: true,
// Exclude base styles
base: null,
});
```
### Tailwindcss v3
If can't update to the current version of tailwindcss we have a dedicated
`@fresh/plugin-tailwindcss-v3` plugin that uses tailwindcss v3. That way you can
decided on your own when it's best to update to v4.
```ts dev.ts
import { Builder } from "fresh/dev";
import { tailwind } from "@fresh/plugin-tailwind-v3";
tailwind(builder, {});
```
-85
View File
@@ -1,85 +0,0 @@
---
description: |
Define helpers are a less TypeScripty way to declare middlewares, routes and layouts
---
Define helpers can be used to shorten the amount of types you have to type
yourself in code. They are entirely optional as some developers prefer the
expliciteness of types, other's like the convenience of `define.*` helpers.
Without define helpers:
```ts util.ts
export interface State {
foo: string;
}
```
```ts middleware.ts
import type { State } from "./util.ts";
export async function myMiddleware(ctx: Context<State>): Promise<Response> {
return new Response("hello " + ctx.state.foo);
}
export async function otherMiddleware(ctx: Context<State>): Promise<Response> {
return new Response("other " + ctx.state.foo);
}
```
With define helpers:
```ts util.ts
import { createDefine } from "fresh";
// Setup, do this once in a file and import it everywhere else.
export const define = createDefine<{ foo: string }>();
```
```ts middleware.ts
import { define } from "./util.ts";
// Usage
export const myMiddleware = define.middleware((ctx) => {
return new Response("hello " + ctx.state.foo);
});
export const otherMiddleware = define.middleware((ctx) => {
return new Response("other " + ctx.state.foo);
});
```
## File routes
The `define.*` helpers include a `define.handler()` and `define.page()` function
to make it easy for TypeScript to establish a relation between the two. That way
when you can pass data from the handler to the component in a type-safe way.
```tsx routes/index.tsx
export const handler = define.handlers({
GET(ctx) {
return { data: { foo: "Deno" } };
},
});
// When you type `props.data.*` you'll get autocompletion
export default define.page<typeof handler>((props) => {
return (
<div>
<h1>I like {props.data.foo}</h1>
</div>
);
});
```
There is also a `define.layout()` helper for layouts:
```tsx
export default define.layout((props) => {
return (
<div>
<h1>I like {props.state.foo}</h1>
</div>
);
});
```
@@ -1,58 +0,0 @@
---
description: |
Error pages can be used to customize the page that is shown when an error occurs in the application.
---
Environment variables in Deno are typically read via `Deno.env.get()` or
`process.env.*` calls or via an `.env` file if the `--env-file` flag is used,
see
[how to use Environment Variables in Deno](https://docs.deno.com/runtime/reference/env_variables/).
On top of that Fresh automatically inlines all environment variables whose names
start with `FRESH_PUBLIC_` during bundling of islands.
> [info]: This inlining step occurs when building the app (`deno task build`).
> Environment variables inside islands cannot be read at runtime.
Example:
```sh Terminal
$ FRESH_PUBLIC_FOO=bar deno task dev
```
```tsx
export function MyIsland() {
const value = Deno.env.get("FRESH_PUBLIC_FOO");
return <h1>{value}</h1>;
}
```
This code when bundled will be turned into this:
```tsx
export function MyIsland() {
const value = "bar";
return <h1>{value}</h1>;
}
```
This way you can use specific environment variables in the browser.
> [warn]: To make inlining work the code needs to be analyzable by our plugins.
> This means that not all forms of reading an environment variable in Deno are
> supported, even if it's perfectly valid JavaScript code.
>
> ```ts MyIsland.tsx
> // CORRECT
> Deno.env.get("FRESH_PUBLIC_FOO");
> process.env.FRESH_PUBLIC_FOO;
>
> // WRONG
> const name = "FRESH_PUBLIC_FOO";
> Deno.env.get(name);
> process.env[name];
>
> // WRONG
> const obj = Deno.env.toObject();
> obj.FRESH_PUBLIC_FOO;
> ```
-102
View File
@@ -1,102 +0,0 @@
---
description: |
Error pages can be used to customize the page that is shown when an error occurs in the application.
---
Error pages are used to ensure that your app keeps working and display relevant
feedback to the one who made the request.
Fresh supports two kind of error pages:
1. Generic error pages
2. 404 Not found error pages
> [tip]: Be sure to return the appropriate
> [HTTP Status](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status)
> code. This makes it a lot easier for clients of your app to act appropriately.
> It also makes it easier to find failed requests when going through traces.
## Generic error pages
To add an error page use [`app.onError()`](/docs/canary/concepts/app#onerror).
```ts main.ts
const app = new App()
.onError("*", (ctx) => {
console.log(`Error: ${ctx.error}`);
return new Response("Oops!", { status: 500 });
})
.get("/thrower", () => {
throw new Error("fail");
});
```
When you access `/thrower` the error will be caught and the `onError` callback
will be invoked.
You can also nest error pages:
```ts main.ts
const app = new App()
// Top level error page
.onError("*", (ctx) => {
return new Response("Oops!", { status: 500 });
})
.onError("/foo/bar", (ctx) => {
return new Response("nested error!", { status: 500 });
})
.get("/foo/bar/thrower", () => {
throw new Error("fail");
});
```
## Not found error
Not found errors are often treated differently than generic errors. You can both
treat them with the `.onError()` way, but by adding a specific `.notFound()`
handler, Fresh ensures that every 404 error will invoke this callback.
```ts main.ts
const app = new App()
// Top level error page
.notFound((ctx) => {
return new Response("Page not found", { status: 404 });
})
.get("/", () => new Response("foo"));
```
Accessing an unknown route like `/invalid` will trigger the `notFound`
middleware. Contrary to generic error pages this handler cannot be nested.
## Throwing HTTP errors
If you need to bail out of execution and need to respond with a particular HTTP
error code, you can use Fresh's `HttpError` class.
```ts middleware/auth.ts
import { HttpError } from "fresh";
async function authMiddleware(ctx) {
const user = ctx.state.user;
// Check if user is authenticated, throw 404 error if not
if (!isAuthenticated(user)) {
throw new HttpError(404);
}
return await ctx.next();
}
```
You can check the status code of the thrown `HttpError` in your error handler:
```ts main.ts
app.onError((ctx) => {
if (ctx.error instanceof HttpError) {
const status = ctx.error.status;
return new Response("oops", { status });
}
// ...
});
```
-110
View File
@@ -1,110 +0,0 @@
---
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 { define } from "../utils.ts";
export const handlers = define.handlers({
async GET(ctx) {
return { data: {} };
},
async POST(ctx) {
const form = await ctx.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 define.page<typeof handlers>(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 { define } from "../utils.ts";
export const handler = define.handlers({
async GET(ctx) {
return { data: { message: null } };
},
async POST(ctx) {
const form = await ctx.req.formData();
const file = form.get("my-file") as File;
if (!file) {
return { data: { message: "Please try again" } };
}
const name = file.name;
const contents = await file.text();
console.log(contents);
return { data: { message: `${name} uploaded!` } };
},
});
export default define.page<typeof handlers>(function Upload(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.
-81
View File
@@ -1,81 +0,0 @@
---
description: Modify the document head in Fresh
---
The
[`<head>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/head)-element
is a crucial element in HTML to set metadata for a page. It allows you to:
- Set the document title with `<title>`
- Specify page metadata with `<meta>`
- Link to resources like stylesheets with `<link>`
- Include JavaScript code with `<script>`
> [info]: The outer HTML structure including `<head>` is typically created
> inside `_app.tsx`.
## Passing metadata from `ctx.state`
For simple scenarios passing metadata along from a handler or a middleware by
writing to `ctx.state` is often sufficient.
```tsx routes/_app.tsx
import { define } from "../util.ts";
export default define.page((ctx) => {
return (
<html lang="en">
<head>
<meta charset="utf-8" />
<title>{ctx.state.title ?? "Welcome!"}</title>
</head>
<body>
<ctx.Component />
</body>
</html>
);
});
```
## Using the `<Head>`-component
For more complex scenarios, or to set page metadata from islands, Fresh ships
with the `<Head>`-component.
> [info]: The `<Head>` component is not dynamic by default. It will not
> automatically update the document title or other head elements on the client
> side when component state changes. The head elements are set during server
> rendering or initial page load.
```tsx routes/about.tsx
import { Head } from "fresh/runtime";
export default define.page((ctx) => {
return (
<div>
<Head>
<title>About me</title>
</Head>
<h1>About me</h1>
<p>I like Fresh!</p>
</div>
);
});
```
### Avoiding duplicate tags
You might end up with duplicate tags, when multiple `<Head />` components are
rendered on the same page. Fresh will employ the following strategies to find
the matching element:
1. For `<title>` elements Fresh will set `document.title` directly
2. Check if an element with the same `key` exists
3. Check if an element with the same `id` attribute
4. Only for `<meta>` elements: Check if there is a `<meta>` element with the
same `name` attribute
5. No matching element was found, Fresh will create a new one and append it to
`<head>`
> [info]: The `<title>`-tag is automatically deduplicated, even without a `key`
> prop.
-6
View File
@@ -1,6 +0,0 @@
---
description: |
This chapter goes over some advanced concepts of Fresh.
---
This section of the documentation describes advanced functionality of Fresh.
-47
View File
@@ -1,47 +0,0 @@
---
description: "Create re-usable layouts across routes"
---
Layouts are plain Preact components that are inherited based on the matching
pattern. When you have a section on your site where all pages share the same
HTML structure and only the content changes, a layout is a neat way to abstract
this. Layouts only ever render on the server. The passed `Component` value
represents the children of this component.
```tsx main.tsx
function PageLayout({ Component }) {
return (
<div>
<Component />
<aside>Here is some sidebar content</aside>
</div>
);
}
const app = new App()
.layout("*", PageLayout)
.get("/", (ctx) => ctx.render(<h1>hello</h1>));
```
If you browse to the `/` route, Fresh will render the following HTML
```html Response body
<div>
<h1>hello world</h1>
<aside>Here is some sidebar content</aside>
</div>
```
## Options
Add a layout and ignore all previously inherited ones.
```ts main.ts
app.layout("/foo/bar", MyComponent, { skipInheritedLayouts: true });
```
Ignore the app wrapper component:
```ts main.ts
app.layout("/foo/bar", MyComponent, { skipAppWrapper: true });
```
-230
View File
@@ -1,230 +0,0 @@
---
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 { define } from "../utils.ts";
+ import { Partial } from "fresh/runtime";
export default define.page(function App({ Component }) {
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).
![A sketched layout of a typical documentation page with the sidebar on the left composed of green links and a main content area on the right. The main content area is labeled as Partial docs-content](/docs/fresh-partial-docs.png)
The code for such a page (excluding styling) might look like this:
```tsx routes/docs/[id].tsx
import { define } from "../../utils.ts";
export default define.page(async (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 { define } from "../utils.ts";
import { Partial } from "fresh/runtime";
// 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 define.page(async (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/_app.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.
-56
View File
@@ -1,56 +0,0 @@
---
description: |
Troubleshooting Fresh applications.
---
This site contains some tips to troubleshoot your app in case something doesn't
work as expected.
## Update Fresh
The easiest way to resolve most issues is to ensure that you're on the
[latest version](https://jsr.io/@fresh/core/versions) of Fresh. We continuously
work on Fresh and there is a good chance that the issue you're running into has
already been resolved in the latest version of Fresh.
## Don't use esm.sh
Fresh 1.x heavily relied on [esm.sh](https://esm.sh/) to be able to use npm
packages with Fresh. This continued a bit through the early alpha versions of
Fresh 2. With the move to [`vite`](https://vite.dev/) this is not necessary
anymore and you should use the relevant npm package directly from npm.
```diff deno.json
{
"imports": {
- "cowsay": "https://esm.sh/cowsay"
+ "cowsay": "npm:cowsay@^1.6.0"
}
}
```
> [info]: Not using `esm.sh` solves many issues and footguns with duplicate
> Preact versions in your app. If you're seeing strange JavaScript errors in the
> browser in your app than this is likely the cause.
## Attach a debugger
To attach a debugger to vite with Deno run this command:
```sh Terminal
deno run -A --inspect npm:vite
# or
deno run -A --inspect-brk npm:vite
```
## Debug vite resolution
To debug vite resolution issues run vite with the `--debug` flag. This will
print lots of debugging information to the terminal.
## Debug vite transformations
To debug vite plugin transformations, use
[`vite-plugin-inspect`](https://github.com/antfu-collective/vite-plugin-inspect).
This gives you a UI that shows all transformations of all plugins for every
file.
-32
View File
@@ -1,32 +0,0 @@
---
description: |
Configure the fresh vite plugin.
---
The Fresh vite plugin can be optionally configured in the following ways:
```ts vite.config.ts
import { defineConfig, type Plugin } from "vite";
import { fresh } from "@fresh/plugin-vite";
export default defineConfig({
plugins: [
fresh({
// Path to main server entry file. Default: main.ts
serverEntry: "./path/to/main.ts",
// Path to main client entry file. Default: client.ts
clientEntry: "./path/to/client.ts",
// Path to islands directory. Default: ./islands
islandsDir: "./islands",
// Path to routes directory. Default: ./routes
routeDir: "./routes",
// Optional regex to ignore folders when crawling the routes and
// island directory.
ignore: [/[\\/]+some-folder[\\/]+/],
// Additional specifiers to treat as island files. This is used
// for declaring islands from third party packages.
islandSpecifiers: ["@example/my-remote-island"],
}),
],
});
```
-342
View File
@@ -1,342 +0,0 @@
---
description: |
Add a global app wrapper to provide common meta tags or context for application routes.
---
The `App` class is the heart of Fresh and routes incoming requests to the
correct middlewares. This is where routes, middlewares, layouts and more are
defined.
```tsx main.ts
const app = new App()
.use(staticFiles())
.get("/", () => new Response("hello"))
.get("/about", (ctx) => ctx.render(<h1>About me</h1>));
// Start server
app.listen();
```
All items are applied from top to bottom. This means that when you defined a
middleware _after_ a `.get()` handler, it won't be included.
```tsx main.tsx
const app = new App()
.use((ctx) => {
// Will be called for all middlewares
return ctx.next();
})
.get("/", () => new Response("hello"))
.use((ctx) => {
// Will only be called for `/about
return ctx.next();
})
.get("/about", (ctx) => ctx.render(<h1>About me</h1>));
```
## `.use()`
Add one or more [middlewares](/docs/canary/concepts/middleware). Middlewares are
matched left to right.
```ts
// Add a middleware at the root
app.use(async (ctx) => {
console.log("my middleware");
return await ctx.next();
});
```
You can also add multiple middlewares:
```ts
app.use(middleware1, middleware2, middleware3);
```
Adding middlewares at a specific path:
```ts
app.use("/foo/bar", middleware);
```
Middlewares can also be instantiated lazily:
```ts
app.use("/foo/bar", async () => {
const mod = await import("./path/to/my/middleware.ts");
return mod.default;
});
```
## `.get()`
Respond to a `GET` request with the specified middlewares.
```ts
app.get("/about", async (ctx) => {
return new Response(`GET: ${ctx.url.pathname}`);
});
```
Respond with multiple middlewares:
```ts
app.get("/about", middleware1, middleware2, async (ctx) => {
return new Response(`GET: ${ctx.url.pathname}`);
});
```
You can also pass lazy middlewares:
```ts
app.get("/about", async () => {
const mod = await import("./middleware-or-handler.ts");
return mod.default;
});
```
## `.post()`
Respond to a `POST` request with the specified middlewares.
```ts
app.post("/api/user/:id", async (ctx) => {
await somehowCreateUser(ctx.params.id);
return new Response(`User created`);
});
```
Respond with multiple middlewares:
```ts
app.post("/api/user/:id", middleware1, middleware2, async (ctx) => {
await somehowCreateUser(ctx.params.id);
return new Response(`User created`);
});
```
You can also pass lazy middlewares:
```ts
app.post("/api/user/:id", async () => {
const mod = await import("./middleware-or-handler.ts");
return mod.default;
});
```
## `.put()`
Respond to a `PUT` request with the specified middlewares.
```ts
app.put("/api/user/:id", async (ctx) => {
await somehowSaveUser(ctx.params.id);
return new Response(`Updated user`);
});
```
Respond with multiple middlewares:
```ts
app.put("/api/user/:id", middleware1, middleware2, async (ctx) => {
await somehowSaveUser(ctx.params.id);
return new Response(`Updated user`);
});
```
You can also pass lazy middlewares:
```ts
app.put("/api/user/:id", async () => {
const mod = await import("./middleware-or-handler.ts");
return mod.default;
});
```
## `.delete()`
Respond to a `DELETE` request with the specified middlewares.
```ts
app.delete("/api/user/:id", async (ctx) => {
await somehowDeleteUser(ctx.params.id);
return new Response(`User deleted`);
});
```
Respond with multiple middlewares:
```ts
app.delete("/api/user/:id", middleware1, middleware2, async (ctx) => {
await somehowDeleteUser(ctx.params.id);
return new Response(`User deleted`);
});
```
You can also pass lazy middlewares:
```ts
app.delete("/api/user/:id", async () => {
const mod = await import("./middleware-or-handler.ts");
return mod.default;
});
```
## `.head()`
Respond to a `HEAD` request with the specified middlewares.
```ts
app.head("/api/user/:id", async (ctx) => {
return new Response(null, { status: 200 });
});
```
Respond with multiple middlewares:
```ts
app.head("/api/user/:id", middleware1, middleware2, async (ctx) => {
return new Response(null, { status: 200 });
});
```
You can also pass lazy middlewares:
```ts
app.head("/api/user/:id", async () => {
const mod = await import("./middleware-or-handler.ts");
return mod.default;
});
```
## `.all()`
Respond to a request for all HTTP verbs with the specified middlewares.
```ts
app.all("/api/foo", async (ctx) => {
return new Response("hehe");
});
```
Respond with multiple middlewares:
```ts
app.all("/api/foo", middleware1, middleware2, async (ctx) => {
return new Response("hehe");
});
```
You can also pass lazy middlewares:
```ts
app.all("/api/foo", async () => {
const mod = await import("./middleware-or-handler.ts");
return mod.default;
});
```
## `.fsRoute()`
Injects all file-based routes, middlewares, layouts and error pages to the app
instance.
```ts
app.fsRoutes();
```
You can optionally pass a path where they should be mounted.
```ts
app.fsRoutes("/foo/bar");
```
> [info]: If possible, routes are lazily loaded. Routes that set a route config
> and set `routeOverride` in particular, are never lazily loaded as Fresh would
> need to load the file to get the route pattern.
## `.route()`
TODO
## `.appWrapper()`
Set the [App Wrapper](/docs/canary/advanced/app-wrapper) component. This is
where the outer HTML, typically up until the `<body>`-tag is rendered.
## `.layout()`
Set a [Layout](/docs/canary/advanced/layouts) component at the specified path.
The app wrapper component and prior layouts are inherited by default unless
opted out.
## `.onError()`
Set an error route or middleware that will be rendered when it catches an error.
Setting a middleware:
```ts
// top level error handler
app.onError("*", (ctx) => {
return new Response(String(ctx.error), { status: 500 });
});
```
Setting a route:
TODO
## `.notFound()`
Call this middleware or route whenever a HTTP 404 error is caught.
```ts
app.notFound(() => {
return new Response("Not found", { status: 404 });
});
```
TODO: Route
## `.mountApp()`
TODO
## `.handler()`
Create a handler function out of your app. This is a function where you can pass
a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) instance
to and receive a
[`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
```ts
const app = new App()
.get("/", () => new Response("hello"));
const handler = app.handler();
const response = await handler(new Request("http://localhost"));
console.log(await response.text()); // Logs: "hello"
```
This functionality is often used during testing or to run Fresh inside other
frameworks.
## `.listen()`
Spawns a server and listens for incoming connections.
```ts
const app = new App()
.get("/", () => new Response("hello"));
app.listen();
```
You can pass an options object to customize which port to listen on and other
aspects.
```ts
app.listen({ port: 4000 });
```
-155
View File
@@ -1,155 +0,0 @@
---
description: Plugins can add new functionality to Fresh without requiring significant complexity.
---
The `Context` instance is shared across all middlewares in Fresh. Use it to
respond with HTML, trigger redirects, access the incoming
[`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) or read
other metadata.
## `.config`
Contains the resolved Fresh configuration.
```ts
app.get("/", (ctx) => {
console.log("Config: ", ctx.config);
return new Response("hey");
});
```
## `.url`
Contains a [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL)
instance of the requested url.
```ts
app.get("/", (ctx) => {
console.log("path: ", ctx.url.pathname);
const hasParam = ctx.url.searchParams.has("q");
return new Response(`Has q param: ${hasParam}`);
});
```
## `.req`
Contains the incoming
[`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) instance.
```ts
app.get("/", (ctx) => {
console.log("Request: ", ctx.req);
if (ctx.req.headers.has("X-Foo")) {
// do something
}
return new Response("hello");
});
```
## `.route`
Contains the matched route pattern as a `string`. Will be `null` if no pattern
matched.
```ts
app.get("/foo/:id", (ctx) => {
console.log(ctx.route); // Logs: "/foo/:id
// ...
});
```
## `.params`
Contains the params of the matched route pattern.
```ts
app.get("/foo/:id", (ctx) => {
console.log("id: ", ctx.params.id);
return new Response(`Accessed: /foo/${ctx.params.id}`);
});
```
## `.state`
Pass data to the next middlewares with state. Every request has its own state
object.
```ts
interface State {
text?: string;
}
const app = new App<State>();
app.use((ctx) => {
ctx.state.text = "foo";
return ctx.next();
});
app.use((ctx) => {
console.log(ctx.state.text); // Logs: "foo"
return ctx.next();
});
```
## `.error`
If an error was thrown, this property will hold the caught value (default:
`null`). This is typically used mainly on an error page.
```ts
app.onError((ctx) => {
const message = ctx.error instanceof Error
? ctx.error.message
: String(ctx.error);
return new Response(message, { status: 500 });
});
```
## `.redirect()`
Trigger a redirect from a middleware:
```ts
app.get("/old-url", (ctx) => {
return ctx.redirect("/new-url");
});
```
Set a custom status code (default is `302`):
```ts
app.get("/old-url", (ctx) => {
return ctx.redirect("/new-url", 307);
});
```
## `.render()`
Render JSX and create a HTML `Response`.
```tsx
app.get("/", (ctx) => {
return ctx.render(<h1>hello world</h1>);
});
```
Set custom response headers or other metadata:
```tsx
app.get("/teapot", (ctx) => {
return ctx.render(
<h1>I'm a teapot</h1>,
{
status: 418,
headers: {
"X-Foo": "abc",
},
},
);
});
```
-144
View File
@@ -1,144 +0,0 @@
---
description: |
Routes are the basic building block of Fresh applications. They are used to define the behaviour the application when a given path is requested.
---
Use the `.fsRoutes()` helper on the [`App`](/docs/canary/concepts/app) instance
to specify where file based routes should be inserted. It adds routes based on
the structure in the `routes/` folder in your project (or any other folder you
have specified when instantiating the
[`fresh()` vite plugin](/docs/canary/advanced/vite). in `vite.config.ts`). When
you add a new file there, it will register a new route automatically.
```ts main.ts
import { App, staticFiles } from "fresh";
const app = new App({ basePath: "/foo" })
.use(staticFiles())
.fsRoutes(); // This inserts all file based routes here
```
> [info]: The `staticFiles()` middleware is required when using file based
> routing. Otherwise the necessary JavaScript files for islands won't be served
> to the browser.
Example project structure:
```txt-files Project structure
<project root>
├── deno.json
├── main.ts
├── vite.config.ts
└── routes
   ├── (marketing) # Route group, used to group related routes
   │ ├── _layout.tsx # Apply layout to all routes in this directory
   │ ├── about.tsx # /about route
   │ ├── career.tsx # /career route
│ ├── (_components) # related components
   │ │ └── newsletter-cta.tsx
│ └── (_islands) # Local island directory
│ └── interactive-stats.tsx # Fresh treats this as an island
└── shop
├── (_components)
│ └── product-card.tsx
├── (_islands)
│ └── cart.tsx # Fresh treats this as an island
└── index.tsx
```
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/my-route.ts
import { RouteConfig } from "fresh";
export const config: RouteConfig = {
routeOverride: "/x/:module@:version/:path*",
};
// ...
```
## Route Groups
When working with [layouts](/docs/concepts/layouts) or
[middlewares](/docs/concepts/middleware), you'll sometimes come across a
situation where you want your routes to inherit from a layout other than what's
suggested by the URL segment.
Let's illustrate that with an example:
```txt Example page layout
/about -> layout A
/career -> layout A
/archive -> layout B
/contact -> layout B
```
Without any way to group routes this is a problem because every route segment
can only have one `_layout` file.
```txt-files Project structure
└── <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
-36
View File
@@ -1,36 +0,0 @@
---
description: |
This chapter goes over some fundamental concepts of Fresh.
---
The way Fresh works is that it receives a
[`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request), passes it
through one or more middlewares until one of them responds. This can be an HTML
response, a JSON response or any other response for that matter.
If the response was HTML and contained Islands (=interactive Preact components),
Fresh will boot them up in the browser and execute the relevant JavaScript.
Here is an overview of the basic concepts in Fresh:
- [**App**](/docs/canary/concepts/app) - Holds all the information about your
app, like routes, etc
- [**Middleware**](/docs/canary/concepts/middleware) - Respond to a request and
return a `Response`. Used to set headers, or pass state to other middelwares.
When a middleware doesn't call the next one and returns a response, it's
usually called a "handler".
- [**Context**](/docs/canary/context) - Passed through every middleware. Use
this to share state, trigger redirects or render HTML.
- [**Routes**](/docs/canary/routes) - Responds to a particular URL and runs as
chain of middlewares if it matches
- [**Islands**](/docs/canary/concepts/islands) - Render interactive Preact
components on the client
Advanced concepts:
- [**App wrapper**](/docs/canary/advanced/app-wrapper) - Responsible for the
outer HTML structure, usually up to the `<body>`-tag
- [**Layouts**](/docs/canary/advanced/layouts) - Re-use a shared layout when
calling `ctx.render()` across routes
- [**Partials**](/docs/canary/advanced/partials) - Stream in server generated
content on the current page
-135
View File
@@ -1,135 +0,0 @@
---
description: |
Islands enable client side interactivity in Fresh. They are hydrated on the client in addition to being rendered on the server.
---
Islands enable client side interactivity in Fresh and they are rendered both on
the server and in the client.
Islands are defined by creating a file in the `islands/` folder or a
`(_islands)` folder somewhere in the `routes/` directory. The name of this file
must be a PascalCase or kebab-case name of the island.
```tsx islands/my-island.tsx
import { useSignal } from "@preact/signals";
export default function MyIsland() {
const count = useSignal(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => (count.value += 1)}>+</button>
</div>
);
}
```
An island can be used anywhere like a regular Preact component. Fresh will take
care of making it interactive on the client.
```tsx main.tsx
import { App, staticFiles } from "fresh";
import MyIsland from "./islands/my-island.tsx";
const app = new App()
.use(staticFiles())
.get("/", (ctx) => ctx.render(<MyIsland />));
```
## Passing props to islands
Passing props to islands is supported, but only if the props are serializable.
Fresh can serialize the following types of values:
- Primitive types `string`, `number`, `boolean`, `bigint`, `undefined`, and
`null`
- `Infinity`, `-Infinity`, `-0`, and `NaN`
- `Uint8Array`
- `URL`
- `Date`
- `RegExp`
- `JSX` Elements
- Collections `Map` and `Set`
- Plain objects with string keys and serializable values
- Arrays containing serializable values
- Preact Signals (if the inner value is serializable)
Circular references are supported. If an object or signal is referenced multiple
times, it is only serialized once and the references are restored upon
deserialization.
> [warn]: Passing functions to an island is not supported.
>
> ```tsx routes/example.tsx
> export default function () {
> // WRONG
> return <MyIsland onClick={() => console.log("hey")} />;
> }
> ```
### Passing JSX
A powerful feature of Fresh is that you can pass server-rendered JSX to an
island via props.
```tsx routes/index.tsx
import { staticFiles } from "fresh";
import MyIsland from "../islands/my-island.tsx";
const app = new App()
.use(staticFiles())
.get("/", (ctx) => {
return ctx.render(
<MyIsland jsx={<h1>hello</h1>}>
<p>This text is rendered on the server</p>
</MyIsland>,
);
});
```
### Nesting islands
Islands can be nested within other islands as well. In that scenario they act
like a normal Preact component, but still receive the serialized props if any
were present.
In essence, Fresh allows you to mix static and interactive parts in your app in
a way that's most optimal for your app. We'll keep sending only the JavaScript
that is needed for the islands to the browser.
```tsx islands/other-island.tsx
export default (props: { foo: string }) => <>{props.foo}</>;
```
```tsx route/index.tsx
import MyIsland from "../islands/my-island.tsx";
import OtherIsland from "../islands/other-island.tsx";
// Later...
<div>
<MyIsland>
<OtherIsland foo="this prop will be serialized" />
</MyIsland>
<p>Some more server rendered text</p>
</div>;
```
## Rendering islands on client only
When using client-only APIs, like `EventSource` or `navigator.getUserMedia`,
this component will not run on the server as it will produce an error. To fix
this use the `IS_BROWSER` flag as a guard:
```tsx islands/my-island.tsx
import { IS_BROWSER } from "fresh/runtime";
export function MyIsland() {
// Return any prerenderable JSX here which makes sense for your island
if (!IS_BROWSER) return <div></div>;
// All the code which must run in the browser comes here!
// Like: EventSource, navigator.getUserMedia, etc.
return <div></div>;
}
```
-105
View File
@@ -1,105 +0,0 @@
---
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 { define } from "../../utils.ts";
export default define.layout({ Component, state }) => {
// 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 { define } from "../../utils.ts";
export default define.layout(async (ctx) => {
// do something with state here
const data = await loadData();
return (
<div class="layout">
<p>{data.greeting}</p>
<ctx.Component />
</div>
);
});
```
## 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 { type RouteConfig } from "fresh";
import { define } from "../../utils.ts";
export const config: RouteConfig = {
skipInheritedLayouts: true, // Skip already inherited layouts
};
export default define.layout(() => {
return <p>Hello world</p>;
});
```
You can skip already inherited layouts inside a layout file:
```tsx routes/special/_layout.tsx
import { type LayoutConfig } from "fresh";
export const config: LayoutConfig = {
skipInheritedLayouts: true, // Skip already inherited layouts
};
export default function MyPage() {
return <p>Hello world</p>;
}
```
-89
View File
@@ -1,89 +0,0 @@
---
description: |
Add middleware routes to intercept requests or responses for analytics purposes, access control, or anything else.
---
A middleware is a function that receives a [`Context`](/docs/canary/context)
object with the
[`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) and
returns a
[`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response). They
are typically used to set HTTP Headers, measure response times or fetch data and
pass it to another middleware.
```tsx main.ts
const app = new App<{ greeting: string }>()
.use((ctx) => {
// Middleware to pass data
ctx.state.greeting = "Hello world";
return ctx.next();
})
.use(async (ctx) => {
// Middleware to add a HTTP header
const res = await ctx.next();
res.headers.set("server", "fresh server");
return res;
})
// A handler is a form of middleware that responds. Here we
// render HTML and return it.
.get("/", (ctx) => {
return ctx.render(<h1>{ctx.state.greeting}</h1>);
});
```
Middlewares can be chained and combined in whatever way you desire. They are an
excellent way to make http-related logic reusable on the server.
## Middleware helper
Use the `define.middleware()` helper to get typings out of the box:
```ts middleware/my-middleware.ts
import { define } from "./utils.ts";
const middleware = define.middleware(async (ctx) => {
console.log("my middleware");
return await ctx.next();
});
```
## Included middlewares
Fresh ships with the following middlewares built-in:
- [cors()](/docs/canary/plugins/cors) - Set CORS HTTP headers
- [csrf()](/docs/canary/plugins/cors) - Set CSRF HTTP headers
- [trailingSlash()](/docs/canary/plugins/trailing-slashes) - Enforce trailing
slashes
## Filesystem-based middlewares
With file system based routing you can define a middleware in a `_middleware.ts`
file inside the `routes/` folder or any of it's subfolders.
```ts routes/foo/_middleware.ts
import { define } from "./utils.ts";
export default define.middleware(async (ctx) => {
console.log("my middleware");
return await ctx.next();
});
```
You can also export an array of middlewares:
```ts routes/foo/_middleware.ts
import { define } from "./utils.ts";
const middleware1 = define.middleware(async (ctx) => {
console.log("A");
return await ctx.next();
});
const middleware2 = define.middleware(async (ctx) => {
console.log("B");
return await ctx.next();
});
export default [middleware1, middleware2];
```
-32
View File
@@ -1,32 +0,0 @@
---
description: |
File based routing is the simplest way to do routing in Fresh apps. Additionally custom patterns can be configured per route.
---
Routing defines which middlewares and routes should respond to a particular
request.
```ts main.ts
const app = new App()
.get("/", () => new Response("hello")) // Responds to: GET /
.get("/other", () => new Response("other")) // Responds to: GET /other
.post("/upload", () => new Response("upload")) // Responds to: POST /upload
.get("/books/:id", (ctx) => {
// Responds to: GET /books/my-book, /books/cool-book, etc
const id = ctx.params.id;
return new Response(`Book id: ${id}`);
})
.get("/blog/:post/comments", () => {
// Responds to: GET /blog/my-post/comments, /blog/hello/comments, etc
const post = ctx.params.post;
return new Response(`Blog post comments for post: ${post}`);
})
.get("/foo/*", (ctx) => {
// Responds to: GET /foo/bar, /foo/bar/baz, etc
return new Response("foo");
});
```
Fresh supports the full
[`URLPattern`](https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API)
syntax for setting pathnames.
-52
View File
@@ -1,52 +0,0 @@
---
description: |
Fresh has built-in support for serving static files. This is useful for serving images, CSS, and other static assets.
---
Static assets placed in the `static/` directory are served at the root of the
webserver via the `staticFiles()` middleware. They are streamed directly from
disk for optimal performance with
[`ETag`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/ETag)
headers.
```ts main.ts
import { staticFiles } from "fresh";
const app = new App()
.use(staticFiles());
```
## Caching headers
By default, Fresh adds caching headers for the `src` and `srcset` attributes on
`<img>` and `<source>` tags.
```tsx main.tsx
// Caching headers will be automatically added
app.get("/user", (ctx) => ctx.render(<img src="/user.png" />));
```
You can always opt out of this behaviour per tag, by adding the
`data-fresh-disable-lock` attribute.
```tsx main.tsx
// Opt-out of automatic caching headers
app.get(
"/user",
(ctx) => ctx.render(<img src="/user.png" data-fresh-disable-lock />),
);
```
## Adding caching headers manually
Use the `asset()` function to add caching headers manually. It will be served
with a cache lifetime of one year.
```tsx routes/about.tsx
import { asset } from "fresh/runtime";
export default function About() {
// Adding caching headers manually
return <a href={asset("/brochure.pdf")}>View brochure</a>;
}
```
@@ -1,27 +0,0 @@
---
description: "Deploy Fresh on Cloudflare Workers"
---
Deploy Fresh to Cloudflare Workers by following these instructions:
1. Run `deno install --allow-scripts npm:@cloudflare/vite-plugin npm:wrangler`
2. Add the cloudflare plugin in your vite configuration file:
```diff vite.config.ts
import { defineConfig } from "vite";
import { fresh } from "@fresh/plugin-vite";
+ import { cloudflare } from "@cloudflare/vite-plugin";
export default defineConfig({
plugins: [
fresh(),
+ cloudflare(),
],
});
```
3. Follow further instructions provided by the cloudflare vite plugin.
Check out the
[Cloudflare Documentation](https://developers.cloudflare.com/workers/vite-plugin/)
for further information.
-20
View File
@@ -1,20 +0,0 @@
---
description: "Generate a self contained executable with deno compile."
---
You can create a self-contained executable out of your app with the
[`deno compile` command](https://docs.deno.com/runtime/reference/cli/compile/).
It will include all assets and dependencies. This executable can run on any
platform without requiring Deno to be installed.
```sh
# Build your app first
$ deno task build
# Generate self-contained executable
deno compile --include static --include _fresh --include deno.json -A my-app _fresh/compiled-entry.js
```
The compiled entry supports two environment variables out of the box:
- `PORT` to set the port number (`PORT=4000 my-app`)
- `HOSTNAME` to set the host name number (`HOSTNAME=0.0.0.0 my-app`)
-16
View File
@@ -1,16 +0,0 @@
---
description: "Deploy Fresh on Deno Deploy"
---
The recommended way to deploy Fresh is by using
[Deno Deploy](https://deno.com/deploy). It will automatically create branch
previews for pull requests, collect request and HTTP metrics, as well has
collect traces for you out of the box.
1. Log in to [Deno Deploy](https://deno.com/deploy)
1. Create a new app
1. Link your GitHub repository
1. Pick the "Fresh" preset if it's not already detected automatically
Every time you merge into the `main` branch a new production deployment will be
created.
-51
View File
@@ -1,51 +0,0 @@
---
description: "Deploy Fresh with 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:latest
ARG GIT_REVISION
ENV DENO_DEPLOYMENT_ID=${GIT_REVISION}
WORKDIR /app
COPY . .
RUN deno task build
RUN deno cache _fresh/server.js
EXPOSE 8000
CMD ["serve", "-A", "_fresh/server.js"]
```
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](https://docs.aws.amazon.com/AmazonECS/latest/userguide/create-container-image.html#create-container-image-push-ecr)
- [Google Cloud](https://cloud.google.com/container-registry/docs/pushing-and-pulling)
-35
View File
@@ -1,35 +0,0 @@
---
description: "Create a production build of your app"
---
When shipping an app to production, we can run a build step that optimizes
assets for consumption in the browser. This step can be invoked by running:
```sh Terminal
deno task build
# or
deno run -A dev.ts build
```
Once completed, it will have created a `_fresh` folder in the project directory
which contains the optimized assets.
> [info]: The `_fresh` folder should not be committed to git. Exclude it via
> `.gitignore`.
>
> ```gitignore .gitignore
> # Ignore fresh build directory
> _fresh/
> ```
## Running a production build
To run Fresh in production mode, run the `start` task:
```sh Terminal
deno task start
# or
deno serve -A _fresh/server.js
```
Fresh will automatically pick up the optimized assets in the `_fresh` directory.
-48
View File
@@ -1,48 +0,0 @@
---
description: |
Style active links with ease in Fresh
---
Fresh automatically enhances the accessibility of `<a>` elements by adding the
aria-current attribute when rendering links that match the current URL. This
attribute is recognized by assistive technologies and clearly indicates the
current page within a set of pages.
- `aria-current="page"` - Added to links with an exact path match, enhancing
accessibility by indicating the current page to assistive technologies.
As we aim to improve accessibility, we encourage the use of aria-current for
styling current links where applicable.
## Styling with CSS
The aria-current attribute is easily styled with CSS using attribute selectors,
providing a native way to visually differentiate the active link.
```css static/styles.css
/* Give links pointing to the current page a green color */
a[aria-current="page"] {
color: green;
}
/* Color all ancestor links of the current page */
a[aria-current="true"] {
color: peachpuff;
}
```
## Tailwindcss
In Tailwindcss or similar CSS frameworks, you can apply styles to elements with
the `aria-current` attribute using bracket notation in your class definitions.
For Tailwindcss, use the syntax:
```tsx components/Menu.tsx
function Menu() {
return (
<a href="/foo" class="aria-[current]:text-green-600">
Link to some page
</a>
);
}
```
-58
View File
@@ -1,58 +0,0 @@
---
title: Install daisyUI for Deno Fresh
desc: How to install Tailwind CSS and daisyUI in a Deno Fresh project
---
[daisyUI](https://daisyui.com/) is a component library for
[Tailwind CSS](https://tailwindcss.com/) that provides semantic class names for
common UI components like buttons, cards, and modals. It makes building
beautiful interfaces faster while maintaining full Tailwind CSS compatibility.
## Installation
To get started with daisyUI, make sure you have Tailwind CSS enabled in your
Fresh project, then install daisyUI and update your configuration.
1. Run `deno i -D npm:daisyui@latest` to install daisyUI
2. Add daisyUI configuration in `./static/styles.css`:
```diff static/styles.css
@import "tailwindcss";
+ @plugin "daisyui";
```
Now you're ready to use daisyUI.
## Using daisyUI Components
Create a button component in the `components` directory, using daisyUI's style
classes for reference.
```tsx components/Button.tsx
import type { ComponentChildren } from "preact";
export interface ButtonProps {
id?: string;
onClick?: () => void;
children?: ComponentChildren;
disabled?: boolean;
}
export function Button(props: ButtonProps) {
return (
<button
className="btn btn-dash btn-primary"
{...props}
/>
);
}
```
### Display Effect
![DaisyUI Showcase](/docs/fresh-daisyui-showcase.jpg)
### daisyUI Class Name Reference
For more components and usage, please refer to the
[daisyUI official documentation](https://daisyui.com/)
-59
View File
@@ -1,59 +0,0 @@
---
description: |
How to render markdown on your Fresh site.
---
[Markdown](https://www.markdownguide.org/basic-syntax/) is a common text-based
file format that is often used for writing documentation, blogs and more. In
this example we are going convert markdown content to HTML and send it to the
browser.
First, let's install the [`@deno/gfm`](https://jsr.io/@deno/gfm) package that
can transform markdown to html.
1. Run `deno install jsr:@deno/gfm`
2. Create a markdown file like `content.md`:
```md path/to/content.md
## some heading
and some interesting text here
> oh look a blockquote
```
4. Add a route that renders that file
```tsx main.ts
import { CSS, render as renderMarkdown } from "@deno/gfm";
const CONTENT = `## some heading
and some interesting text here
> oh look a blockquote
`;
const app = new App();
app.get("/", async (ctx) => {
const content = await Deno.readTextFile("path/to/content.md");
const html = renderMarkdown(content);
return await ctx.render(
<div>
<h1>Here comes a markdown post:</h1>
<style dangerouslySetInnerHTML={{ __html: CSS }} />
<div dangerouslySetInnerHTML={{ __html: html }} />
</div>,
);
});
```
## Other libraries
There are several other popular libraries besides `@deno/gfm` that can be used
to render markdown. The most common ones are:
- [marked](https://marked.js.org/)
- [remark](https://remark.js.org/)
-290
View File
@@ -1,290 +0,0 @@
---
description: |
Migration guide for Fresh 2.x
---
We tried to keep breaking changes in Fresh 2 as minimal as possible, but some
changes need to be updated manually. Fresh 2 comes with many quality of life
[improvements](https://deno.com/blog/an-update-on-fresh) that make it easier to
extend and adapt Fresh. We've created this upgrade guide as part of upgrading
our own apps here at Deno.
Use this guide to migrate a Fresh 1.x app to Fresh 2.
## Applying automatic updates
Most changes can be applied automatically with the update script. Start the
update by running it in your project directory:
```sh Terminal
deno run -Ar jsr:@fresh/update
```
This will apply most API changes made in Fresh 2 automatically update like
changing `$fresh/server.ts` imports to `fresh`.
## Getting `main.ts` and `dev.ts` ready
Configuring Fresh doesn't require a dedicated config file anymore. You can
delete the `fresh.config.ts` file. The `fresh.gen.ts` manifest file isn't needed
anymore either.
```diff Project structure
<project root>
├── routes/
- ├── dev.ts
- ├── fresh.gen.ts
- ├── fresh.config.ts
└── main.ts
```
Fresh 2 takes great care in ensuring that code that's only needed during
development is separate from production code. This split makes deployments much
smaller, quicker to upload and allows them to boot up much quicker in
production.
### Replacing `dev.ts` with `vite.config.ts`
Delete `dev.ts` and create a `vite.config.ts` file instead. Pass your custom
Fresh configuration to the [fresh vite plugin](/docs/canary/advanced/vite).
```ts vite.config.ts
import { defineConfig } from "vite";
import { fresh } from "@fresh/plugin-vite";
import tailwindcss from "@tailwindcss/vite";
export default defineConfig({
plugins: [
fresh(),
tailwindcss(),
],
});
```
### Add a `client.ts` file
The `client.ts` file is the main entry file for client-side code. Since vite
requires everything to be part of the internal module graph to get hot module
reloading to work, this is also the place where you import CSS assets.
```diff Project structure
<project root>
├── routes/
+ ├── client.ts
├── vite.config.ts
└── main.ts
```
```ts client.ts
// Import CSS files here for hot module reloading to work.
import "./assets/styles.css";
```
### Updating `main.ts`
Similarly, configuration related to running Fresh in production can be passed to
`new App()`:
```ts main.ts
import { App, staticFiles } from "fresh";
export const app = new App()
// Add static file serving middleware
.use(staticFiles())
// Enable file-system based routing
.fsRoutes();
```
## Merging error pages
Both the `_500.tsx` and `_404.tsx` template have been unified into a single
`_error.tsx` template.
```diff Project structure
└── <root>/routes/
- ├── _404.tsx
- ├── _500.tsx
+ ├── _error.tsx
└── ...
```
Inside the `_error.tsx` template you can show different content based on errors
or status codes with the following code:
```tsx routes/_error.tsx
export default function ErrorPage(props: PageProps) {
const error = props.error; // Contains the thrown Error or HTTPError
if (error instanceof HttpError) {
const status = error.status; // HTTP status code
// Render a 404 not found page
if (status === 404) {
return <h1>404 - Page not found</h1>;
}
}
return <h1>Oh no...</h1>;
}
```
## Updating tasks
The server entrypoint is now generated by Fresh for more optimal startup times.
This means you need to update your task when launching Fresh in production mode.
To launch Fresh in production mode:
```diff
- deno run -A main.ts
+ deno serve -A _fresh/server.js
```
You'll likely have that command inside your `deno.json` as a task. Update it
accordingly.
```diff deno.json
{
"tasks":
- "dev": "deno run -A dev.ts",
- "build": "deno run -A dev.ts build",
- "preview": "deno run -A main.ts"
+ "dev": "vite",
+ "build": "vite build",
+ "preview": "deno serve -A _fresh/server.js"
}
}
```
## Update deployment settings
Fresh 2 requires assets to be build during deployment instead of building them
on demand. Run the `deno task build` command as part of your deployment process.
If you have already set up Fresh's 1.x "Ahead-of-Time Builds", then no changes
are necessary.
## Trailing slash handling
The handling trailing slashes has been extracted to an optional middleware that
you can add if needed. This middleware can be used to ensure that URLs always
have a trailing slash at the end or that they will never have one.
```diff main.ts
- import { App, staticFiles } from "fresh";
+ import { App, staticFiles, trailingSlashes } from "fresh";
export const app = new App({ root: import.meta.url })
.use(staticFiles())
+ .use(trailingSlashes("never"));
```
## Automatic updates
> [info]: The changes listed here are applied automatically when running the
> [`@fresh/update`](https://jsr.io/@fresh/update) script and you shouldn't need
> to have to do these yourself.
### Unified middleware signatures
Middleware, handler and route component signatures have been unified to all look
the same. Instead of receiving two arguments, they receive one. The `Request`
object is stored on the context object as `ctx.req`.
```diff middleware.ts
- const middleware = (req, ctx) => new Response("ok");
+ const middleware = (ctx) => new Response("ok");
```
Same is true for handlers:
```diff route/page.tsx
export const handler = {
- GET(req, ctx) {
+ GET(ctx) {
return new Response("ok");
},
};
```
...and async route components:
```diff routes/my-page.tsx
- export default async function MyPage(req: Request, ctx: RouteContext) {
+ export default async function MyPage(props: PageProps) {
const value = await loadFooValue();
return <p>foo is: {value}</p>;
}
```
All the various context interfaces have been consolidated and simplified:
| Fresh 1.x | Fresh 2.x |
| --------------------------------------------- | ------------------------------------------ |
| `AppContext`, `LayoutContext`, `RouteContext` | [`Context`](/docs/canary/concepts/context) |
### Context methods
The `ctx.renderNotFound()` method has been removed in favor of throwing an
`HttpError` instance. This allows all middlewares to optionally participate in
error handling. Other properties have been moved or renamed to make it easier to
re-use existing objects internally as a minor performance optimization.
| Fresh 1.x | Fresh 2.x |
| ---------------------- | -------------------------- |
| `ctx.renderNotFound()` | `throw new HttpError(404)` |
| `ctx.basePath` | `ctx.config.basePath` |
| `ctx.remoteAddr` | `ctx.info.remoteAddr` |
### `ctx.render()`
The meaning of `ctx.render()` has changed. In Fresh 1.x this was used to pass
data from a handler to a component. In Fresh 2.x this function has been
generalized to render JSX.
Fresh 1.x:
```ts
export const handlers = {
async GET(req, ctx) {
const data = await Query();
await ctx.render({ value: data });
},
};
export default function Page({ data }) {
// ...
}
```
Fresh 2:
```ts
export const handlers = {
async GET(ctx) {
const data = await Query();
return { data: { value: data } };
},
};
export default function Page({ data }) {
// ...
}
```
To render JSX in general, use the `ctx.render()` function:
```tsx
const app = new App()
.get("/", () => ctx.render(<h1>hello</h1>));
```
## `createHandler`
The `createHandler` function was often used to launch Fresh for tests. This can
be now done via vite's `createBuilder` function. See the
[testing page](/docs/canary/testing) for more information.
## Getting help
If you run into problems with upgrading your app, reach out to us by creating an
issue here https://github.com/denoland/fresh/issues/new . That way we can
improve this migration guide for everyone.
@@ -1,32 +0,0 @@
---
description: |
How to render raw HTML in Fresh.
---
Text content in Fresh is always escaped, whether serverside rendered or rendered
in islands. While this generally desired, it can create issues in certain
situations.
To address this you can render raw HTML via Preact's `dangerouslySetInnerHTML`
prop:
```tsx routes/dynamic-html.tsx
<div dangerouslySetInnerHTML={{ __html: "<h1>This is raw HTML</h1>" }} />;
```
This will output:
```html Response body
<div>
<h1>This is raw HTML</h1>
</div>
```
A common use case for rendering raw HTML is syntax highlighting code blocks or
rendering markdown.
> [warn]: Setting arbitrary HTML can be dangerous, hence the
> `dangerouslySetInnerHTML` naming. Make sure you trust the source. Rendering
> user-supplied HTML to the DOM makes your site vulnerable to cross- site
> scripting. The markup must first be sanitizied, or better yet, something you
> trust.
-128
View File
@@ -1,128 +0,0 @@
---
description: |
In this chapter of the Fresh documentation, you'll be introduced to the
framework. Create a new project, run it locally, edit and create pages, fetch
data, handle user interactions, and deploy it.
---
Let's set up your first Fresh project. To create a new project, run this
command:
```sh Terminal
deno run -Ar jsr:@fresh/init
```
This will span a short wizard that guides you through the setup, like the
project name, if you want to use tailwindcss and if you're using vscode. Your
project folder should look like this:
```txt-files Project structure
<project root>
├── components/ # Store other components here. Can be named differently
│ └── Button.tsx
├── islands/ # Components that need JS to run client-side
│ └── Counter.tsx
├── routes/ # File system based routes
│   ├── api/
│   │ └── [name].tsx # API route for /api/:name
│   ├── _app.tsx # Renders the outer <html> content structure
│   └── index.tsx # Renders /
├── static/ # Contains static assets like css, logos, etc
│   └── ...
│
├── client.ts # Client entry file that's loaded on every page.
├── main.ts # The server entry file of your app
├── deno.json # Contains dependencies, tasks, etc
└── vite.config.ts # Vite configuration file
```
Run the `dev` task to launch your app in development mode:
```sh Terminal
deno task dev
```
Go to the URL printed in the terminal to view your app.
![Screenshot of the newly initialized Fresh app showing a counter](/docs/getting-started-1-init.jpg)
## Creating our first route
Let's create a new about page at `/about`. We can do that by adding a new file
at `routes/about.tsx`.
```tsx routes/about.tsx
import { define } from "../utils.ts";
export default define.page(() => {
return (
<main>
<h1>About</h1>
<p>This is the about page.</p>
</main>
);
});
```
If we navigate to `/about` in the browser we'll see our newly created page.
![Screenshot of the /about route](/docs/getting-started-2-about.png)
## Create an island
We're going to create a countdown component that requires JavaScript to function
in the browser.
Create a new file at `islands/Countdown.tsx`
```tsx islands/Countdown.tsx
import { useSignal } from "@preact/signals";
import { useEffect } from "preact/hooks";
export function Countdown(props: { target: string }) {
const count = useSignal(10);
useEffect(() => {
const timer = setInterval(() => {
if (count.value <= 0) {
clearInterval(timer);
}
count.value -= 1;
}, 1000);
return () => clearInterval(timer);
}, []);
if (count.value <= 0) {
return <p>Countdown: 🎉</p>;
}
return <p>Countdown: {count}</p>;
}
```
Let's add the countdown to our about page:
```tsx routes/about.tsx
import { define } from "../utils.ts";
import { Countdown } from "../islands/Countdown.tsx";
export default define.page(() => {
return (
<main>
<h1>About</h1>
<p>This is the about page.</p>
<Countdown />
</main>
);
});
```
Now, we can see our countdown in action:
![Screenshot of the countdown component](/docs/getting-started-3-cotuntdown.png)
## Next steps
TODO
-75
View File
@@ -1,75 +0,0 @@
---
description: |
Fresh is a full stack modern web framework for JavaScript and TypeScript
developers, designed to build high-quality, performant,
and personalized web applications.
---
Fresh is a small, fast and extensible full stack web framework built on Web
Standards. It's designed for building high-quality, performant, and personalized
web applications.
```tsx main.tsx
import { App } from "fresh";
const app = new App()
.get("/", () => new Response("hello world"))
.get("/jsx", (ctx) => ctx.render(<h1>render JSX!</h1>));
app.listen();
```
## Quick Start
Create a new Fresh app by running:
```sh Terminal
deno run -Ar jsr:@fresh/init
```
## Features
The core idea powering Fresh is to render server generated HTML pages and only
ship JavaScript for areas in the page that need to be interactive. This is often
referred to as the
[Island Architecture](https://jasonformat.com/islands-architecture).
- **Fast** 🚀 - Rendering is super fast thanks to [Preact][preact] and Deno's
[`precompile` transform](https://docs.deno.com/runtime/reference/jsx/#jsx-precompile-transform)
- **Lightweight** 🏎️ - Only ship the JavaScript you need
- **Extensible** 🧩 - Nearly every aspect can be customized
- **Powerful & small API** 🤗 - Familiar APIs make you productive quickly
- **Built-in OpenTelemetry** 📈 - Built-in support for OpenTelemetry
## When to use Fresh
Fresh is ideal for sites and apps that are primarily server rendered, like a
home page, an e-commerce shop or something like GitHub or Bluesky.
- Web APIs
- E-Commerce shops
- Portfolio sites
- Landing pages & Documentation
- CRUD apps
That said, if you want to build a Single-Page-App (=SPA), then Fresh is not the
right framework.
## Who is using Fresh?
Fresh powers [deno.com](https://deno.com) and [Deno Deploy][deno-deploy] among
many other projects at Deno. It's also used by [deco.cx](https://deco.cx/) for
e-commerce projects.
## Where to host Fresh apps?
Fresh is most often deployed on [Deno Deploy][deno-deploy] where it can be
deployed with 1-click and has out of the box integrations with metrics among
other things.
Fresh projects can be deployed manually to any platform with [Deno][deno] like
via docker containers too.
[preact]: https://preactjs.com
[deno]: https://deno.com
[deno-deploy]: https://deno.com/deploy
-28
View File
@@ -1,28 +0,0 @@
---
description: "Set CORS HTTP headers with the cors middleware"
---
The `cors()` middleware can be used to add
[Cross-Origin-Resource-Sharing headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS)
to HTTP requests. These allow the server to indicate which origins (domains,
scheme or port) other than its own is permitted to load resources from.
```ts main.ts
import { cors } from "fresh";
const app = new App()
.use(cors({
origin: "http://example.com",
allowHeaders: ["X-Custom-Header", "Upgrade-Insecure-Requests"],
allowMethods: ["POST", "GET", "OPTIONS"],
exposeHeaders: ["Content-Length", "X-Kuma-Revision"],
maxAge: 600,
credentials: true,
}))
.get("/", () => new Response("hello"));
```
## Options
See the [API docs](https://jsr.io/@fresh/core/doc/~/cors) for a list of all
supported options
-37
View File
@@ -1,37 +0,0 @@
---
description: "Prevent Cross-Site Request Forgery with this middleware"
---
The `csrf()` middleware can be used to add safeguard against
[Cross-Site Request Forgery vulnerabilities](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/CSRF).
It checks if the user is allowed to load the requested URL based on the values
in the
[`Sec-Fetch-Site`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Sec-Fetch-Site)
header and
[`Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Origin)
header. to HTTP requests. These allow the server to indicate which origins
(domains, scheme or port) other than its own is permitted to load resources
from.
```ts main.ts
import { app, csrf } from "fresh";
const app = new App();
app.use(csrf());
// Specify a single origin
app.use(csrf({ origin: "https://example.com" }));
// Specify multiple origins
app.use(
csrf({ origin: ["https://example.com", "https://trusted.example.com"] }),
);
// Use a function
app.use(
csrf({
origin: (origin) => /^https:\/\/(foo|bar)\.example\.com$/.test(origin),
}),
);
```
-25
View File
@@ -1,25 +0,0 @@
---
description: "Extend fresh with plugins"
---
Fresh itself can be extended through the methods available on the
[`App`](/docs/canary/concepts/app) class or on the `Builder` class. Most of the
features in Fresh itself are built using these APIs.
## Custom middlewares
If you need to modify requests, add HTTP headers or pass additional data to
other middlewares via `ctx.state`, then going with a middleware is the way to
go.
```ts middleware/fresh.ts
const addXFreshHeader = define.middleware(async (ctx) => {
const res = await ctx.next();
res.headers.set("X-Fresh", "served by Fresh");
return res;
});
```
Learn more about [middlewares](/docs/canary/concepts/middleware).
TODO: Show more ways
-25
View File
@@ -1,25 +0,0 @@
---
description: "Ensure URLs always end or never end with trailing slashes"
---
The `trailingSlashes()` middleware can be used to ensure URL pathnames always
end with a slash character or will never end with one. It redirects the user's
request respectively.
```ts main.ts
import { trailingSlashes } from "fresh";
const app = new App()
.use(trailingSlashes("never"))
.get("/", () => new Response("hello"));
```
Always append a trailing slash:
```ts main.ts
import { trailingSlashes } from "fresh";
const app = new App()
.use(trailingSlashes("always"))
.get("/", () => new Response("hello"));
```
-138
View File
@@ -1,138 +0,0 @@
---
description: |
Add a global app wrapper to provide common meta tags or context for application routes.
---
To ensure that your application works as expected we can write tests. Any aspect
of Fresh can be tested as a whole together or in isolation. We use Deno's
built-in [test runner](https://docs.deno.com/runtime/fundamentals/testing/) to
write tests.
## Testing middlewares
To test [middlewares](/docs/canary/concepts/middleware) we're going to create a
dummy app and return the relevant info we want to check in a custom `/` handler.
```ts middleware.test.ts
import { expect } from "@std/expect";
import { App } from "fresh";
const middleware = define.middleware((ctx) => {
ctx.state.text = "middleware text";
return ctx.next();
});
Deno.test("My middleware - sets ctx.state.text", async () => {
const handler = new App()
.use(middleware)
.get("/", (ctx) => new Response(ctx.state.text))
.handler();
const res = await handler(new Request("http://localhost"));
const text = await res.text();
expect(text).toEqual("middleware text");
});
```
You can extend this pattern for other middlewares. When you have a middleware
that adds a header to the returned response, you can assert against that too.
## Testing app wrapper or layouts
Both the [app wrapper](/docs/canary/advanced/app-wrapper) component and
[layouts](/docs/canary/advanced/layouts) can be tested in the same way.
```tsx routes/_app.test.tsx
import { expect } from "@std/expect";
import { App } from "fresh";
function AppWrapper({ Component }) {
return (
<html lang="en">
<head>
<meta charset="utf-8" />
<title>My App</title>
</head>
<body>
<Component />
</body>
</html>
);
}
Deno.test("App Wrapper - renders title and content", async () => {
const handler = new App()
.appWrapper(AppWrapper)
.get("/", (ctx) => ctx.render(<h1>hello</h1>))
.handler();
const res = await handler(new Request("http://localhost"));
const text = await res.text();
expect(text).toContain("My App");
expect(text).toContain("Hello");
});
```
Same can be done for layouts.
```tsx routes/_layout.test.tsx
import { expect } from "@std/expect";
import { App } from "fresh";
function MyLayout({ Component }) {
return (
<div>
<h1>My Layout</h1>
<Component />
</div>
);
}
Deno.test("MyLayout - renders heading and content", async () => {
const handler = new App()
.layout("*", MyLayout)
.get("/", (ctx) => ctx.render(<h1>hello</h1>))
.handler();
const res = await handler(new Request("http://localhost"));
const text = await res.text();
expect(text).toContain("My Layout");
expect(text).toContain("Hello");
});
```
## Testing with file routes and islands
[File routes](/docs/canary/concepts//file-routing) are collected by the
[`Builder`](/docs/canary/concepts/builder) class and not just by
[`App`](/docs/concepts/app) alone. We can generate a snapshot and re-use it for
many app instances in our test suite.
```ts my-app.test.ts
import { createBuilder } from "vite";
// Best to do this once instead of for every test case for
// performance reasons.
const builder = await createBuilder({
root: "./path/to/app",
build: {
emptyOutDir: true,
},
});
await builder.build();
const { app } = await import("./path/to/app/_fresh/server.js");
Deno.test("My Test", async () => {
const handler = app.handler();
const response = await handler(new Request("http://localhost"));
const text = await response.text();
if (text !== "hello") {
throw new Error("fail");
}
});
```