docs: update canary docs for Fresh 2 (#3108)
There are still some rough edges here and there, but it's in a much better shape than what we have today.
This commit is contained in:
@@ -0,0 +1,33 @@
|
|||||||
|
---
|
||||||
|
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
|
||||||
|
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()` 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.
|
||||||
@@ -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
|
||||||
|
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,47 @@
|
|||||||
|
---
|
||||||
|
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
|
||||||
|
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
|
||||||
|
<div>
|
||||||
|
<h1>hello world</h1>
|
||||||
|
<aside>Here is some sidebar content</aside>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
## Options
|
||||||
|
|
||||||
|
Add a layout and ignore all previously inherited ones.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
app.layout("/foo/bar", MyComponent, { skipInheritedLayouts: true });
|
||||||
|
```
|
||||||
|
|
||||||
|
Ignore the app wrapper component:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
app.layout("/foo/bar", MyComponent, { skipAppWrapper: true });
|
||||||
|
```
|
||||||
@@ -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
|
||||||
|
- <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
|
||||||
|
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
|
||||||
|
<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,243 @@
|
|||||||
|
---
|
||||||
|
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
|
||||||
|
const app = new App()
|
||||||
|
.use(staticFiles())
|
||||||
|
.get("/", () => new Response("hello"))
|
||||||
|
.get("/about", (ctx) => ctx.render(<h1>About me</h1>));
|
||||||
|
|
||||||
|
// Start server
|
||||||
|
app.listen();
|
||||||
|
```
|
||||||
|
|
||||||
|
## `.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);
|
||||||
|
```
|
||||||
|
|
||||||
|
## `.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}`);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## `.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`);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## `.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`);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## `.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`);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## `.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 });
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## `.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");
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## `.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 });
|
||||||
|
```
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
---
|
||||||
|
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: ${String(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");
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## `.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
|
||||||
|
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",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
```
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
---
|
||||||
|
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.
|
||||||
|
---
|
||||||
|
|
||||||
|
Fresh ships with the `fsRoutes` helper which automatically adds routes based on
|
||||||
|
the structure in the `routes/` folder in your project. When you add a new file
|
||||||
|
there, it will register a new route automatically.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { App, fsRoutes, staticFiles } from "fresh";
|
||||||
|
|
||||||
|
const app = new App({ root: import.meta.url })
|
||||||
|
.use(staticFiles());
|
||||||
|
|
||||||
|
await fsRoutes(app, {
|
||||||
|
loadIsland: (path) => import(`./islands/${path}`),
|
||||||
|
loadRoute: (path) => import(`./routes/${path}`),
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
> [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:
|
||||||
|
|
||||||
|
```sh Project structure
|
||||||
|
└── 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
|
||||||
|
/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 Project structure
|
||||||
|
└── 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 Project structure
|
||||||
|
└── 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 Project structure
|
||||||
|
> └── 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
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
---
|
||||||
|
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
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
---
|
||||||
|
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
|
||||||
|
import MyIsland from "../islands/my-island.tsx";
|
||||||
|
|
||||||
|
const app = new App()
|
||||||
|
.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`, and `null`
|
||||||
|
- `Infinity`, `-Infinity`, and `NaN`
|
||||||
|
- `Uint8Array`
|
||||||
|
- `Date`
|
||||||
|
- `RegExp`
|
||||||
|
- `JSX` Elements
|
||||||
|
- 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
|
||||||
|
> // WRONG
|
||||||
|
> <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 MyIsland from "../islands/my-island.tsx";
|
||||||
|
|
||||||
|
const app = new App()
|
||||||
|
.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 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>;
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
---
|
||||||
|
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 Project structure
|
||||||
|
└── 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
|
||||||
|
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 Project structure
|
||||||
|
└── 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,88 @@
|
|||||||
|
---
|
||||||
|
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
|
||||||
|
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
|
||||||
|
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
|
||||||
|
- [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 middleware1 = define.middleware(async (ctx) => {
|
||||||
|
console.log("B");
|
||||||
|
return await ctx.next();
|
||||||
|
});
|
||||||
|
|
||||||
|
export default [middleware1, middleware2];
|
||||||
|
```
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
---
|
||||||
|
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
|
||||||
|
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.
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
---
|
||||||
|
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
|
||||||
|
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.
|
||||||
|
|
||||||
|
```jsx
|
||||||
|
// Caching headers will be automatically added
|
||||||
|
<img src="/user.png" />;
|
||||||
|
```
|
||||||
|
|
||||||
|
You can always opt out of this behaviour per tag, by adding the
|
||||||
|
`data-fresh-disable-lock` attribute.
|
||||||
|
|
||||||
|
```jsx
|
||||||
|
// Opt-out of automatic caching headers
|
||||||
|
<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.
|
||||||
|
|
||||||
|
```jsx
|
||||||
|
import { asset } from "fresh/runtime";
|
||||||
|
|
||||||
|
// Adding caching headers manually
|
||||||
|
<a href={asset("/brochure.pdf")}>View brochure</a>;
|
||||||
|
```
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
---
|
||||||
|
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.
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
---
|
||||||
|
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: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](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)
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
---
|
||||||
|
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`.
|
||||||
|
>
|
||||||
|
> ```sh .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 run -A main.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
Fresh will automatically pick up the optimized assets in the `_fresh` directory.
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
---
|
||||||
|
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:
|
||||||
|
|
||||||
|
```sh Project structure
|
||||||
|
<project dir>
|
||||||
|
├── 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
|
||||||
|
│ └── ...
|
||||||
|
│
|
||||||
|
├── deno.json # Contains dependencies, tasks, etc
|
||||||
|
├── dev.ts # Run this during development
|
||||||
|
└── main.ts # Run this for production
|
||||||
|
```
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
TODO IMAGE
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
|
||||||
|
TODO: IMAGE
|
||||||
|
|
||||||
|
## 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
|
||||||
|
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:
|
||||||
|
|
||||||
|
TODO: IMAGE
|
||||||
|
|
||||||
|
## Next steps
|
||||||
|
|
||||||
|
TODO
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
---
|
||||||
|
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
|
||||||
|
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
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
---
|
||||||
|
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
|
||||||
|
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
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
---
|
||||||
|
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
|
||||||
|
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
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
---
|
||||||
|
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
|
||||||
|
import { trailingSlashes } from "fresh";
|
||||||
|
|
||||||
|
const app = new App()
|
||||||
|
.use(trailingSlashes("never"))
|
||||||
|
.get("/", () => new Response("hello"));
|
||||||
|
```
|
||||||
|
|
||||||
|
Always append a trailing slash:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { trailingSlashes } from "fresh";
|
||||||
|
|
||||||
|
const app = new App()
|
||||||
|
.use(trailingSlashes("always"))
|
||||||
|
.get("/", () => new Response("hello"));
|
||||||
|
```
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
---
|
||||||
|
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
|
||||||
|
import { expect } from "@std/expect";
|
||||||
|
import { App } from "fresh";
|
||||||
|
|
||||||
|
const middleware = define.middleware((ctx) => {
|
||||||
|
ctx.state.text = "middleware text";
|
||||||
|
return await 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
|
||||||
|
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
|
||||||
|
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");
|
||||||
|
});
|
||||||
|
```
|
||||||
+44
-46
@@ -18,54 +18,61 @@ const toc: RawTableOfContents = {
|
|||||||
canary: {
|
canary: {
|
||||||
label: "canary",
|
label: "canary",
|
||||||
content: {
|
content: {
|
||||||
"the-canary-version": {
|
|
||||||
title: "The canary version",
|
|
||||||
},
|
|
||||||
introduction: {
|
introduction: {
|
||||||
title: "Introduction",
|
title: "Introduction",
|
||||||
link: "latest",
|
link: "canary",
|
||||||
},
|
},
|
||||||
"getting-started": {
|
"getting-started": {
|
||||||
title: "Getting Started",
|
title: "Getting Started",
|
||||||
link: "latest",
|
link: "canary",
|
||||||
pages: [
|
|
||||||
["create-a-project", "Create a project", "link:latest"],
|
|
||||||
["running-locally", "Running locally", "link:latest"],
|
|
||||||
["create-a-route", "Create a route", "link:latest"],
|
|
||||||
["dynamic-routes", "Dynamic routes", "link:latest"],
|
|
||||||
["custom-handlers", "Custom handlers", "link:latest"],
|
|
||||||
["form-submissions", "Form submissions", "link:latest"],
|
|
||||||
["adding-interactivity", "Adding interactivity", "link:latest"],
|
|
||||||
["deploy-to-production", "Deploy to production", "link:latest"],
|
|
||||||
],
|
|
||||||
},
|
},
|
||||||
concepts: {
|
concepts: {
|
||||||
title: "Concepts",
|
title: "Concepts",
|
||||||
link: "latest",
|
link: "canary",
|
||||||
pages: [
|
pages: [
|
||||||
["architecture", "Architecture", "link:latest"],
|
["app", "App", "link:canary"],
|
||||||
["server-components", "Server Components", "link:latest"],
|
["middleware", "Middlewares", "link:canary"],
|
||||||
["routing", "Routing", "link:latest"],
|
["context", "Context", "link:canary"],
|
||||||
["routes", "Routes", "link:latest"],
|
|
||||||
["app-wrapper", "App wrapper", "link:latest"],
|
["routing", "Routing", "link:canary"],
|
||||||
["layouts", "Layouts", "link:latest"],
|
|
||||||
["forms", "Forms", "link:latest"],
|
["islands", "Islands", "link:canary"],
|
||||||
["islands", "Interactive islands", "link:latest"],
|
["static-files", "Static files", "link:canary"],
|
||||||
["static-files", "Static files", "link:latest"],
|
|
||||||
["middleware", "Middlewares", "link:latest"],
|
["file-routing", "File routing", "link:canary"],
|
||||||
["error-pages", "Error pages", "link:latest"],
|
|
||||||
["partials", "Partials", "link:latest"],
|
|
||||||
["data-fetching", "Data fetching", "link:latest"],
|
|
||||||
["ahead-of-time-builds", "Ahead-of-time Builds", "link:latest"],
|
|
||||||
["deployment", "Deployment", "link:latest"],
|
|
||||||
["plugins", "Plugins", "link:latest"],
|
|
||||||
["updating", "Updating Fresh", "link:latest"],
|
|
||||||
["server-configuration", "Server configuration", "link:latest"],
|
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
integrations: {
|
advanced: {
|
||||||
title: "Integrations",
|
title: "Advanced",
|
||||||
link: "latest",
|
link: "canary",
|
||||||
|
pages: [
|
||||||
|
["app-wrapper", "App wrapper", "link:canary"],
|
||||||
|
["layouts", "Layouts", "link:canary"],
|
||||||
|
["error-handling", "Error handling", "link:canary"],
|
||||||
|
["partials", "Partials", "link:canary"],
|
||||||
|
["forms", "Forms", "link:canary"],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
deployment: {
|
||||||
|
title: "Deployment",
|
||||||
|
link: "canary",
|
||||||
|
pages: [
|
||||||
|
["production", "Production builds", "link:canary"],
|
||||||
|
["deno-deploy", "Deno Deploy", "link:canary"],
|
||||||
|
["docker", "Docker", "link:canary"],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
testing: {
|
||||||
|
title: "Testing",
|
||||||
|
link: "canary",
|
||||||
|
},
|
||||||
|
plugins: {
|
||||||
|
title: "Plugins",
|
||||||
|
link: "canary",
|
||||||
|
pages: [
|
||||||
|
["cors", "cors", "link:canary"],
|
||||||
|
["trailing-slashes", "trailingSlashes", "link:canary"],
|
||||||
|
],
|
||||||
},
|
},
|
||||||
examples: {
|
examples: {
|
||||||
title: "Examples",
|
title: "Examples",
|
||||||
@@ -73,16 +80,7 @@ const toc: RawTableOfContents = {
|
|||||||
pages: [
|
pages: [
|
||||||
["migration-guide", "Migration Guide", "link:canary"],
|
["migration-guide", "Migration Guide", "link:canary"],
|
||||||
["modifying-the-head", "Modifying the <head>", "link:latest"],
|
["modifying-the-head", "Modifying the <head>", "link:latest"],
|
||||||
["writing-tests", "Writing tests", "link:latest"],
|
|
||||||
[
|
|
||||||
"changing-the-src-dir",
|
|
||||||
"Changing the source directory",
|
|
||||||
"link:latest",
|
|
||||||
],
|
|
||||||
["init-the-server", "Initializing the server", "link:latest"],
|
|
||||||
["dealing-with-cors", "Dealing with CORS", "link:latest"],
|
|
||||||
["creating-a-crud-api", "Creating a CRUD API", "link:latest"],
|
["creating-a-crud-api", "Creating a CRUD API", "link:latest"],
|
||||||
["handling-complex-routes", "Handling complex routes", "link:latest"],
|
|
||||||
["rendering-markdown", "Rendering markdown", "link:latest"],
|
["rendering-markdown", "Rendering markdown", "link:latest"],
|
||||||
["rendering-raw-html", "Rendering raw HTML", "link:latest"],
|
["rendering-raw-html", "Rendering raw HTML", "link:latest"],
|
||||||
[
|
[
|
||||||
|
|||||||
+38
@@ -166,6 +166,10 @@ export let getBuildCache: (app: App<any>) => BuildCache | null;
|
|||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
export let setBuildCache: (app: App<any>, cache: BuildCache | null) => void;
|
export let setBuildCache: (app: App<any>, cache: BuildCache | null) => void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create an application instance that passes the incoming `Request`
|
||||||
|
* instance through middlewares and routes.
|
||||||
|
*/
|
||||||
export class App<State> {
|
export class App<State> {
|
||||||
#router: Router<MiddlewareFn<State>> = new UrlPatternRouter<
|
#router: Router<MiddlewareFn<State>> = new UrlPatternRouter<
|
||||||
MiddlewareFn<State>
|
MiddlewareFn<State>
|
||||||
@@ -221,6 +225,9 @@ export class App<State> {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add one or more middlewares at the top or the specified path.
|
||||||
|
*/
|
||||||
use(...middleware: MiddlewareFn<State>[]): this;
|
use(...middleware: MiddlewareFn<State>[]): this;
|
||||||
use(path: string, ...middleware: MiddlewareFn<State>[]): this;
|
use(path: string, ...middleware: MiddlewareFn<State>[]): this;
|
||||||
use(
|
use(
|
||||||
@@ -244,6 +251,9 @@ export class App<State> {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the app's 404 error handler. Can be a {@linkcode Route} or a {@linkcode MiddlewareFn}.
|
||||||
|
*/
|
||||||
notFound(routeOrMiddleware: Route<State> | MiddlewareFn<State>): this {
|
notFound(routeOrMiddleware: Route<State> | MiddlewareFn<State>): this {
|
||||||
const route = typeof routeOrMiddleware === "function"
|
const route = typeof routeOrMiddleware === "function"
|
||||||
? { handler: routeOrMiddleware }
|
? { handler: routeOrMiddleware }
|
||||||
@@ -304,31 +314,52 @@ export class App<State> {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add middlewares for GET requests at the specified path.
|
||||||
|
*/
|
||||||
get(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
get(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
||||||
this.#addMiddleware("GET", path, middlewares);
|
this.#addMiddleware("GET", path, middlewares);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* Add middlewares for POST requests at the specified path.
|
||||||
|
*/
|
||||||
post(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
post(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
||||||
this.#addMiddleware("POST", path, middlewares);
|
this.#addMiddleware("POST", path, middlewares);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* Add middlewares for PATCH requests at the specified path.
|
||||||
|
*/
|
||||||
patch(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
patch(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
||||||
this.#addMiddleware("PATCH", path, middlewares);
|
this.#addMiddleware("PATCH", path, middlewares);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* Add middlewares for PUT requests at the specified path.
|
||||||
|
*/
|
||||||
put(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
put(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
||||||
this.#addMiddleware("PUT", path, middlewares);
|
this.#addMiddleware("PUT", path, middlewares);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* Add middlewares for DELETE requests at the specified path.
|
||||||
|
*/
|
||||||
delete(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
delete(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
||||||
this.#addMiddleware("DELETE", path, middlewares);
|
this.#addMiddleware("DELETE", path, middlewares);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* Add middlewares for HEAD requests at the specified path.
|
||||||
|
*/
|
||||||
head(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
head(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
||||||
this.#addMiddleware("HEAD", path, middlewares);
|
this.#addMiddleware("HEAD", path, middlewares);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add middlewares for all HTTP verbs at the specified path.
|
||||||
|
*/
|
||||||
all(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
all(path: string, ...middlewares: MiddlewareFn<State>[]): this {
|
||||||
this.#addMiddleware("ALL", path, middlewares);
|
this.#addMiddleware("ALL", path, middlewares);
|
||||||
return this;
|
return this;
|
||||||
@@ -356,6 +387,10 @@ export class App<State> {
|
|||||||
this.#routeDefs.push({ method, pattern: path, fns });
|
this.#routeDefs.push({ method, pattern: path, fns });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Merge another {@linkcode App} instance into this app at the
|
||||||
|
* specified path.
|
||||||
|
*/
|
||||||
mountApp(path: string, app: App<State>): this {
|
mountApp(path: string, app: App<State>): this {
|
||||||
const segmentPath = mergePath("", path);
|
const segmentPath = mergePath("", path);
|
||||||
const segment = getOrCreateSegment(this.#root, segmentPath, true);
|
const segment = getOrCreateSegment(this.#root, segmentPath, true);
|
||||||
@@ -484,6 +519,9 @@ export class App<State> {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Spawn a server for this app.
|
||||||
|
*/
|
||||||
async listen(options: ListenOptions = {}): Promise<void> {
|
async listen(options: ListenOptions = {}): Promise<void> {
|
||||||
if (!options.onListen) {
|
if (!options.onListen) {
|
||||||
options.onListen = createOnListen(this.config.basePath, options);
|
options.onListen = createOnListen(this.config.basePath, options);
|
||||||
|
|||||||
@@ -43,6 +43,10 @@ export interface ResolvedFreshConfig {
|
|||||||
build: {
|
build: {
|
||||||
outDir: string;
|
outDir: string;
|
||||||
};
|
};
|
||||||
|
/**
|
||||||
|
* Serve fresh from a base path instead of from the root.
|
||||||
|
* "/foo/bar" -> http://localhost:8000/foo/bar
|
||||||
|
*/
|
||||||
basePath: string;
|
basePath: string;
|
||||||
staticDir: string;
|
staticDir: string;
|
||||||
/**
|
/**
|
||||||
|
|||||||
+10
-1
@@ -62,11 +62,14 @@ export class Context<State> {
|
|||||||
* certain search parameters are set.
|
* certain search parameters are set.
|
||||||
*/
|
*/
|
||||||
readonly url: URL;
|
readonly url: URL;
|
||||||
/** The original incoming `Request` object` */
|
/** The original incoming {@linkcode Request} object. */
|
||||||
readonly req: Request;
|
readonly req: Request;
|
||||||
|
/** The url parameters of the matched route pattern. */
|
||||||
readonly params: Record<string, string>;
|
readonly params: Record<string, string>;
|
||||||
|
/** State object that is shared with all middlewares. */
|
||||||
readonly state: State = {} as State;
|
readonly state: State = {} as State;
|
||||||
data: unknown = undefined;
|
data: unknown = undefined;
|
||||||
|
/** Error value if an error was caught (Default: null) */
|
||||||
error: unknown | null = null;
|
error: unknown | null = null;
|
||||||
readonly info: Deno.ServeHandlerInfo | Deno.ServeHandlerInfo;
|
readonly info: Deno.ServeHandlerInfo | Deno.ServeHandlerInfo;
|
||||||
/**
|
/**
|
||||||
@@ -174,6 +177,12 @@ export class Context<State> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render JSX and return an HTML `Response` instance.
|
||||||
|
* ```tsx
|
||||||
|
* ctx.render(<h1>hello world</h1>);
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
async render(
|
async render(
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
vnode: VNode<any> | null,
|
vnode: VNode<any> | null,
|
||||||
|
|||||||
+21
-14
@@ -1,33 +1,40 @@
|
|||||||
import type { FreshContext } from "../context.ts";
|
import type { Context } from "../context.ts";
|
||||||
import type { MiddlewareFn } from "./mod.ts";
|
import type { MiddlewareFn } from "./mod.ts";
|
||||||
|
|
||||||
export type CORSOptions<State> = {
|
export type CORSOptions<State> = {
|
||||||
|
/**
|
||||||
|
* The value of [`Access-Control-Allow-Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Allow-Origin) CORS header
|
||||||
|
*/
|
||||||
origin:
|
origin:
|
||||||
| string
|
| string
|
||||||
| string[]
|
| string[]
|
||||||
| ((
|
| ((origin: string, ctx: Context<State>) => string | undefined | null);
|
||||||
requestOrigin: string,
|
/**
|
||||||
ctx: FreshContext<State>,
|
* Sets the permitted methods for the [`Access-Control-Allow-Methods`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Allow-Methods) CORS header.
|
||||||
) => string | undefined | null);
|
*/
|
||||||
allowMethods?: string[];
|
allowMethods?: string[];
|
||||||
|
/**
|
||||||
|
* Indicate the HTTP headers that can be used during the actual request. Sets the [`Access-Control-Allow-Headers`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Allow-Headers) header
|
||||||
|
*/
|
||||||
allowHeaders?: string[];
|
allowHeaders?: string[];
|
||||||
|
/**
|
||||||
|
* The value of [`Access-Control-Max-Age`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Max-Age) CORS header
|
||||||
|
*/
|
||||||
maxAge?: number;
|
maxAge?: number;
|
||||||
|
/**
|
||||||
|
* The value of [`Access-Control-Allow-Credentials`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Allow-Credentials) CORS header
|
||||||
|
*/
|
||||||
credentials?: boolean;
|
credentials?: boolean;
|
||||||
|
/**
|
||||||
|
* The value of [`Access-Control-Expose-Headers`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Expose-Headers) CORS header
|
||||||
|
*/
|
||||||
exposeHeaders?: string[];
|
exposeHeaders?: string[];
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* CORS Middleware for Fresh.
|
* CORS Middleware to set [`Cross-Origin-Resource-Sharing`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) headers.
|
||||||
* Adapted from Hono's CORS middleware.
|
|
||||||
* Would like to express my gratitude to all the developers of Hono.
|
|
||||||
*
|
*
|
||||||
* @param {CORSOptions} [options] - The options for the CORS middleware.
|
* @param {CORSOptions} [options] - The options for the CORS middleware.
|
||||||
* @param {string | string[] | ((requestOrigin: string, ctx: FreshContext) => string | undefined | null)} [options.origin='*'] - The value of "Access-Control-Allow-Origin" CORS header.
|
|
||||||
* @param {string[]} [options.allowMethods=['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH']] - The value of "Access-Control-Allow-Methods" CORS header.
|
|
||||||
* @param {string[]} [options.allowHeaders=[]] - The value of "Access-Control-Allow-Headers" CORS header.
|
|
||||||
* @param {number} [options.maxAge] - The value of "Access-Control-Max-Age" CORS header.
|
|
||||||
* @param {boolean} [options.credentials] - The value of "Access-Control-Allow-Credentials" CORS header.
|
|
||||||
* @param {string[]} [options.exposeHeaders=[]] - The value of "Access-Control-Expose-Headers" CORS header.
|
|
||||||
* @returns {(req: Request, ctx: FreshContext) => Promise<Response>} The Fresh middleware handler function.
|
* @returns {(req: Request, ctx: FreshContext) => Promise<Response>} The Fresh middleware handler function.
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
|
|||||||
+16
-1
@@ -6,6 +6,7 @@ import "prismjs/components/prism-diff.js";
|
|||||||
import "prismjs/components/prism-json.js";
|
import "prismjs/components/prism-json.js";
|
||||||
import "prismjs/components/prism-bash.js";
|
import "prismjs/components/prism-bash.js";
|
||||||
import "prismjs/components/prism-yaml.js";
|
import "prismjs/components/prism-yaml.js";
|
||||||
|
import denoJson from "../../deno.json" with { type: "json" };
|
||||||
|
|
||||||
export { extractYaml as frontMatter } from "@std/front-matter";
|
export { extractYaml as frontMatter } from "@std/front-matter";
|
||||||
|
|
||||||
@@ -55,7 +56,15 @@ class DefaultRenderer extends Marked.Renderer {
|
|||||||
depth,
|
depth,
|
||||||
raw,
|
raw,
|
||||||
}: Marked.Tokens.Heading): string {
|
}: Marked.Tokens.Heading): string {
|
||||||
const slug = slugger.slug(raw);
|
let slugInput = tokens.length === 1 && tokens[0].type === "codespan"
|
||||||
|
? tokens[0].text
|
||||||
|
: raw;
|
||||||
|
|
||||||
|
if (/^\..*\(\)$/.test(slugInput)) {
|
||||||
|
slugInput = slugInput.slice(1, -2);
|
||||||
|
}
|
||||||
|
|
||||||
|
const slug = slugger.slug(slugInput);
|
||||||
const text = this.parser.parseInline(tokens);
|
const text = this.parser.parseInline(tokens);
|
||||||
this.headings.push({ id: slug, html: text });
|
this.headings.push({ id: slug, html: text });
|
||||||
return `<h${depth} id="${slug}"><a class="md-anchor" tabindex="-1" href="#${slug}">${text}<span aria-hidden="true">#</span></a></h${depth}>`;
|
return `<h${depth} id="${slug}"><a class="md-anchor" tabindex="-1" href="#${slug}">${text}<span aria-hidden="true">#</span></a></h${depth}>`;
|
||||||
@@ -76,6 +85,12 @@ class DefaultRenderer extends Marked.Renderer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override code({ lang: info, text }: Marked.Tokens.Code): string {
|
override code({ lang: info, text }: Marked.Tokens.Code): string {
|
||||||
|
// For canary only
|
||||||
|
text = text.replaceAll(
|
||||||
|
/(@fresh\/init)/g,
|
||||||
|
`@fresh/init@${denoJson.version}`,
|
||||||
|
);
|
||||||
|
|
||||||
// format: tsx
|
// format: tsx
|
||||||
// format: tsx my/file.ts
|
// format: tsx my/file.ts
|
||||||
// format: tsx "This is my title"
|
// format: tsx "This is my title"
|
||||||
|
|||||||
Reference in New Issue
Block a user