www: move latest docs into latest folder (#1522)
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
---
|
||||
description: |
|
||||
Add a global application wrapper to provide common meta tags or context for application routes.
|
||||
---
|
||||
|
||||
An application wrapper is defined in an `_app.tsx` file in `routes/` folder. It
|
||||
must contain a default export that is a regular Preact component. Only one such
|
||||
wrapper is allowed per application.
|
||||
|
||||
The component to be wrapped is received via props, in addition to a few other
|
||||
things. This allows for the introduction of a global container functioning as a
|
||||
template which can be conditioned based on state and params. Note that any state
|
||||
set by middleware is available via `props.state`.
|
||||
|
||||
```tsx
|
||||
// routes/_app.tsx
|
||||
|
||||
import { AppProps } from "$fresh/server.ts";
|
||||
|
||||
export default function App({ Component, state }: AppProps) {
|
||||
//do something with state here
|
||||
return (
|
||||
<div class="wrapper">
|
||||
<Component />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
description: |
|
||||
Fresh's architecture is designed to make it easy to build fast, scalable, and reliable applications.
|
||||
---
|
||||
|
||||
Fresh is designed to make it easy to build fast, scalable, and reliable
|
||||
applications. To do this, it makes opinionated decisions about how one should
|
||||
build web applications. These decisions are backed by strong empirical data
|
||||
gathered from experts in the field. Some examples of these principles are:
|
||||
|
||||
- Page load times should be reduced to a minimum.
|
||||
- The work performed on the client should be minimized.
|
||||
- Errors should have a small blast radius - stuff should gracefully degrade.
|
||||
|
||||
The single biggest architecture decision that Fresh makes is its usage of the
|
||||
[islands architecture][islands] pattern. This means that Fresh applications ship
|
||||
pure HTML to the client by default. Parts of a server-rendered page can then be
|
||||
independently re-hydrated with interactive widgets (islands). This means that
|
||||
the client is only responsible for rendering parts of the page that are
|
||||
interactive enough to warrant the extra effort. Any content that is purely
|
||||
static does not have related client-side JavaScript and is thus very
|
||||
lightweight.
|
||||
|
||||
<!-- TODO(lucacasonato): elaborate on request handling, form actions, etc. -->
|
||||
|
||||
[islands]: https://www.patterns.dev/posts/islands-architecture/
|
||||
@@ -0,0 +1,42 @@
|
||||
---
|
||||
description: |
|
||||
Data fetching in Fresh happens inside of route handler functions. These can pass route data to the page via page props.
|
||||
---
|
||||
|
||||
Server side data fetching in Fresh is accomplished through asynchronous handler
|
||||
functions. These handler functions can call a `ctx.render()` function with the
|
||||
data to be rendered as an argument. This data can then be retrieved by the page
|
||||
component through the `data` property on the `props`.
|
||||
|
||||
Here is an example:
|
||||
|
||||
```tsx
|
||||
interface Project {
|
||||
name: string;
|
||||
stars: number;
|
||||
}
|
||||
|
||||
export const handler: Handlers<Project> = {
|
||||
async GET(_req, ctx) {
|
||||
const project = await db.projects.findOne({ id: ctx.params.id });
|
||||
if (!project) {
|
||||
return new Response("Project not found", { status: 404 });
|
||||
}
|
||||
return ctx.render(project);
|
||||
},
|
||||
};
|
||||
|
||||
export default function ProjectPage(props: PageProps<Project>) {
|
||||
return (
|
||||
<div>
|
||||
<h1>{props.data.name}</h1>
|
||||
<p>{props.data.stars} stars</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The type parameter on the `PageProps`, `Handlers`, `Handler`, and
|
||||
`HandlerContext` can be used to enforce a TypeScript type to use for the render
|
||||
data. Fresh enforces during type checking that the types in all of these fields
|
||||
are compatible within a single page.
|
||||
@@ -0,0 +1,75 @@
|
||||
---
|
||||
description: |
|
||||
Fresh can be deployed to a variety of platforms easily.
|
||||
---
|
||||
|
||||
While Fresh is designed to be deployed to [Deno Deploy][deno-deploy], it can be
|
||||
deployed to any system or platform that can run a Deno based web server.
|
||||
|
||||
Here are instructions for specific providers / systems:
|
||||
|
||||
- [Deno Deploy](#deno-deploy)
|
||||
- [Docker](#docker)
|
||||
|
||||
## Deno Deploy
|
||||
|
||||
The recommended way to deploy Fresh is by using Deno Deploy. Deno Deploy
|
||||
provides a GitHub integration that can deploy your Fresh projects to its
|
||||
globally distributed edge network in seconds, automatically.
|
||||
|
||||
View [the getting started guide][deploy-to-production] for instructions on how
|
||||
to deploy Fresh to Deno Deploy.
|
||||
|
||||
## Docker
|
||||
|
||||
You can deploy Fresh to any platform that can run Docker containers. Docker is a
|
||||
tool to containerize projects and portably run them on any supported platform.
|
||||
|
||||
When packaging your Fresh app for Docker, it is important that you set the
|
||||
`DENO_DEPLOYMENT_ID` environment variable in your container. This variable needs
|
||||
to be set to an opaque string ID that represents the version of your application
|
||||
that is currently being run. This could be a Git commit hash, or a hash of all
|
||||
files in your project. It is critical for the function of Fresh that this ID
|
||||
changes when _any_ file in your project changes - if it doesn't, incorrect
|
||||
caching **will** cause your project to not function correctly.
|
||||
|
||||
Here is an example `Dockerfile` for a Fresh project:
|
||||
|
||||
```dockerfile
|
||||
FROM denoland/deno:1.35.0
|
||||
|
||||
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
|
||||
$ docker build --build-arg GIT_REVISION=$(git rev-parse HEAD) -t my-fresh-app .
|
||||
```
|
||||
|
||||
Then run your Docker container:
|
||||
|
||||
```sh
|
||||
$ docker run -t -i -p 80:8000 my-fresh-app
|
||||
```
|
||||
|
||||
To deploy to a cloud provider, push it to a container registry and follow their
|
||||
documentation.
|
||||
|
||||
- [Amazon Web Services][aws-container-registry]
|
||||
- [Google Cloud][gcp-container-registry]
|
||||
|
||||
[aws-container-registry]: https://docs.aws.amazon.com/AmazonECS/latest/userguide/create-container-image.html#create-container-image-push-ecr
|
||||
[gcp-container-registry]: https://cloud.google.com/container-registry/docs/pushing-and-pulling
|
||||
[deno-deploy]: https://deno.com/deploy
|
||||
[deploy-to-production]: /docs/getting-started/deploy-to-production
|
||||
@@ -0,0 +1,69 @@
|
||||
---
|
||||
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 `UnknownPageProps` is passed in as an argument.
|
||||
|
||||
```tsx
|
||||
import { UnknownPageProps } from "$fresh/server.ts";
|
||||
|
||||
export default function NotFoundPage({ url }: UnknownPageProps) {
|
||||
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
|
||||
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>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 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 `ErrorPageProps` is passed in as an argument.
|
||||
|
||||
```tsx
|
||||
import { ErrorPageProps } from "$fresh/server.ts";
|
||||
|
||||
export default function Error500Page({ error }: ErrorPageProps) {
|
||||
return <p>500 internal error: {(error as Error).message}</p>;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,59 @@
|
||||
---
|
||||
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 `multipart/form-data`
|
||||
|
||||
Forms can either submit as a `GET` request with URL search parameter encoding,
|
||||
or as a `POST` request with `multipart/form-data`.
|
||||
|
||||
This example demonstrates how to handle `multipart/form-data` `<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 access a specific `email` value from a
|
||||
`formData()`, add the email to a list, and redirect the user to a thank you
|
||||
page.
|
||||
@@ -0,0 +1,8 @@
|
||||
---
|
||||
description: |
|
||||
This chapter goes over some fundamental concepts of Fresh.
|
||||
---
|
||||
|
||||
This chapter goes over some fundamental concepts of Fresh. It covers the
|
||||
overarching architecture design of Fresh applications, as well as reference
|
||||
documentation about the various features of Fresh.
|
||||
@@ -0,0 +1,117 @@
|
||||
---
|
||||
description: |
|
||||
Islands enable client side interactivity in Fresh. They are hydrated on the client in addition to being rendered on the server.
|
||||
---
|
||||
|
||||
Islands enable client side interactivity in Fresh. Islands are isolated Preact
|
||||
components that are rendered on the client. This is different from all other
|
||||
components in Fresh, as they are usually just rendered on the server.
|
||||
|
||||
Islands are defined by creating a file in the `islands/` folder in a Fresh
|
||||
project. The name of this file must be a PascalCase or kebab-case name of the
|
||||
island.
|
||||
|
||||
```tsx
|
||||
// islands/MyIsland.tsx
|
||||
|
||||
import { useSignal } from "@preact/signals";
|
||||
|
||||
export default function MyIsland() {
|
||||
const count = useSignal(0);
|
||||
|
||||
return (
|
||||
<div>
|
||||
Counter is at {count}.{" "}
|
||||
<button onClick={() => (count.value += 1)}>+</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
An island can be used in a page like a regular Preact component. Fresh will take
|
||||
care of automatically re-hydrating the island on the client.
|
||||
|
||||
Passing props to islands is supported, but only if the props are serializable.
|
||||
Fresh can serialize the following types of values:
|
||||
|
||||
- Primitive types `string`, `boolean`, `bigint`, and `null`
|
||||
- Most `number`s (`Infinity`, `-Infinity`, and `NaN` are silently converted to
|
||||
`null`)
|
||||
- Plain objects with string keys and serializable values
|
||||
- Arrays containing serializable values
|
||||
- Uint8Array
|
||||
- JSX Elements (restricted to `props.children`)
|
||||
- Preact Signals (if the inner value is serializable)
|
||||
|
||||
Circular references are supported. If an object or signal is referenced multiple
|
||||
times, it is only serialized once and the references are restored upon
|
||||
deserialization. Passing complex objects like `Date`, custom classes, or
|
||||
functions is not supported.
|
||||
|
||||
## Passing JSX to islands
|
||||
|
||||
Islands support passing JSX elements via the `children` property. This allows
|
||||
you to pass static content rendered by the server to an island in the browser.
|
||||
|
||||
```jsx
|
||||
// route/index.tsx
|
||||
import MyIsland from "../islands/my-island.tsx";
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<MyIsland>
|
||||
<p>This text is rendered on the server</p>
|
||||
</MyIsland>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
We can deduce which parts were rendered by the server and which parts where
|
||||
rendered by an island from the HTML alone. It contains all the information we
|
||||
need, which allows us to skip the work of having to send a serialized version of
|
||||
`props.children` to the browser.
|
||||
|
||||
### Nesting islands
|
||||
|
||||
Islands can be nested within other islands as well. In that scenario they act
|
||||
like a normal Preact component, but still receive the serialized props if any
|
||||
were present.
|
||||
|
||||
```jsx
|
||||
// route/index.tsx
|
||||
import MyIsland from "../islands/my-island.tsx";
|
||||
import OtherIsland from "../islands/other-island.tsx";
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<MyIsland>
|
||||
<OtherIsland foo="this prop will be serialized">
|
||||
<p>This text is rendered on the server</p>
|
||||
</OtherIsland>
|
||||
</MyIsland>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
In essence, Fresh allows you to mix static and interactive parts in your app in
|
||||
a way that's most optimal for your use app. We'll keep sending only the
|
||||
JavaScript that is needed for the islands to the browser.
|
||||
|
||||
```jsx
|
||||
// route/index.tsx
|
||||
import MyIsland from "../islands/my-island.tsx";
|
||||
import OtherIsland from "../islands/other-island.tsx";
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<MyIsland>
|
||||
<div>
|
||||
<h1>Rendered by server</h1>
|
||||
<OtherIsland>
|
||||
<p>also rendered by server</p>
|
||||
</OtherIsland>
|
||||
</div>
|
||||
</MyIsland>
|
||||
);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,199 @@
|
||||
---
|
||||
description: |
|
||||
Add middleware routes to intercept requests or responses for analytics purposes, access control, or anything else.
|
||||
---
|
||||
|
||||
A middleware is defined in a `_middleware.ts` file. It will intercept the
|
||||
request in order for you to perform custom logic before or after the route
|
||||
handler. This allows modifying or checking requests and responses. Common
|
||||
use-cases for this are logging, authentication, and performance monitoring.
|
||||
|
||||
Each middleware gets passed a `next` function in the context argument that is
|
||||
used to trigger child handlers. The `ctx` also has a `state` property that can
|
||||
be used to pass arbitrary data to downstream (or upstream) handlers. This
|
||||
`state` is included in `PageProps` by default, which is available to both the
|
||||
special [\_app](/docs/concepts/app-wrapper.md) wrapper and normal
|
||||
[routes](/docs/concepts/routes.md).
|
||||
|
||||
```ts
|
||||
// routes/_middleware.ts
|
||||
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||
|
||||
interface State {
|
||||
data: string;
|
||||
}
|
||||
|
||||
export async function handler(
|
||||
req: Request,
|
||||
ctx: MiddlewareHandlerContext<State>,
|
||||
) {
|
||||
ctx.state.data = "myData";
|
||||
const resp = await ctx.next();
|
||||
resp.headers.set("server", "fresh server");
|
||||
return resp;
|
||||
}
|
||||
```
|
||||
|
||||
```ts
|
||||
// routes/myHandler.ts
|
||||
export const handler: Handlers<any, { data: string }> = {
|
||||
GET(_req, ctx) {
|
||||
return new Response(`middleware data is ${ctx.state.data}`);
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
Middlewares are scoped and can be layered. This means a project can have
|
||||
multiple middlewares, each covering a different set of routes. If multiple
|
||||
middlewares cover a route, they will all be run, in order of specificity (least
|
||||
specific first).
|
||||
|
||||
For example, take a project with the following routes:
|
||||
|
||||
```
|
||||
└── routes
|
||||
├── _middleware.ts
|
||||
├── index.ts
|
||||
└── admin
|
||||
├── _middleware.ts
|
||||
└── index.ts
|
||||
└── signin.ts
|
||||
```
|
||||
|
||||
For a request to `/` the request will flow like this:
|
||||
|
||||
1. The `routes/_middleware.ts` middleware is invoked.
|
||||
2. Calling `ctx.next()` will invoke the `routes/index.ts` handler.
|
||||
|
||||
For a request to `/admin` the request flows like this:
|
||||
|
||||
1. The `routes/_middleware.ts` middleware is invoked.
|
||||
2. Calling `ctx.next()` will invoke the `routes/admin/_middleware.ts`
|
||||
middleware.
|
||||
3. Calling `ctx.next()` will invoke the `routes/admin/index.ts` handler.
|
||||
|
||||
For a request to `/admin/signin` the request flows like this:
|
||||
|
||||
1. The `routes/_middleware.ts` middleware is invoked.
|
||||
2. Calling `ctx.next()` will invoke the `routes/admin/_middleware.ts`
|
||||
middleware.
|
||||
3. Calling `ctx.next()` will invoke the `routes/admin/signin.ts` handler.
|
||||
|
||||
A single middleware file can also define multiple middlewares (all for the same
|
||||
route) by exporting an array of handlers instead of a single handler. For
|
||||
example:
|
||||
|
||||
```ts
|
||||
// routes/_middleware.ts
|
||||
|
||||
export const handler = [
|
||||
async function middleware1(req, ctx) {
|
||||
// do something
|
||||
return ctx.next();
|
||||
},
|
||||
async function middleware2(req, ctx) {
|
||||
// do something
|
||||
return ctx.next();
|
||||
},
|
||||
];
|
||||
```
|
||||
|
||||
It should be noted that `middleware` has access to route parameters. If you're
|
||||
running a fictitious `routes/[tenant]/admin/_middleware.ts` like this:
|
||||
|
||||
```ts
|
||||
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||
|
||||
export async function handler(_req: Request, ctx: MiddlewareHandlerContext) {
|
||||
const currentTenant = ctx.params.tenant;
|
||||
//do something with the tenant
|
||||
const resp = await ctx.next();
|
||||
return resp;
|
||||
}
|
||||
```
|
||||
|
||||
and the request is to `mysaas.com/acme/admin/`, then `currentTenant` will have
|
||||
the value of `acme` in your middleware.
|
||||
|
||||
## Middleware Destination
|
||||
|
||||
To set the stage for this section, `MiddlewareHandlerContext` looks like this:
|
||||
|
||||
```ts
|
||||
export interface MiddlewareHandlerContext<State = Record<string, unknown>> {
|
||||
next: () => Promise<Response>;
|
||||
state: State;
|
||||
destination: router.DestinationKind;
|
||||
remoteAddr: {
|
||||
transport: "tcp" | "udp";
|
||||
hostname: string;
|
||||
port: number;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
and `router.DestinationKind` is defined like this:
|
||||
|
||||
```ts
|
||||
export type DestinationKind = "internal" | "static" | "route" | "notFound";
|
||||
```
|
||||
|
||||
This is useful if you want your middleware to only run when a request is headed
|
||||
for a `route`, as opposed to something like `http://localhost:8001/favicon.ico`.
|
||||
|
||||
### Example
|
||||
|
||||
Initiate a new Fresh project (`deno run -A -r https://fresh.deno.dev/`) and then
|
||||
create a `_middleware.ts` file in the `routes` folder like this:
|
||||
|
||||
```ts
|
||||
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||
|
||||
export async function handler(req: Request, ctx: MiddlewareHandlerContext) {
|
||||
console.log(ctx.destination);
|
||||
console.log(req.url);
|
||||
const resp = await ctx.next();
|
||||
return resp;
|
||||
}
|
||||
```
|
||||
|
||||
If you start up your server (`deno task start`) you'll see the following:
|
||||
|
||||
```
|
||||
Task start deno run -A --watch=static/,routes/ dev.ts
|
||||
Watcher Process started.
|
||||
The manifest has been generated for 4 routes and 1 islands.
|
||||
|
||||
🍋 Fresh ready
|
||||
Local: http://localhost:8000/
|
||||
|
||||
route
|
||||
http://localhost:8000/
|
||||
internal
|
||||
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/deserializer.js
|
||||
internal
|
||||
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/signals.js
|
||||
internal
|
||||
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/plugin-twind-main.js
|
||||
internal
|
||||
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/main.js
|
||||
internal
|
||||
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/island-counter.js
|
||||
internal
|
||||
http://localhost:8000/_frsh/refresh.js
|
||||
static
|
||||
http://localhost:8000/logo.svg?__frsh_c=3c7400558fc00915df88cb181036c0dbf73ab7f5
|
||||
internal
|
||||
http://localhost:8000/_frsh/alive
|
||||
internal
|
||||
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/chunk-PDMKJVJ5.js
|
||||
internal
|
||||
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/chunk-UGFDDSOV.js
|
||||
internal
|
||||
http://localhost:8000/_frsh/js/3c7400558fc00915df88cb181036c0dbf73ab7f5/chunk-RCK7U3UF.js
|
||||
```
|
||||
|
||||
That first `route` request is for when `Fresh` responds with the root level
|
||||
`index.tsx` route. The rest, as you can see, are either `internal` or `static`
|
||||
requests. You can use `ctx.destination` to filter these out if your middleware
|
||||
is only supposed to deal with routes.
|
||||
@@ -0,0 +1,142 @@
|
||||
---
|
||||
description: Plugins can add new functionality to Fresh without requiring significant complexity.
|
||||
---
|
||||
|
||||
Plugins can dynamically add new functionality to Fresh without exposing
|
||||
significant complexity to the user. Users can add plugins by importing and
|
||||
initializing them in their `main.ts` file:
|
||||
|
||||
```ts
|
||||
// main.ts
|
||||
|
||||
import { start } from "$fresh/server.ts";
|
||||
import manifest from "./fresh.gen.ts";
|
||||
|
||||
import twindPlugin from "$fresh/plugins/twind.ts";
|
||||
import twindConfig from "./twind.config.js";
|
||||
|
||||
await start(manifest, {
|
||||
plugins: [
|
||||
// This line configures Fresh to use the first-party twind plugin.
|
||||
twindPlugin(twindConfig),
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Currently, the only available first-party plugin is the Twind plugin.
|
||||
Third-party plugins are also supported - they can be imported from any HTTP
|
||||
server, like any other Deno module.
|
||||
|
||||
Plugin hooks are executed in the order that the plugins are defined in the
|
||||
`plugins` array. This means that the first plugin in the array will be executed
|
||||
first, and the last plugin in the array will be executed last. For many plugins,
|
||||
this does not matter, but for some plugins it may.
|
||||
|
||||
## Creating a plugin
|
||||
|
||||
Fresh plugins are in essence a collection of hooks that allow the plugin to hook
|
||||
into various systems inside of Fresh. Currently only a `render` hook is
|
||||
available (explained below).
|
||||
|
||||
A Fresh plugin is just a JavaScript object that conforms to the
|
||||
[Plugin](https://deno.land/x/fresh/server.ts?s=Plugin) interface. The only
|
||||
required property of a plugin is its name. Names must only contain the
|
||||
characters `a`-`z`, and `_`.
|
||||
|
||||
```ts
|
||||
import { Plugin } from "$fresh/server.ts";
|
||||
|
||||
const plugin: Plugin = {
|
||||
name: "my_plugin",
|
||||
};
|
||||
```
|
||||
|
||||
A plugin containing only a name is technically valid, but not very useful. To be
|
||||
able to do anything with a plugin, it must register some hooks, middlewares, or
|
||||
routes.
|
||||
|
||||
### Hook: `render`
|
||||
|
||||
The render hook allows plugins to:
|
||||
|
||||
- Control timing of the synchronous render of a page.
|
||||
- Inject additional CSS and JS into the rendered page.
|
||||
|
||||
This is commonly used to set thread local variables for the duration of the
|
||||
render (for example preact global context, preact option hooks, or for style
|
||||
libraries like Twind). After render is complete, the plugin can inject inline
|
||||
CSS and JS modules (with attached state) into the page.
|
||||
|
||||
The render hook is called with the
|
||||
[`PluginRenderContext`](https://deno.land/x/fresh/server.ts?s=PluginRenderContext)
|
||||
object, which contains a `render()` method. This method must be invoked during
|
||||
the render hook to actually render the page. It is a terminal error to not call
|
||||
the `render()` method during the render hook.
|
||||
|
||||
The `render()` method returns a
|
||||
[`PluginRenderFunctionResult`](https://deno.land/x/fresh/server.ts?s=PluginRenderFunctionResult)
|
||||
object which contains the HTML text of the rendered page, as well as a boolean
|
||||
indicating whether the page contains any islands that will be hydrated on the
|
||||
client.
|
||||
|
||||
The `render` hook needs to synchronously return a
|
||||
[`PluginRenderResult`](https://deno.land/x/fresh/server.ts?s=PluginRenderResult)
|
||||
object. Additional CSS and JS modules can be added to be injected into the page
|
||||
by adding them to `styles` and `scripts` arrays in this object.
|
||||
|
||||
`styles` are injected into the `<head>` of the page as inline CSS. Each entry
|
||||
can define the CSS text to inject, as well as an optional `id` for the style
|
||||
tag, and an optional `media` attribute for the style tag.
|
||||
|
||||
`scripts` define JavaScript/TypeScript modules to be injected into the page. The
|
||||
possibly loaded modules need to be defined up front in the `Plugin#entrypoints`
|
||||
property. Each defined module must be a JavaScript/TypeScript module that has a
|
||||
default export of a function that takes one (arbitrary) argument, and returns
|
||||
nothing (or a promise resolving to nothing). Fresh will call this function with
|
||||
the state defined in the `scripts` entry. The state can be any arbitrary JSON
|
||||
serializable JavaScript value.
|
||||
|
||||
For an example of a plugin that uses the `render` hook, see the first-party
|
||||
[Twind plugin](https://github.com/denoland/fresh/blob/main/plugins/twind.ts).
|
||||
|
||||
### Hook: `renderAsync`
|
||||
|
||||
This hook is largely the same as the `render` hook, with a couple of key
|
||||
differences to make asynchronous style and script generation possible. It must
|
||||
asynchronously return its
|
||||
[`PluginRenderResult`](https://deno.land/x/fresh/server.ts?s=PluginRenderResult),
|
||||
either from an `async/await` function or wrapped within a promise.
|
||||
|
||||
The render hook is called with the
|
||||
[`PluginAsyncRenderContext`](https://deno.land/x/fresh/server.ts?s=PluginAsyncRenderContext)
|
||||
object, which contains a `renderAsync()` method. This method must be invoked
|
||||
during the render hook to actually render the page. It is a terminal error to
|
||||
not call the `renderAsync()` method during the render hook.
|
||||
|
||||
This is useful for when plugins are generating styles and scripts with
|
||||
asynchronous dependencies based on the `htmlText`. Unlike the synchronous render
|
||||
hook, async render hooks for multiple pages can be running at the same time.
|
||||
This means that unlike the synchronous render hook, you can not use global
|
||||
variables to propagate state between the render hook and the renderer.
|
||||
|
||||
The `renderAsync` hooks start before any page rendering occurs, and finish after
|
||||
all rendering is complete -- they wrap around the underlying JSX->string
|
||||
rendering, plugin `render` hooks, and the
|
||||
[`RenderFunction`](https://deno.land/x/fresh/server.ts?s=RenderFunction) that
|
||||
may be provided to Fresh's `start` entrypoint in the `main.ts` file.
|
||||
|
||||
### Routes and Middlewares
|
||||
|
||||
You can create routes and middlewares that get loaded and rendered like the
|
||||
normal [routes](/docs/concepts/routes) and
|
||||
[middlewares](/docs/concepts/middleware).
|
||||
|
||||
The plugin routes and middlewares need a defined path in the format of a file
|
||||
name without a filetype inside the routes directory(E.g. `blog/index`,
|
||||
`blog/[slug]`).
|
||||
|
||||
For more examples see the [Concepts: Routing](/docs/concepts/routing) page.
|
||||
|
||||
To create a middleware you need to create a `MiddlewareHandler` function.
|
||||
|
||||
And to create a route you can create both a Handler and/or component.
|
||||
@@ -0,0 +1,173 @@
|
||||
---
|
||||
description: |
|
||||
Routes are the basic building block of Fresh applications. They are used to define the behaviour the application when a given path is requested.
|
||||
---
|
||||
|
||||
At their core, routes describe how a request for a given path should be handled,
|
||||
and what the response should be. To do this, routes have two main parts: the
|
||||
handler, and the component. A route can have either one, or both, but never
|
||||
neither.
|
||||
|
||||
The handler is a function that is called for every request to the route. It
|
||||
needs to return a response that is then sent to the client. The response could
|
||||
be anything: a plain text string, a JSON object, an HTML page, a WebSocket
|
||||
connection, a streaming file, or pretty much anything else. The handler is
|
||||
passed a `render` function that it can call to invoke rendering a component.
|
||||
|
||||
The component is the template for a page. It is a JSX element that is rendered
|
||||
on the server. The page component gets passed props that can be used by it to
|
||||
determine exactly what should be rendered. By default components receives props
|
||||
consisting of: the request URL, the matching route (as a string), the matches
|
||||
from the URL pattern match, any state set by middleware, and any data passed to
|
||||
the handler's `render` function.
|
||||
|
||||
## Handler route
|
||||
|
||||
Let's look at a basic route that returns a plain text string:
|
||||
|
||||
```tsx
|
||||
// routes/plain.tsx
|
||||
|
||||
import { HandlerContext, Handlers } from "$fresh/server.ts";
|
||||
|
||||
export const handler: Handlers = {
|
||||
GET(_req: Request, _ctx: HandlerContext) {
|
||||
return new Response("Hello World");
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
To define a handler, one needs to export a `handler` function or object from the
|
||||
route module. If the handler is an object, each key in the object is the name of
|
||||
the HTTP method that the handler should be called for. For example the `GET`
|
||||
handler above is called for `GET` requests. If the handler is a function, it is
|
||||
called for all requests regardless of the method. If an HTTP method does not
|
||||
have a corresponding handler, a 405 HTTP error is returned.
|
||||
|
||||
## Component route
|
||||
|
||||
Now, let's render some HTML using the route component:
|
||||
|
||||
```tsx
|
||||
// routes/html.tsx
|
||||
|
||||
import { PageProps } from "$fresh/server.ts";
|
||||
|
||||
export default function Page(props: PageProps) {
|
||||
return <div>You are on the page '{props.url.href}'.</div>;
|
||||
}
|
||||
```
|
||||
|
||||
The page component needs to be the default export of the route module. It is
|
||||
passed props that can be used to render the page.
|
||||
|
||||
As you can see in the second example, if no handler is explicitly defined a
|
||||
default handler is used that just renders out the page component if present. You
|
||||
can also override the default handler though to modify how exactly rendering
|
||||
should work.
|
||||
|
||||
## Mixed handler and component route
|
||||
|
||||
In the below example, a custom handler is used to add a custom header to the
|
||||
response after rendering the page component.
|
||||
|
||||
```tsx
|
||||
// routes/html.tsx
|
||||
|
||||
import { HandlerContext, Handlers, PageProps } from "$fresh/server.ts";
|
||||
|
||||
export const handler: Handlers = {
|
||||
async GET(_req: Request, ctx: HandlerContext) {
|
||||
const resp = await ctx.render();
|
||||
resp.headers.set("X-Custom-Header", "Hello World");
|
||||
return resp;
|
||||
},
|
||||
};
|
||||
|
||||
export default function Page(props: PageProps) {
|
||||
return <div>You are on the page '{props.url.href}'.</div>;
|
||||
}
|
||||
```
|
||||
|
||||
## Async route components
|
||||
|
||||
Having a separate route handler and component function is nice, when you want to
|
||||
test these in isolation, but can become a bit cumbersome to maintain. They
|
||||
require some additional indirection of declaring an interface for the component
|
||||
`Data` when you're passing it around through `ctx.render()`.
|
||||
|
||||
```tsx
|
||||
interface Data {
|
||||
foo: number;
|
||||
}
|
||||
|
||||
export const handler: Handlers<Data> = {
|
||||
async GET(req, ctx) {
|
||||
const value = await loadFooValue();
|
||||
ctx.render({ foo: value });
|
||||
},
|
||||
};
|
||||
|
||||
export default function MyPage(props: PageProps<Data>) {
|
||||
return <p>foo is: {props.data.foo}</p>;
|
||||
}
|
||||
```
|
||||
|
||||
When a route has both a component and a `GET` handler, they are typically very
|
||||
closely coupled. With async route components you can merge the two together and
|
||||
avoid having to create the `Data` interface boilerplate.
|
||||
|
||||
```tsx
|
||||
// Async route component
|
||||
export default async function MyPage(req: Request, ctx: RouteContext) {
|
||||
const value = await loadFooValue();
|
||||
return <p>foo is: {value}</p>;
|
||||
}
|
||||
```
|
||||
|
||||
The code gets a little shorter with async route components. Conceptually, you
|
||||
can think of async route components inlining the `GET` handler into the
|
||||
component function. Note, that you can still add additional HTTP handlers in the
|
||||
same file like before.
|
||||
|
||||
```tsx
|
||||
export const handler: Handlers = {
|
||||
async POST(req) {
|
||||
// ... do something here
|
||||
},
|
||||
};
|
||||
|
||||
export default async function MyPage(req: Request, ctx: RouteContext) {
|
||||
const value = await loadFooValue();
|
||||
return <p>foo is: {value}</p>;
|
||||
}
|
||||
```
|
||||
|
||||
### Returning Response objects
|
||||
|
||||
Quite often a route handler needs to render a 404 page or bail out of rendering
|
||||
in another manner. This can be done by returning a `Response` object.
|
||||
|
||||
```tsx
|
||||
// Async route component
|
||||
export default async function MyPage(req: Request, ctx: RouteContext) {
|
||||
const value = await loadFooValue();
|
||||
|
||||
// Return 404 if `value` is null
|
||||
if (value === null) {
|
||||
return ctx.renderNotFound();
|
||||
}
|
||||
|
||||
// Returning a response object directly works too
|
||||
if (value === "redirect") {
|
||||
const headers = new Headers();
|
||||
headers.set("location", "/some-other-page");
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers,
|
||||
});
|
||||
}
|
||||
|
||||
return <p>foo is: {value}</p>;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,56 @@
|
||||
---
|
||||
description: |
|
||||
File based routing is the simplest way to do routing in Fresh apps. Additionally custom patterns can be configured per route.
|
||||
---
|
||||
|
||||
Routing is the mechanism that determines what route a given incoming request is
|
||||
handled by. Fresh routes requests based on their URL path. By default routes
|
||||
specify which paths they are invoked for using the name of the file. Routes can
|
||||
also define a custom [URL pattern][urlpattern] to match against for more
|
||||
advanced use cases.
|
||||
|
||||
The file based routing in Fresh is very similar to the file based routing seen
|
||||
in other frameworks, namely Next.js. File names are used to determine which
|
||||
route a given request should be handled by. The pattern is determined based on
|
||||
the path of the file on disk, relative to the `routes/` directory.
|
||||
|
||||
File names are mapped to route patterns as follows:
|
||||
|
||||
- File extensions are ignored.
|
||||
- Literals in the file path are treated as string literals to match.
|
||||
- Files named `<path>/index.<ext>` behave identically to a file named
|
||||
`<path>.<ext>`.
|
||||
- Path segments can be made dynamic by surrounding an identifier with `[` and
|
||||
`]`.
|
||||
- Paths where the last path segment follows the structure `[...<ident>]` are
|
||||
treated as having a wildcard suffix.
|
||||
|
||||
Here is a table of file names, which route patterns they map to, and which paths
|
||||
they might match:
|
||||
|
||||
| File name | Route pattern | Matching paths |
|
||||
| ------------------------- | ---------------------- | -------------------------- |
|
||||
| `index.ts` | `/` | `/` |
|
||||
| `about.ts` | `/about` | `/about` |
|
||||
| `blog/index.ts` | `/blog` | `/blog` |
|
||||
| `blog/[slug].ts` | `/blog/:slug` | `/blog/foo`, `/blog/bar` |
|
||||
| `blog/[slug]/comments.ts` | `/blog/:slug/comments` | `/blog/foo/comments` |
|
||||
| `old/[...path].ts` | `/old/:path*` | `/old/foo`, `/old/bar/baz` |
|
||||
|
||||
Advanced use-cases can require that a more complex pattern be used for matching.
|
||||
A custom [URL pattern][urlpattern] can be specified in the route configuration.
|
||||
This pattern will be used instead of the file path based pattern:
|
||||
|
||||
```ts
|
||||
// routes/x.ts
|
||||
|
||||
import { RouteConfig } from "$fresh/server.ts";
|
||||
|
||||
export const config: RouteConfig = {
|
||||
routeOverride: "/x/:module@:version/:path*",
|
||||
};
|
||||
|
||||
// ...
|
||||
```
|
||||
|
||||
[urlpattern]: https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
description: |
|
||||
Fresh's architecture is designed to leverage server components by default.
|
||||
---
|
||||
|
||||
If you've read about Fresh's [architecture](/docs/concepts/architecture) then
|
||||
you know that it's based on the islands architecture pattern. The flip side of
|
||||
this is that everything else is, by default, a server component. When you
|
||||
[create a route](/docs/getting-started/create-a-route), all of the components
|
||||
used are rendered on the server. No javascript is sent to the client, unless you
|
||||
specifically include something from the `/islands/` folder.
|
||||
|
||||
Internally, Fresh's rendering heavily leverages
|
||||
[preact-render-to-string](https://github.com/preactjs/preact-render-to-string).
|
||||
This is the exact library mentioned on Preact's
|
||||
[Server-Side Rendering](https://preactjs.com/guide/v10/server-side-rendering/)
|
||||
article.
|
||||
@@ -0,0 +1,86 @@
|
||||
---
|
||||
description: |
|
||||
The ability to configure the core Fresh server leads to its flexibility.
|
||||
---
|
||||
|
||||
In this page we discuss how the server can be configured during startup.
|
||||
|
||||
The signature of the primary method looks like this:
|
||||
|
||||
```ts
|
||||
export async function start(routes: Manifest, opts: StartOptions = {});
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
`Manifest` comes from `fresh.gen.ts`, so nothing to do there. `opts` is where
|
||||
things get interesting. `StartOptions` looks like this:
|
||||
|
||||
```
|
||||
export type StartOptions = ServeInit & FreshOptions;
|
||||
```
|
||||
|
||||
The good stuff is really in...
|
||||
|
||||
```ts
|
||||
export interface FreshOptions {
|
||||
render?: RenderFunction;
|
||||
plugins?: Plugin[];
|
||||
staticDir?: string;
|
||||
router?: RouterOptions;
|
||||
}
|
||||
```
|
||||
|
||||
And for brevity here are the remaining two types:
|
||||
|
||||
```ts
|
||||
export type RenderFunction = (
|
||||
ctx: RenderContext,
|
||||
render: InnerRenderFunction,
|
||||
) => void | Promise<void>;
|
||||
|
||||
export interface RouterOptions {
|
||||
/**
|
||||
* @default {false}
|
||||
*/
|
||||
trailingSlash?: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
## Plugins
|
||||
|
||||
See the [docs](/docs/concepts/plugins) on this topic for more detail. But for
|
||||
completion, you can do something like this to load plugins:
|
||||
|
||||
```ts
|
||||
await start(manifest, { plugins: [twindPlugin(twindConfig)] });
|
||||
```
|
||||
|
||||
## StaticDir
|
||||
|
||||
This allows you to specify the location where your site's static assets are
|
||||
stored. Here's an example:
|
||||
|
||||
```ts
|
||||
await start(manifest, { staticDir: "./custom_static" });
|
||||
```
|
||||
|
||||
## Render
|
||||
|
||||
This is by far the most complicated option currently available. It allows you to
|
||||
configure how your components get rendered.
|
||||
|
||||
A detailed, concrete example of this is changing the language of the `<html>`
|
||||
tag. See the documentation [here](/docs/examples/setting-the-language).
|
||||
|
||||
## RouterOptions
|
||||
|
||||
### TrailingSlash
|
||||
|
||||
By default Fresh uses URLs like `https://www.example.com/about`. If you'd like,
|
||||
you can configure this to `https://www.example.com/about/` by using the
|
||||
`trailingSlash` setting.
|
||||
|
||||
```ts
|
||||
await start(manifest, { router: { trailingSlash: true } });
|
||||
```
|
||||
@@ -0,0 +1,51 @@
|
||||
---
|
||||
description: |
|
||||
Fresh has built-in support for serving static files. This is useful for serving images, CSS, and other static assets.
|
||||
---
|
||||
|
||||
Fresh automatically serves static assets placed in a `static/` directory in the
|
||||
project root. These assets are served at the root of the webserver, with a
|
||||
higher priority than routes. This means that if a given request matches a file
|
||||
in the `static/` folder, it is always served, even if there is a route that
|
||||
would also match the request.
|
||||
|
||||
Static asset responses automatically get a `content-type` header assigned based
|
||||
on the file extension of the file on disk. Assets are also automatically
|
||||
streamed from disk to the client to improve performance and efficiency for both
|
||||
user and server.
|
||||
|
||||
Fresh also adds an `etag` header to assets automatically and handles the
|
||||
`If-None-Match` header for incoming requests.
|
||||
|
||||
### Caching
|
||||
|
||||
By default, no caching headers are added to assets. This can be disadvantageous
|
||||
in many scenarios, so Fresh makes it easy to serve assets with long cache
|
||||
lifetimes too.
|
||||
|
||||
The first approach to do this is manual. The client runtime exports an `asset`
|
||||
function that takes an absolute path to the static asset and returns a "locked"
|
||||
version of this path that contains a build ID for cache busting. When the asset
|
||||
is requested at this "locked" path, it will be served with a cache lifetime of
|
||||
one year.
|
||||
|
||||
```jsx
|
||||
import { asset } from "$fresh/runtime.ts";
|
||||
|
||||
export default function Page() {
|
||||
return (
|
||||
<p>
|
||||
<a href={asset("/brochure.pdf")}>View brochure</a>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Fresh also does this automatically for `src` and `srcset` attributes in `<img>`
|
||||
and `<source>` HTML tags. These will automatically use "locked" paths if Fresh
|
||||
deems it safe to do so. You can always opt out of this behaviour per tag, by
|
||||
adding the `data-fresh-disable-lock` attribute.
|
||||
|
||||
```jsx
|
||||
<img src="/user.png" />;
|
||||
```
|
||||
@@ -0,0 +1,128 @@
|
||||
---
|
||||
description: |
|
||||
New versions of Fresh are regularly released. This page explains how to update your project.
|
||||
---
|
||||
|
||||
Fresh constists of multiple pieces which are independently versioned and
|
||||
released.
|
||||
|
||||
- Fresh (https://deno.land/x/fresh)
|
||||
- Preact (https://esm.sh/preact)
|
||||
- preact-render-to-string (https://esm.sh/preact-render-to-string)
|
||||
|
||||
Some plugins also have their own dependencies that can be updated independently.
|
||||
|
||||
- Twind (https://esm.sh/twind) (for the twind plugin)
|
||||
|
||||
For the most part these pieces can be updated independently. Certain versions of
|
||||
Fresh may require a minimum version of a given dependency. This is documented
|
||||
below.
|
||||
|
||||
| Fresh version | Preact | preact-render-to-string | Deno |
|
||||
| ------------- | ----------------- | ----------------------- | --------- |
|
||||
| 1.0.0-1.0.2 | >=10.8.1 <11.0.0 | >=5.2.0 <6.0.0 | >= 1.23.0 |
|
||||
| 1.1.0-1.1.5 | >=10.8.1 <11.0.0 | >=5.2.0 <6.0.0 | >= 1.25.0 |
|
||||
| 1.2.0 | >=10.15.0 <11.0.0 | >=6.1.0 | >= 1.25.0 |
|
||||
|
||||
## Updating dependencies
|
||||
|
||||
To update your dependencies, you have two options:
|
||||
|
||||
- Run the Fresh updater to update your project dependencies.
|
||||
- Manually update the dependency versions in your `deno.json` file.
|
||||
|
||||
### Auto updater
|
||||
|
||||
The auto updater is a command line tool that will update your project's
|
||||
`deno.json` file to the latest versions of Fresh and its dependencies. It may
|
||||
also contain code mods for your project that will update your code to the latest
|
||||
recommended patterns for Fresh projects.
|
||||
|
||||
To run the auto updater, run the following command from the root of your
|
||||
project:
|
||||
|
||||
```bash
|
||||
$ deno run -A -r https://fresh.deno.dev/update .
|
||||
```
|
||||
|
||||
You will be prompted to confirm the changes that will be made to your project.
|
||||
|
||||
### Manual update
|
||||
|
||||
To manually update your project's dependencies, you can edit the `deno.json`
|
||||
file in the root of your projects directory. Dependency versions are encoded
|
||||
into the URLs in this file. For example, here is how to update a project from
|
||||
Fresh 1.0.2 to 1.1.3, and update Preact to the latest version:
|
||||
|
||||
```diff
|
||||
{
|
||||
"imports": {
|
||||
- "$fresh/": "https://deno.land/x/fresh@1.0.2/",
|
||||
+ "$fresh/": "https://deno.land/x/fresh@1.1.5/",
|
||||
|
||||
- "preact": "https://esm.sh/preact@10.8.1",
|
||||
- "preact/": "https://esm.sh/preact@10.8.1/",
|
||||
+ "preact": "https://esm.sh/preact@10.11.0",
|
||||
+ "preact/": "https://esm.sh/preact@10.11.0/",
|
||||
|
||||
- "preact-render-to-string": "https://esm.sh/*preact-render-to-string@5.2.0",
|
||||
+ "preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.1.0",
|
||||
|
||||
"twind": "https://esm.sh/twind@0.16.17",
|
||||
"twind/": "https://esm.sh/twind@0.16.17/"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Automatic update checks
|
||||
|
||||
Fresh will periodically check if a new Fresh version is available if it's
|
||||
running outside of CI. This happens once per day and can be disabled by setting
|
||||
the `FRESH_NO_UPDATE_CHECK=true` environment variable.
|
||||
|
||||
## Code mods
|
||||
|
||||
Code mods are small scripts that can be run to update your project's code to
|
||||
match the latest recommended patterns for Fresh projects. Code mods can be run
|
||||
through the auto updater. Sometimes the code mod can not cover all cases, so you
|
||||
may need to manually update some code. This section explains the code mods
|
||||
currently available.
|
||||
|
||||
### Classical JSX -> Automatic JSX
|
||||
|
||||
> This code mod is only available in Fresh 1.1.0 and above.
|
||||
|
||||
The classical JSX transform that relies on a `/** @jsx h */` pragma is no longer
|
||||
the recommended way to use JSX in Fresh projects. Instead, starting with version
|
||||
1.1.0, Fresh projects should use the automatic JSX transform that requires no
|
||||
JSX pragma or preact import.
|
||||
|
||||
```diff
|
||||
- /** @jsx h */
|
||||
- import { h } from "preact";
|
||||
|
||||
export default function Page() {
|
||||
return <div>Hello world!</div>;
|
||||
}
|
||||
```
|
||||
|
||||
This code mod will update your deno.json file to include the relevant compiler
|
||||
options to enable the automatic JSX transform. It will then go through your
|
||||
project and remove any `/** @jsx h */` pragmas and `import { h } from "preact"`
|
||||
statements.
|
||||
|
||||
### Classic twind -> Twind plugin
|
||||
|
||||
> This code mod is only available in Fresh 1.1.0 and above.
|
||||
|
||||
Fresh version 1.1.0 introduced a new plugin for using twind with Fresh. This
|
||||
plugin is much nicer to use than the raw twind integration that was previously
|
||||
available.
|
||||
|
||||
This code mod will update your project to use the new twind plugin. It will
|
||||
update your `main.ts` file to import the twind plugin and add it to the plugins
|
||||
array. It will also update your files to remove many unnecessary uses of the
|
||||
`tw` function, and remove unnecessary twind imports. While the code mod can
|
||||
handle most cases, you may need to manually update some code. Additionally you
|
||||
will need to manually update your `twind.config.ts` if you use a custom
|
||||
configuration.
|
||||
@@ -0,0 +1,80 @@
|
||||
---
|
||||
description: |
|
||||
Change the source directory to effectively manage your project.
|
||||
---
|
||||
|
||||
When you initialize a project with `deno run -A -r https://fresh.deno.dev`,
|
||||
you'll end up with a project like the following:
|
||||
|
||||
```
|
||||
.
|
||||
├── README.md
|
||||
├── components
|
||||
│ └── Button.tsx
|
||||
├── deno.json
|
||||
├── dev.ts
|
||||
├── fresh.gen.ts
|
||||
├── islands
|
||||
│ └── Counter.tsx
|
||||
├── main.ts
|
||||
├── routes
|
||||
│ ├── greet
|
||||
│ │ ├── [name].tsx
|
||||
│ ├── api
|
||||
│ │ └── joke.ts
|
||||
│ ├── _404.tsx
|
||||
│ └── index.tsx
|
||||
└── static
|
||||
├── favicon.ico
|
||||
└── logo.svg
|
||||
```
|
||||
|
||||
## Using a `src` directory
|
||||
|
||||
If you'd like your code to live in an `src` directory (or any other directory of
|
||||
your choosing), then you'll need to do the following things:
|
||||
|
||||
1. Move all your files, except `deno.json` and `README.md`, to the `src`
|
||||
directory.
|
||||
2. Modify the `start` task in `deno.json` to point to the new directory.
|
||||
|
||||
Here's what the diff of `deno.json` looks like:
|
||||
|
||||
```diff
|
||||
{
|
||||
"lock": false,
|
||||
"tasks": {
|
||||
- "start": "deno run -A --watch=static/,routes/ dev.ts"
|
||||
+ "start": "deno run -A --watch=src/static/,src/routes/ src/dev.ts"
|
||||
},
|
||||
"imports": {
|
||||
"$fresh/": "file:///Users/reed/code/fresh/",
|
||||
```
|
||||
|
||||
The resulting file structure looks like this:
|
||||
|
||||
```
|
||||
.
|
||||
├── README.md
|
||||
├── deno.json
|
||||
└── src
|
||||
├── components
|
||||
│ └── Button.tsx
|
||||
├── dev.ts
|
||||
├── fresh.gen.ts
|
||||
├── islands
|
||||
│ └── Counter.tsx
|
||||
├── main.ts
|
||||
├── routes
|
||||
│ ├── greet
|
||||
│ │ ├── [name].tsx
|
||||
│ ├── api
|
||||
│ │ └── joke.ts
|
||||
│ ├── _404.tsx
|
||||
│ └── index.tsx
|
||||
└── static
|
||||
├── favicon.ico
|
||||
└── logo.svg
|
||||
```
|
||||
|
||||
Success! Your code now lives elsewhere.
|
||||
@@ -0,0 +1,271 @@
|
||||
---
|
||||
description: |
|
||||
Use HTTP CRUD methods to perform operations on resources. Learn how to use HTTP handlers to create a RESTful API.
|
||||
---
|
||||
|
||||
The MDN [docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods) are a
|
||||
great resource to learn more about HTTP methods. We'll touch on the four
|
||||
fundamental methods necessary to create a basic CRUD (create, read, update,
|
||||
delete) API here. Additionally, we'll briefly mention CORS requests and how
|
||||
`OPTIONS` comes into play.
|
||||
|
||||
Using HTTP methods is a common way to create a REST API. Fresh supports common
|
||||
HTTP methods in handlers out of the box. Async HTTP requests are also supported.
|
||||
Read more about custom handlers [here](/docs/getting-started/custom-handlers).
|
||||
|
||||
In this example we'll be creating a small API that uses
|
||||
[Deno KV](https://deno.com/kv) to store users in a database.
|
||||
|
||||
Our project structure will look like this (in addition to the rest of the Fresh
|
||||
code from a new project):
|
||||
|
||||
```
|
||||
├── routes
|
||||
│ └── api
|
||||
│ └── users
|
||||
│ ├── [id].ts
|
||||
│ └── index.ts
|
||||
```
|
||||
|
||||
In each section about a method, only the relevant handler will be shown. The
|
||||
full files are available at the bottom for reference.
|
||||
|
||||
## POST
|
||||
|
||||
`POST` (create) is used to create a resource.
|
||||
|
||||
```tsx
|
||||
// routes/api/users/index.ts
|
||||
export const handler: Handlers<User | null> = {
|
||||
async POST(req, _ctx) {
|
||||
const user = await req.json() as User;
|
||||
const userKey = ["user", user.id];
|
||||
const ok = await kv.atomic()
|
||||
.set(userKey, user)
|
||||
.commit();
|
||||
if (!ok) throw new Error("Something went wrong.");
|
||||
return new Response(JSON.stringify(user));
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
Test this with Postman (or your favorite client) with a URL like
|
||||
`http://localhost:8000/api/users` and a method of `POST`. Make sure to have a
|
||||
payload like:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "2",
|
||||
"name": "TestUserName"
|
||||
}
|
||||
```
|
||||
|
||||
You should receive the same thing back:
|
||||
|
||||
```json
|
||||
{ "id": "2", "name": "TestUserName" }
|
||||
```
|
||||
|
||||
## GET
|
||||
|
||||
`GET` (read) is used to retrieve a resource and is by far the most common HTTP
|
||||
method. You can use `GET` to fetch database content, markdown, or static files.
|
||||
|
||||
```tsx
|
||||
// routes/api/users/[id].ts
|
||||
export const handler: Handlers<User | null> = {
|
||||
async GET(_req, ctx) {
|
||||
const id = ctx.params.id;
|
||||
const key = ["user", id];
|
||||
const user = (await kv.get<User>(key)).value!;
|
||||
return new Response(JSON.stringify(user));
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
Let's practice retrieving our user! A `GET` request to
|
||||
`http://localhost:8000/api/users/2` should return:
|
||||
|
||||
```json
|
||||
{ "id": "2", "name": "TestUserName" }
|
||||
```
|
||||
|
||||
## PUT (and PATCH)
|
||||
|
||||
`PUT` (update) and `PATCH` are used to update a resource. While similar, there
|
||||
are differences and you should use the one that best suits your use case. Read
|
||||
more about HTTP methods on
|
||||
[MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods).
|
||||
|
||||
The short version of it: `PUT` requires the entire object to be submitted, while
|
||||
`PATCH` requires only the properties that are different to be submitted.
|
||||
|
||||
An example of an update endpoint using `PUT`:
|
||||
|
||||
```tsx
|
||||
// routes/api/users/[id].ts
|
||||
export const handler: Handlers<User | null> = {
|
||||
async PUT(req, ctx) {
|
||||
const id = ctx.params.id;
|
||||
const user = await req.json() as User;
|
||||
const userKey = ["user", id];
|
||||
const userRes = await kv.get(userKey);
|
||||
if (!userRes.value) return new Response(`no user with id ${id} found`);
|
||||
const ok = await kv.atomic()
|
||||
.check(userRes)
|
||||
.set(userKey, user)
|
||||
.commit();
|
||||
if (!ok) throw new Error("Something went wrong.");
|
||||
return new Response(JSON.stringify(user));
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
Time to change their name. We'll now `PUT` a request to
|
||||
`http://localhost:8000/api/users/2` like:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "2",
|
||||
"name": "New Name"
|
||||
}
|
||||
```
|
||||
|
||||
We should receive:
|
||||
|
||||
```json
|
||||
{ "id": "2", "name": "New Name" }
|
||||
```
|
||||
|
||||
If, on the other hand, we chose to implement this as a `PATCH` operation, the
|
||||
request would just involve the changed property like this:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "New Name"
|
||||
}
|
||||
```
|
||||
|
||||
No need to send in the id in this case.
|
||||
|
||||
## DELETE
|
||||
|
||||
`DELETE` (delete) is used to delete a resource.
|
||||
|
||||
```tsx
|
||||
// routes/api/users/[id].ts
|
||||
export const handler: Handlers<User | null> = {
|
||||
async DELETE(_req, ctx) {
|
||||
const id = ctx.params.id;
|
||||
const userKey = ["user", id];
|
||||
const userRes = await kv.get(userKey);
|
||||
if (!userRes.value) return new Response(`no user with id ${id} found`);
|
||||
const ok = await kv.atomic()
|
||||
.check(userRes)
|
||||
.delete(userKey)
|
||||
.commit();
|
||||
if (!ok) throw new Error("Something went wrong.");
|
||||
return new Response(`user ${id} deleted`);
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
Try sending `DELETE` to `http://localhost:8000/api/users/2` without a body.
|
||||
We'll get back:
|
||||
|
||||
```
|
||||
user 2 deleted
|
||||
```
|
||||
|
||||
## OPTIONS
|
||||
|
||||
Options can be used for some advanced cases, including implementing preflight
|
||||
request checks for complex CORS use cases. See more on the
|
||||
[CORS documentation](/docs/examples/dealing-with-cors).
|
||||
|
||||
## Full File Reference
|
||||
|
||||
<details>
|
||||
<summary>[id].ts</summary>
|
||||
|
||||
```ts
|
||||
import { Handlers } from "$fresh/server.ts";
|
||||
|
||||
type User = {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
|
||||
const kv = await Deno.openKv();
|
||||
|
||||
export const handler: Handlers<User | null> = {
|
||||
async GET(_req, ctx) {
|
||||
const id = ctx.params.id;
|
||||
const key = ["user", id];
|
||||
const user = (await kv.get<User>(key)).value!;
|
||||
return new Response(JSON.stringify(user));
|
||||
},
|
||||
async DELETE(_req, ctx) {
|
||||
const id = ctx.params.id;
|
||||
const userKey = ["user", id];
|
||||
const userRes = await kv.get(userKey);
|
||||
if (!userRes.value) return new Response(`no user with id ${id} found`);
|
||||
const ok = await kv.atomic()
|
||||
.check(userRes)
|
||||
.delete(userKey)
|
||||
.commit();
|
||||
if (!ok) throw new Error("Something went wrong.");
|
||||
return new Response(`user ${id} deleted`);
|
||||
},
|
||||
async PUT(req, ctx) {
|
||||
const id = ctx.params.id;
|
||||
const user = await req.json() as User;
|
||||
const userKey = ["user", id];
|
||||
const userRes = await kv.get(userKey);
|
||||
if (!userRes.value) return new Response(`no user with id ${id} found`);
|
||||
const ok = await kv.atomic()
|
||||
.check(userRes)
|
||||
.set(userKey, user)
|
||||
.commit();
|
||||
if (!ok) throw new Error("Something went wrong.");
|
||||
return new Response(JSON.stringify(user));
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>index.ts</summary>
|
||||
|
||||
```ts
|
||||
import { Handlers } from "$fresh/server.ts";
|
||||
|
||||
type User = {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
|
||||
const kv = await Deno.openKv();
|
||||
|
||||
export const handler: Handlers<User | null> = {
|
||||
async GET(_req, _ctx) {
|
||||
const users = [];
|
||||
for await (const res of kv.list({ prefix: ["user"] })) {
|
||||
users.push(res.value);
|
||||
}
|
||||
return new Response(JSON.stringify(users));
|
||||
},
|
||||
async POST(req, _ctx) {
|
||||
const user = await req.json() as User;
|
||||
const userKey = ["user", user.id];
|
||||
const ok = await kv.atomic()
|
||||
.set(userKey, user)
|
||||
.commit();
|
||||
if (!ok) throw new Error("Something went wrong.");
|
||||
return new Response(JSON.stringify(user));
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
</details>
|
||||
@@ -0,0 +1,101 @@
|
||||
---
|
||||
description: |
|
||||
CORS enabling routes in your Fresh project.
|
||||
---
|
||||
|
||||
So you've encountered some CORS problems and are on the hunt for the solution?
|
||||
You're in the right spot.
|
||||
|
||||
Here's a good [resource](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)
|
||||
talking about CORS in general, in case you don't fully understand what's wrong.
|
||||
|
||||
## Simple CORS -- Middleware
|
||||
|
||||
As per the above link, "simple" requests involve `GET`, `HEAD`, or `POST`
|
||||
requests. You can CORS enable all the routes affected by some `middleware` by
|
||||
doing the following:
|
||||
|
||||
```ts
|
||||
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||
|
||||
export async function handler(
|
||||
req: Request,
|
||||
ctx: MiddlewareHandlerContext,
|
||||
) {
|
||||
const origin = req.headers.get("Origin") || "*";
|
||||
const resp = await ctx.next();
|
||||
const headers = resp.headers;
|
||||
|
||||
headers.set("Access-Control-Allow-Origin", origin);
|
||||
headers.set("Access-Control-Allow-Credentials", "true");
|
||||
headers.set(
|
||||
"Access-Control-Allow-Headers",
|
||||
"Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With",
|
||||
);
|
||||
headers.set(
|
||||
"Access-Control-Allow-Methods",
|
||||
"POST, OPTIONS, GET, PUT, DELETE",
|
||||
);
|
||||
|
||||
return resp;
|
||||
}
|
||||
```
|
||||
|
||||
## Complex CORS -- Middleware
|
||||
|
||||
What about for one of the other HTTP methods? Then you'll need to be able to
|
||||
deal with "preflight requests". Let's imagine you're trying to support a
|
||||
`DELETE` route. Then you'd need to do something like this:
|
||||
|
||||
```ts
|
||||
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||
|
||||
export async function handler(
|
||||
_req: Request,
|
||||
ctx: MiddlewareHandlerContext,
|
||||
) {
|
||||
if (_req.method == "OPTIONS") {
|
||||
const resp = new Response(null, {
|
||||
status: 204,
|
||||
});
|
||||
const origin = _req.headers.get("Origin") || "*";
|
||||
const headers = resp.headers;
|
||||
headers.set("Access-Control-Allow-Origin", origin);
|
||||
headers.set(
|
||||
"Access-Control-Allow-Methods",
|
||||
"DELETE",
|
||||
);
|
||||
return resp;
|
||||
}
|
||||
const origin = _req.headers.get("Origin") || "*";
|
||||
const resp = await ctx.next();
|
||||
const headers = resp.headers;
|
||||
|
||||
headers.set("Access-Control-Allow-Origin", origin);
|
||||
headers.set("Access-Control-Allow-Credentials", "true");
|
||||
headers.set(
|
||||
"Access-Control-Allow-Headers",
|
||||
"Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With",
|
||||
);
|
||||
headers.set(
|
||||
"Access-Control-Allow-Methods",
|
||||
"POST, OPTIONS, GET, PUT, DELETE",
|
||||
);
|
||||
|
||||
return resp;
|
||||
}
|
||||
```
|
||||
|
||||
These complex results require a two step process:
|
||||
|
||||
1. the browser makes an `OPTIONS` request to find out about the allowed methods
|
||||
2. the browser makes the actual request
|
||||
|
||||
So you can see the middleware has some special handling to deal with `OPTIONS`
|
||||
requests.
|
||||
|
||||
## CORS in Routes
|
||||
|
||||
Of course there's no reason why you need to use middleware in order to solve
|
||||
this. The headers can be set directly in the
|
||||
[handler](/docs/getting-started/custom-handlers) as well.
|
||||
@@ -0,0 +1,87 @@
|
||||
---
|
||||
description: |
|
||||
Sometimes URL based routing isn't enough.
|
||||
---
|
||||
|
||||
The page on [routing](/concepts/routing) hints at complex routing based on URL
|
||||
patterns using a `RouteConfig` object. Let's dive into this in a bit more
|
||||
detail.
|
||||
|
||||
A `RouteConfig` has a `routeOverride` string property, which makes use of the
|
||||
[URL Pattern API](https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API).
|
||||
Here you can define named groups, wildcards, regex groups, and other bits.
|
||||
|
||||
## Simple Route Config
|
||||
|
||||
Let's look at the example from the routing page more closely. We'll flesh out
|
||||
the handler so that we end up with something like the following:
|
||||
|
||||
```ts
|
||||
import { HandlerContext, RouteConfig } from "$fresh/server.ts";
|
||||
|
||||
export const handler = {
|
||||
GET(_req: Request, { params }: HandlerContext) {
|
||||
console.log(params);
|
||||
return new Response(params.path);
|
||||
},
|
||||
};
|
||||
|
||||
export const config: RouteConfig = {
|
||||
routeOverride: "/x/:module@:version/:path*",
|
||||
};
|
||||
```
|
||||
|
||||
Now if we hit the server with a request like
|
||||
`http://localhost:8000/x/bestModule@1.33.7/asdf`, then logging the params will
|
||||
show the following:
|
||||
|
||||
```
|
||||
{
|
||||
module: "bestModule",
|
||||
version: "1.33.7",
|
||||
path: "asdf"
|
||||
}
|
||||
```
|
||||
|
||||
## Complex Route Config
|
||||
|
||||
Let's look at something a bit more complex:
|
||||
|
||||
```ts
|
||||
import { HandlerContext, RouteConfig } from "$fresh/server.ts";
|
||||
|
||||
export const handler = {
|
||||
GET(_req: Request, { params }: HandlerContext) {
|
||||
console.log(params);
|
||||
return new Response(params.path);
|
||||
},
|
||||
};
|
||||
|
||||
export const config: RouteConfig = {
|
||||
routeOverride: "/api/db/:resource(jobs?|bar)/:id(\\d+)?",
|
||||
};
|
||||
```
|
||||
|
||||
Values are available via `params.resource` and `params.id`.
|
||||
|
||||
Here are some example URLs that match this:
|
||||
|
||||
- /api/db/bar/1
|
||||
- /api/db/jobs/1
|
||||
- /api/db/job/1
|
||||
- /api/db/job
|
||||
- /api/db/jobs
|
||||
- /api/db/bar
|
||||
|
||||
Here are some that don't:
|
||||
|
||||
- /api/db/other/123
|
||||
- /api/db/jobs/abc
|
||||
- /api/db
|
||||
|
||||
## Regex
|
||||
|
||||
At this point is should be clear that this is essentially an exercise in
|
||||
understanding regex. There are [numerous](https://regexr.com/)
|
||||
[resources](https://regex101.com/) [available](https://chat.openai.com/) for
|
||||
getting assistance with regex.
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
description: |
|
||||
In this chapter of the Fresh documentation, you can find examples of features that you may like in your Fresh project.
|
||||
---
|
||||
|
||||
In this chapter of the Fresh documentation, you can find examples of features
|
||||
that you may like in your Fresh project. If there's a specific example you'd
|
||||
like to see here, please open
|
||||
[a GitHub discussion](https://github.com/denoland/fresh/discussions/new?category=ideas).
|
||||
|
||||
- [Modifying the `<head>`](./examples/modifying-the-head)
|
||||
- [Setting the language](./examples/setting-the-language)
|
||||
- [Writing tests](./examples/writing-tests)
|
||||
- [Changing the source directory](./examples/changing-the-src-dir)
|
||||
- [Initializing the server](./examples/init-the-server)
|
||||
- [Using Fresh canary version](./examples/using-fresh-canary-version)
|
||||
- [Dealing with CORS](./examples/dealing-with-cors)
|
||||
- [Creating a CRUD API](./examples/creating-a-crud-api)
|
||||
- [Handling complex routes](./examples/handling-complex-routes)
|
||||
- [Rendering markdown](./examples/rendering-markdown)
|
||||
- [Sharing state between islands](./examples/sharing-state-between-islands)
|
||||
- [Using Deno KV Oauth](./examples/using-deno-kv-oauth)
|
||||
- [Using CSP](./examples/using-csp)
|
||||
@@ -0,0 +1,79 @@
|
||||
---
|
||||
description: |
|
||||
For when you have some complicated setup that needs to be performed once.
|
||||
---
|
||||
|
||||
Let's pretend you've just initialized a new Fresh project. You want to do some
|
||||
complicated setup that runs once, before the server is started. This is,
|
||||
fortunately, quite easy. Here's how:
|
||||
|
||||
```diff
|
||||
import { start } from "$fresh/server.ts";
|
||||
import manifest from "./fresh.gen.ts";
|
||||
+import { Context } from "./routes/_middleware.ts";
|
||||
|
||||
+await Context.init();
|
||||
await start(manifest);
|
||||
```
|
||||
|
||||
So your full `main.ts` should look like this:
|
||||
|
||||
```ts
|
||||
/// <reference no-default-lib="true" />
|
||||
/// <reference lib="dom" />
|
||||
/// <reference lib="dom.iterable" />
|
||||
/// <reference lib="dom.asynciterable" />
|
||||
/// <reference lib="deno.ns" />
|
||||
|
||||
import "$std/dotenv/load.ts";
|
||||
|
||||
import { start } from "$fresh/server.ts";
|
||||
import manifest from "./fresh.gen.ts";
|
||||
import { Context } from "./routes/_middleware.ts";
|
||||
|
||||
await Context.init();
|
||||
await start(manifest);
|
||||
```
|
||||
|
||||
But what's going on in this new `_middleware.ts` we've created?
|
||||
|
||||
```ts
|
||||
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||
|
||||
export interface State {
|
||||
context: Context;
|
||||
}
|
||||
|
||||
export class Context {
|
||||
private static context: Context;
|
||||
private complicatedStartupValue: number;
|
||||
|
||||
public constructor() {
|
||||
// presumably this involves connecting to a
|
||||
// database or doing some heavy computation
|
||||
this.complicatedStartupValue = 42;
|
||||
}
|
||||
|
||||
public static async init() {
|
||||
Context.context = new Context();
|
||||
}
|
||||
|
||||
public static instance() {
|
||||
if (this.context) return this.context;
|
||||
else throw new Error("Context is not initialized!");
|
||||
}
|
||||
}
|
||||
|
||||
export async function handler(
|
||||
req: Request,
|
||||
ctx: MiddlewareHandlerContext<State>,
|
||||
) {
|
||||
ctx.state.context = Context.instance();
|
||||
const resp = await ctx.next();
|
||||
return resp;
|
||||
}
|
||||
```
|
||||
|
||||
So now in this `handler` (or any other `handler` functions you create) you can
|
||||
have access to the complicated initialization step by calling
|
||||
`Context.instance()`.
|
||||
@@ -0,0 +1,40 @@
|
||||
---
|
||||
description: |
|
||||
Add components like <title> or <meta> to a <head> tag using Fresh's <Head> component.
|
||||
---
|
||||
|
||||
We can use the `<Head />` component in `$fresh/runtime.ts` to add elements as
|
||||
children of the `<head>` element. By adding elements as children of Fresh's
|
||||
`<Head />` tag, these automatically get injected into the `<head>` element of
|
||||
the web page. Some uses include:
|
||||
|
||||
- Setting the document title using `<title>`
|
||||
- Specifying page metadata using `<meta>`
|
||||
- Linking to resources like stylesheets using `<link>`
|
||||
- Including third-party JavaScript code using `<script>`
|
||||
|
||||
```tsx
|
||||
// routes/index.tsx
|
||||
import { Head } from "$fresh/runtime.ts";
|
||||
import Counter from "../islands/Counter.tsx";
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Fresh App</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="This is a brief description of Fresh"
|
||||
/>
|
||||
<link rel="stylesheet" href="styles.css" />
|
||||
<script src="script.js"></script>
|
||||
</Head>
|
||||
<div class="p-4 mx-auto max-w-screen-md">
|
||||
<h1>Hello World</h1>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,101 @@
|
||||
---
|
||||
description: |
|
||||
How to render markdown on your Fresh site.
|
||||
---
|
||||
|
||||
What if you want to render some markdown on your site? There are a few
|
||||
possibilities:
|
||||
|
||||
1. the markdown is coming from a remote source
|
||||
2. the markdown is defined in a string
|
||||
3. the markdown is on a file
|
||||
|
||||
The following file uses
|
||||
[dynamic routing](https://fresh.deno.dev/docs/getting-started/dynamic-routes) to
|
||||
handle the three cases. It's assumed this file is called `[slug].tsx`:
|
||||
|
||||
```ts
|
||||
// routes/[slug].tsx
|
||||
import { Handlers, PageProps } from "$fresh/server.ts";
|
||||
import { extract } from "$std/front_matter/yaml.ts";
|
||||
import { CSS, render } from "$gfm";
|
||||
import { Head } from "$fresh/runtime.ts";
|
||||
|
||||
interface Page {
|
||||
markdown: string;
|
||||
data: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export const handler: Handlers<Page> = {
|
||||
async GET(_req, ctx) {
|
||||
let rawMarkdown = "";
|
||||
if (ctx.params.slug === "remote") {
|
||||
const resp = await fetch(
|
||||
`https://raw.githubusercontent.com/denoland/fresh/main/docs/introduction/index.md`,
|
||||
);
|
||||
if (resp.status !== 200) {
|
||||
return ctx.render(undefined);
|
||||
}
|
||||
rawMarkdown = await resp.text();
|
||||
} else if (ctx.params.slug === "string") {
|
||||
rawMarkdown = `---
|
||||
description: test
|
||||
---
|
||||
|
||||
## big text
|
||||
|
||||
Look, it's working. _This is in italics._
|
||||
|
||||
`;
|
||||
} else if (ctx.params.slug === "file") {
|
||||
rawMarkdown = await Deno.readTextFile("text.md");
|
||||
} else {
|
||||
return ctx.render(undefined);
|
||||
}
|
||||
const { attrs, body } = extract(rawMarkdown);
|
||||
return ctx.render({ markdown: body, data: attrs });
|
||||
},
|
||||
};
|
||||
|
||||
export default function MarkdownPage({ data }: PageProps<Page | null>) {
|
||||
if (!data) {
|
||||
return <h1>File not found.</h1>;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<style dangerouslySetInnerHTML={{ __html: CSS }} />
|
||||
</Head>
|
||||
<main>
|
||||
<div>{JSON.stringify(data.data)}</div>
|
||||
<div
|
||||
class="markdown-body"
|
||||
dangerouslySetInnerHTML={{ __html: render(data?.markdown) }}
|
||||
/>
|
||||
</main>
|
||||
</>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The contents of the `text.md` file are the following:
|
||||
|
||||
```md
|
||||
---
|
||||
description: testFromText
|
||||
---
|
||||
|
||||
# Really Big Text
|
||||
|
||||
**bold**
|
||||
```
|
||||
|
||||
You'll also need to import the `Github Flavored Markdown` module:
|
||||
|
||||
```json
|
||||
"$gfm": "https://deno.land/x/gfm@0.2.3/mod.ts",
|
||||
```
|
||||
|
||||
Andy has a helpful [post](https://deno.com/blog/build-a-blog-with-fresh) on the
|
||||
Deno Blog which goes into a slightly more realistic example.
|
||||
@@ -0,0 +1,52 @@
|
||||
---
|
||||
description: |
|
||||
Set the lang attribute in the <html> tag.
|
||||
---
|
||||
|
||||
When you initialize a project with `deno run -A -r https://fresh.deno.dev`,
|
||||
you'll end up with a `main.ts` like the following:
|
||||
|
||||
```ts
|
||||
/// <reference no-default-lib="true" />
|
||||
/// <reference lib="dom" />
|
||||
/// <reference lib="dom.iterable" />
|
||||
/// <reference lib="dom.asynciterable" />
|
||||
/// <reference lib="deno.ns" />
|
||||
|
||||
import { start } from "$fresh/server.ts";
|
||||
import manifest from "./fresh.gen.ts";
|
||||
|
||||
import twindPlugin from "$fresh/plugins/twind.ts";
|
||||
import twindConfig from "./twind.config.ts";
|
||||
|
||||
await start(manifest, { plugins: [twindPlugin(twindConfig)] });
|
||||
```
|
||||
|
||||
This is a great start if your site is in English, but let's say you want to
|
||||
change the language, as per the `<html lang=asdf>` tag. Then you'll need to do
|
||||
something like this:
|
||||
|
||||
```ts
|
||||
/// <reference no-default-lib="true" />
|
||||
/// <reference lib="dom" />
|
||||
/// <reference lib="dom.iterable" />
|
||||
/// <reference lib="dom.asynciterable" />
|
||||
/// <reference lib="deno.ns" />
|
||||
|
||||
import { start } from "$fresh/server.ts";
|
||||
import manifest from "./fresh.gen.ts";
|
||||
|
||||
import twindPlugin from "$fresh/plugins/twind.ts";
|
||||
import twindConfig from "./twind.config.ts";
|
||||
|
||||
await start(manifest, {
|
||||
plugins: [twindPlugin(twindConfig)],
|
||||
render: (ctx, render) => {
|
||||
ctx.lang = "de";
|
||||
render();
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
If you're curious how this works, start by checking out `TemplateOptions` in
|
||||
`render.ts`.
|
||||
@@ -0,0 +1,195 @@
|
||||
---
|
||||
description: |
|
||||
When you need to have state shared between islands, this page provides a few recipes.
|
||||
---
|
||||
|
||||
All of this content is lifted from this great
|
||||
[example](https://fresh-with-signals.deno.dev/) by Luca. The source can be found
|
||||
[here](https://github.com/lucacasonato/fresh-with-signals).
|
||||
|
||||
## Multiple Sibling Islands with Independent State
|
||||
|
||||
Imagine we have `Counter.tsx` like this:
|
||||
|
||||
```ts
|
||||
// islands/Counter.tsx
|
||||
import { useSignal } from "@preact/signals";
|
||||
import { Button } from "../components/Button.tsx";
|
||||
|
||||
interface CounterProps {
|
||||
start: number;
|
||||
}
|
||||
|
||||
// This island is used to display a counter and increment/decrement it. The
|
||||
// state for the counter is stored locally in this island.
|
||||
export default function Counter(props: CounterProps) {
|
||||
const count = useSignal(props.start);
|
||||
return (
|
||||
<div class="flex gap-2 items-center w-full">
|
||||
<p class="flex-grow-1 font-bold text-xl">{count}</p>
|
||||
<Button onClick={() => count.value--}>-1</Button>
|
||||
<Button onClick={() => count.value++}>+1</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Note how `useSignal` is within the `Counter` component. Then if we instantiate
|
||||
some counters like this...
|
||||
|
||||
```ts
|
||||
<Counter start={3} />
|
||||
<Counter start={4} />
|
||||
```
|
||||
|
||||
they'll keep track of their own independent state. Not much sharing going on
|
||||
here, yet.
|
||||
|
||||
## Multiple Sibling Islands with Shared State
|
||||
|
||||
But we can switch things up by looking at a `SynchronizedSlider.tsx` like this:
|
||||
|
||||
```ts
|
||||
// islands/SynchronizedSlider.tsx
|
||||
import { Signal } from "@preact/signals";
|
||||
|
||||
interface SliderProps {
|
||||
slider: Signal<number>;
|
||||
}
|
||||
|
||||
// This island displays a slider with a value equal to the `slider` signal's
|
||||
// value. When the slider is moved, the `slider` signal is updated.
|
||||
export default function SynchronizedSlider(props: SliderProps) {
|
||||
return (
|
||||
<input
|
||||
class="w-full"
|
||||
type="range"
|
||||
min={1}
|
||||
max={100}
|
||||
value={props.slider.value}
|
||||
onInput={(e) => props.slider.value = Number(e.currentTarget.value)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Now if we were to do the following...
|
||||
|
||||
```ts
|
||||
// routes/index.tsx
|
||||
export default function Home() {
|
||||
const sliderSignal = useSignal(50);
|
||||
return (
|
||||
<div>
|
||||
<SynchronizedSlider slider={sliderSignal} />
|
||||
<SynchronizedSlider slider={sliderSignal} />
|
||||
<SynchronizedSlider slider={sliderSignal} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
they would all use the same value.
|
||||
|
||||
## Independent Islands
|
||||
|
||||
We can also create a `signal` in a utility file and export it for consumption
|
||||
across multiple places.
|
||||
|
||||
```ts
|
||||
// utils/cart.ts
|
||||
import { signal } from "@preact/signals";
|
||||
|
||||
export const cart = signal<string[]>([]);
|
||||
```
|
||||
|
||||
```ts
|
||||
// islands/AddToCart.tsx
|
||||
import { Button } from "../components/Button.tsx";
|
||||
import { cart } from "../utils/cart.ts";
|
||||
|
||||
interface AddToCartProps {
|
||||
product: string;
|
||||
}
|
||||
|
||||
// This island is used to add a product to the cart state.
|
||||
export default function AddToCart(props: AddToCartProps) {
|
||||
return (
|
||||
<Button
|
||||
onClick={() => cart.value = [...cart.value, props.product]}
|
||||
class="w-full"
|
||||
>
|
||||
Add{cart.value.includes(props.product) ? " another" : ""}{" "}
|
||||
"{props.product}" to cart
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
```ts
|
||||
// islands/Cart.tsx
|
||||
import { Button } from "../components/Button.tsx";
|
||||
import { cart } from "../utils/cart.ts";
|
||||
import * as icons from "../components/Icons.tsx";
|
||||
|
||||
// This island is used to display the cart contents and remove items from it.
|
||||
export default function Cart() {
|
||||
return (
|
||||
<h1 class="text-xl flex items-center justify-center">
|
||||
Cart
|
||||
</h1>
|
||||
|
||||
<ul class="w-full bg-gray-50 mt-2 p-2 rounded min-h-[6.5rem]">
|
||||
{cart.value.length === 0 && (
|
||||
<li class="text-center my-4">
|
||||
<div class="text-gray-400">
|
||||
<icons.Cart class="w-8 h-8 inline-block" />
|
||||
<div>
|
||||
Your cart is empty.
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
)}
|
||||
{cart.value.map((product, index) => (
|
||||
<CartItem product={product} index={index} />
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
interface CartItemProps {
|
||||
product: string;
|
||||
index: number;
|
||||
}
|
||||
|
||||
function CartItem(props: CartItemProps) {
|
||||
const remove = () => {
|
||||
const newCart = [...cart.value];
|
||||
newCart.splice(props.index, 1);
|
||||
cart.value = newCart;
|
||||
};
|
||||
|
||||
return (
|
||||
<li class="flex items-center justify-between gap-1">
|
||||
<icons.Lemon class="text-gray-500" />
|
||||
<div class="flex-1">
|
||||
{props.product}
|
||||
</div>
|
||||
<Button onClick={remove} aria-label="Remove" class="border-none">
|
||||
<icons.X class="inline-block w-4 h-4" />
|
||||
</Button>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Now we can add the islands to our site by doing the following:
|
||||
|
||||
```ts
|
||||
<AddToCart product="Lemon" />
|
||||
<AddToCart product="Lime" />
|
||||
<Cart />
|
||||
```
|
||||
|
||||
What happens as a result? The `cart` signal is shared across the two `AddToCart`
|
||||
islands _and_ the `Cart` island.
|
||||
@@ -0,0 +1,383 @@
|
||||
---
|
||||
description: |
|
||||
Change the source directory to effectively manage your project.
|
||||
---
|
||||
|
||||
As per the
|
||||
[MDN documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP):
|
||||
|
||||
> Content Security Policy (CSP) is an added layer of security that helps to
|
||||
> detect and mitigate certain types of attacks, including Cross-Site Scripting
|
||||
> (XSS) and data injection attacks. These attacks are used for everything from
|
||||
> data theft, to site defacement, to malware distribution.
|
||||
>
|
||||
> To enable CSP, you need to configure your web server to return the
|
||||
> Content-Security-Policy HTTP header. (Sometimes you may see mentions of the
|
||||
> X-Content-Security-Policy header, but that's an older version and you don't
|
||||
> need to specify it anymore.)
|
||||
|
||||
Fortunately Fresh has built in support for CSP. We don't need to worry about
|
||||
setting headers ourselves. We just have to configure our routes correctly. Let's
|
||||
dive into a few examples to see how this works.
|
||||
|
||||
Fresh's CSP implementation supports the following
|
||||
|
||||
<details>
|
||||
<summary>directives</summary>
|
||||
|
||||
```ts
|
||||
export interface ContentSecurityPolicyDirectives {
|
||||
// Fetch directives
|
||||
/**
|
||||
* Defines the valid sources for web workers and nested browsing contexts
|
||||
* loaded using elements such as <frame> and <iframe>.
|
||||
*/
|
||||
childSrc?: string[];
|
||||
/**
|
||||
* Restricts the URLs which can be loaded using script interfaces.
|
||||
*/
|
||||
connectSrc?: string[];
|
||||
/**
|
||||
* Serves as a fallback for the other fetch directives.
|
||||
*/
|
||||
defaultSrc?: string[];
|
||||
/**
|
||||
* Specifies valid sources for fonts loaded using @font-face.
|
||||
*/
|
||||
fontSrc?: string[];
|
||||
/**
|
||||
* Specifies valid sources for nested browsing contexts loading using elements
|
||||
* such as <frame> and <iframe>.
|
||||
*/
|
||||
frameSrc?: string[];
|
||||
/**
|
||||
* Specifies valid sources of images and favicons.
|
||||
*/
|
||||
imgSrc?: string[];
|
||||
/**
|
||||
* Specifies valid sources of application manifest files.
|
||||
*/
|
||||
manifestSrc?: string[];
|
||||
/**
|
||||
* Specifies valid sources for loading media using the <audio> , <video> and
|
||||
* <track> elements.
|
||||
*/
|
||||
mediaSrc?: string[];
|
||||
/**
|
||||
* Specifies valid sources for the <object>, <embed>, and <applet> elements.
|
||||
*/
|
||||
objectSrc?: string[];
|
||||
/**
|
||||
* Specifies valid sources to be prefetched or prerendered.
|
||||
*/
|
||||
prefetchSrc?: string[];
|
||||
/**
|
||||
* Specifies valid sources for JavaScript.
|
||||
*/
|
||||
scriptSrc?: string[];
|
||||
/**
|
||||
* Specifies valid sources for JavaScript <script> elements.
|
||||
*/
|
||||
scriptSrcElem?: string[];
|
||||
/**
|
||||
* Specifies valid sources for JavaScript inline event handlers.
|
||||
*/
|
||||
scriptSrcAttr?: string[];
|
||||
/**
|
||||
* Specifies valid sources for stylesheets.
|
||||
*/
|
||||
styleSrc?: string[];
|
||||
/**
|
||||
* Specifies valid sources for stylesheets <style> elements and <link>
|
||||
* elements with rel="stylesheet".
|
||||
*/
|
||||
styleSrcElem?: string[];
|
||||
/**
|
||||
* Specifies valid sources for inline styles applied to individual DOM
|
||||
* elements.
|
||||
*/
|
||||
styleSrcAttr?: string[];
|
||||
/**
|
||||
* Specifies valid sources for Worker, SharedWorker, or ServiceWorker scripts.
|
||||
*/
|
||||
workerSrc?: string[];
|
||||
|
||||
// Document directives
|
||||
/**
|
||||
* Restricts the URLs which can be used in a document's <base> element.
|
||||
*/
|
||||
baseUri?: string[];
|
||||
/**
|
||||
* Enables a sandbox for the requested resource similar to the <iframe>
|
||||
* sandbox attribute.
|
||||
*/
|
||||
sandbox?: string[];
|
||||
|
||||
// Navigation directives
|
||||
/**
|
||||
* Restricts the URLs which can be used as the target of a form submissions
|
||||
* from a given context.
|
||||
*/
|
||||
formAction?: string[];
|
||||
/**
|
||||
* Specifies valid parents that may embed a page using <frame>, <iframe>,
|
||||
* <object>, <embed>, or <applet>.
|
||||
*/
|
||||
frameAncestors?: string[];
|
||||
/**
|
||||
* Restricts the URLs to which a document can initiate navigation by any
|
||||
* means, including <form> (if form-action is not specified), <a>,
|
||||
* window.location, window.open, etc.
|
||||
*/
|
||||
navigateTo?: string[];
|
||||
|
||||
/**
|
||||
* The URI to report CSP violations to.
|
||||
*/
|
||||
reportUri?: string;
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
For our examples, we'll just be focused on `styleSrc`, but the technique can be
|
||||
applied to any of the directives.
|
||||
|
||||
We'll start off by having an example stylesheet defined like this:
|
||||
|
||||
```css
|
||||
/* static/example.css */
|
||||
h1 {
|
||||
font-size: 25px;
|
||||
font-weight: normal;
|
||||
margin-top: 5px;
|
||||
margin-left: 25px;
|
||||
}
|
||||
```
|
||||
|
||||
## No CSP
|
||||
|
||||
To kick things off, we'll create the following control route which doesn't do
|
||||
anything with CSP. We include a stylesheet to confirm that our sheet correctly
|
||||
styles the response.
|
||||
|
||||
```tsx
|
||||
// routes/noCSP.tsx
|
||||
import { RouteContext } from "$fresh/server.ts";
|
||||
|
||||
export default function Home(req: Request, ctx: RouteContext) {
|
||||
return (
|
||||
<>
|
||||
<h1>This page doesn't use CSP at all. Styles will be applied.</h1>
|
||||
<link rel="stylesheet" type="text/css" href="example.css" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
We can hit `http://localhost:8000/noCSP` and we should see the following:
|
||||
|
||||
```
|
||||
This page doesn't use CSP at all. Styles will be applied.
|
||||
```
|
||||
|
||||
## Incorrect CSP
|
||||
|
||||
Let's invoke the `useCSP` hook in our response to try to secure our page. Watch
|
||||
closely, we're using the wrong URL! This will cause the browser to reject the
|
||||
stylesheet, due to the header that Fresh produces. We get a `(blocked:csp)`
|
||||
status when the browser tries to request this resource.
|
||||
|
||||
```tsx
|
||||
// routes/incorrectCSP.tsx
|
||||
import { RouteConfig, RouteContext } from "$fresh/server.ts";
|
||||
import { useCSP } from "$fresh/runtime.ts";
|
||||
|
||||
export default function Home(req: Request, ctx: RouteContext) {
|
||||
useCSP((csp) => {
|
||||
if (!csp.directives.styleSrc) {
|
||||
csp.directives.styleSrc = [];
|
||||
}
|
||||
csp.directives.styleSrc.push(
|
||||
"http://www.example.com",
|
||||
);
|
||||
});
|
||||
return (
|
||||
<>
|
||||
<h1>This page violates our configured CSP. Styles won't be applied.</h1>
|
||||
<link rel="stylesheet" type="text/css" href="example.css" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export const config: RouteConfig = {
|
||||
csp: true,
|
||||
};
|
||||
```
|
||||
|
||||
We can hit `http://localhost:8000/incorrectCSP` and we should see the following:
|
||||
|
||||
```
|
||||
This page violates our configured CSP. Styles won't be applied.
|
||||
```
|
||||
|
||||
## Correct CSP
|
||||
|
||||
Let's fix our simple mistake and use the correct URL. Everything is working
|
||||
correctly here.
|
||||
|
||||
```tsx
|
||||
// routes/correctCSP.tsx
|
||||
import { RouteConfig, RouteContext } from "$fresh/server.ts";
|
||||
import { useCSP } from "$fresh/runtime.ts";
|
||||
|
||||
export default function Home(req: Request, ctx: RouteContext) {
|
||||
useCSP((csp) => {
|
||||
if (!csp.directives.styleSrc) {
|
||||
csp.directives.styleSrc = [];
|
||||
}
|
||||
csp.directives.styleSrc.push(
|
||||
"http://localhost:8000/example.css",
|
||||
);
|
||||
});
|
||||
return (
|
||||
<>
|
||||
<h1>This page adheres to our configured CSP. Styles will be applied.</h1>
|
||||
<link rel="stylesheet" type="text/css" href="example.css" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export const config: RouteConfig = {
|
||||
csp: true,
|
||||
};
|
||||
```
|
||||
|
||||
We can hit `http://localhost:8000/correctCSP` and we should see the following:
|
||||
|
||||
```
|
||||
This page adheres to our configured CSP. Styles will be applied.
|
||||
```
|
||||
|
||||
## No Route Config
|
||||
|
||||
What happens if we forget to use a `RouteConfig` in our route?
|
||||
|
||||
```tsx
|
||||
// routes/cspNoRouteConfig.tsx
|
||||
import { RouteContext } from "$fresh/server.ts";
|
||||
import { useCSP } from "$fresh/runtime.ts";
|
||||
|
||||
export default function Home(req: Request, ctx: RouteContext) {
|
||||
useCSP((csp) => {
|
||||
if (!csp.directives.styleSrc) {
|
||||
csp.directives.styleSrc = [];
|
||||
}
|
||||
csp.directives.styleSrc.push(
|
||||
"http://www.example.com",
|
||||
);
|
||||
});
|
||||
return (
|
||||
<>
|
||||
<h1>
|
||||
This page violates our configured CSP. But we don't have a{" "}
|
||||
<code>RouteConfig</code>{" "}
|
||||
enabled, so Fresh doesn't know to use the CSP. Styles will be applied.
|
||||
</h1>
|
||||
<link rel="stylesheet" type="text/css" href="example.css" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
We can hit `http://localhost:8000/cspNoRouteConfig` and we should see the
|
||||
following:
|
||||
|
||||
```
|
||||
This page violates our configured CSP. But we don't have a RouteConfig enabled, so Fresh doesn't know to use the CSP. Styles will be applied.
|
||||
```
|
||||
|
||||
## Reporting
|
||||
|
||||
Let's touch on the reporting aspect of CSP. CSP (and Fresh's framework) support
|
||||
a `reportOnly` flag and a `reportUri` endpoint. This is a destination that
|
||||
should be able to receive `POST` requests. If the `reportOnly` flag is enabled,
|
||||
then the browser will ignore the CSP headers and log any issues to the
|
||||
`reportUri` destination.
|
||||
|
||||
```tsx
|
||||
// routes/incorrectCSPwithReport.tsx
|
||||
import { RouteConfig, RouteContext } from "$fresh/server.ts";
|
||||
import { useCSP } from "$fresh/runtime.ts";
|
||||
|
||||
export default function Home(req: Request, ctx: RouteContext) {
|
||||
useCSP((csp) => {
|
||||
csp.reportOnly = true;
|
||||
if (!csp.directives.styleSrc) {
|
||||
csp.directives.styleSrc = [];
|
||||
}
|
||||
csp.directives.reportUri = "http://localhost:8000/reportHandler";
|
||||
csp.directives.styleSrc.push(
|
||||
"http://www.example.com",
|
||||
);
|
||||
});
|
||||
return (
|
||||
<>
|
||||
<h1>
|
||||
This page violates our configured CSP. But we're using "reportOnly".
|
||||
Styles will be applied.
|
||||
</h1>
|
||||
<link rel="stylesheet" type="text/css" href="example.css" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export const config: RouteConfig = {
|
||||
csp: true,
|
||||
};
|
||||
```
|
||||
|
||||
```ts
|
||||
// routes/reportHandler.ts
|
||||
import { HandlerContext } from "$fresh/server.ts";
|
||||
|
||||
export const handler = {
|
||||
async POST(req: Request, _ctx: HandlerContext) {
|
||||
const body = await req.json();
|
||||
const report = JSON.stringify(body, null, 2);
|
||||
|
||||
await Deno.writeTextFile("./csp-reports.txt", report + "\n", {
|
||||
append: true,
|
||||
});
|
||||
return new Response(null, { status: 200 });
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
We can hit `http://localhost:8000/incorrectCSPwithReport` and we should see the
|
||||
following:
|
||||
|
||||
```
|
||||
This page violates our configured CSP. But we're using "reportOnly". Styles will be applied.
|
||||
```
|
||||
|
||||
We can then check our server and we'll see that `csp-reports.txt` has an entry
|
||||
like this:
|
||||
|
||||
```json
|
||||
{
|
||||
"csp-report": {
|
||||
"document-uri": "http://localhost:8000/incorrectCSPwithReport",
|
||||
"referrer": "http://localhost:8000/incorrectCSPwithReport",
|
||||
"violated-directive": "style-src-elem",
|
||||
"effective-directive": "style-src-elem",
|
||||
"original-policy": "default-src 'none'; style-src 'unsafe-inline' http://www.example.com; report-uri http://localhost:8000/reportHandler; script-src 'nonce-0f2d8259315d40479e8c21979128ac0d'; connect-src 'self'",
|
||||
"disposition": "report",
|
||||
"blocked-uri": "http://localhost:8000/example.css",
|
||||
"line-number": 37,
|
||||
"source-file": "http://localhost:8000/incorrectCSPwithReport",
|
||||
"status-code": 200,
|
||||
"script-sample": ""
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,146 @@
|
||||
---
|
||||
description: Easily integrate OAuth 2.0 to your Fresh project with Deno KV OAuth.
|
||||
---
|
||||
|
||||
> ⚠️ Please note that this functionality relies on
|
||||
> [Deno KV](https://deno.com/manual/runtime/kv) which is currently marked as
|
||||
> **experimental** and is **subject to change**. It is only available when using
|
||||
> the `--unstable` flag.
|
||||
|
||||
> ⚠️ Please note that Deno KV OAuth is still in **beta** and is **subject to
|
||||
> change**. See [the documentation](https://deno.land/x/deno_kv_oauth) for
|
||||
> further details.
|
||||
|
||||
## Getting Started
|
||||
|
||||
This example uses GitHub as the OAuth 2.0 provider. However there is a suite of
|
||||
[pre-configured providers](https://deno.land/x/deno_kv_oauth#pre-configured-oauth-20-clients)
|
||||
available.
|
||||
|
||||
1. Register a [new GitHub OAuth](https://github.com/settings/applications/new)
|
||||
application, if you haven't already.
|
||||
2. Create your pre-configured OAuth client instance. For reusability the
|
||||
instance is stored in `utils/oauth2_client.ts`.
|
||||
|
||||
```ts
|
||||
// utils/oauth2_client.ts
|
||||
import { createGitHubOAuth2Client } from "https://deno.land/x/deno_kv_oauth@v0.2.4/mod.ts";
|
||||
|
||||
export const oauth2Client = createGitHubOAuth2Client();
|
||||
```
|
||||
|
||||
3. Using the OAuth 2.0 client instance, insert the authentication flow functions
|
||||
into your authentication routes. In this example, there are dedicated handler
|
||||
routes at `routes/signin.ts`, `routes/signout.ts` and `routes/callback.ts`.
|
||||
Please ensure that the `callback` handler matches the authorization callback
|
||||
URL in the configured OAuth application.
|
||||
|
||||
```ts
|
||||
// routes/signin.ts
|
||||
import { Handlers } from "$fresh/server.ts";
|
||||
import { signIn } from "https://deno.land/x/deno_kv_oauth@v0.2.4/mod.ts";
|
||||
import { oauth2Client } from "../utils/oauth2_client.ts";
|
||||
|
||||
export const handler: Handlers = {
|
||||
async GET(req) {
|
||||
return await signIn(req, oauth2Client);
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
```ts
|
||||
// routes/signout.ts
|
||||
import { Handlers } from "$fresh/server.ts";
|
||||
import { signOut } from "https://deno.land/x/deno_kv_oauth@v0.2.4/mod.ts";
|
||||
|
||||
export const handler: Handlers = {
|
||||
async GET(req) {
|
||||
return await signOut(req);
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
```ts
|
||||
// routes/callback.ts
|
||||
import { Handlers } from "$fresh/server.ts";
|
||||
import { handleCallback } from "https://deno.land/x/deno_kv_oauth@v0.2.4/mod.ts";
|
||||
import { oauth2Client } from "../utils/oauth2_client.ts";
|
||||
|
||||
export const handler: Handlers = {
|
||||
async GET(req) {
|
||||
// Return object also includes `accessToken` and `sessionId` properties.
|
||||
const { response } = await handleCallback(req, oauth2Client);
|
||||
return response;
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
4. Use Deno KV OAuth's helper functions where needed.
|
||||
|
||||
```tsx
|
||||
// routes/index.tsx
|
||||
import { Handlers, PageProps } from "$fresh/server.ts";
|
||||
import {
|
||||
getSessionAccessToken,
|
||||
getSessionId,
|
||||
} from "https://deno.land/x/deno_kv_oauth@v0.2.4/mod.ts";
|
||||
import { oauth2Client } from "../utils/oauth2_client.ts";
|
||||
|
||||
interface User {
|
||||
login: string;
|
||||
name: string;
|
||||
avatar_url: string;
|
||||
}
|
||||
|
||||
export const handler: Handlers<User | null> = {
|
||||
async GET(req, ctx) {
|
||||
const sessionId = await getSessionId(req);
|
||||
|
||||
if (!sessionId) {
|
||||
return ctx.render(null);
|
||||
}
|
||||
|
||||
const accessToken = await getSessionAccessToken(oauth2Client, sessionId);
|
||||
const response = await fetch("https://api.github.com/user", {
|
||||
headers: {
|
||||
authorization: `bearer ${accessToken}`,
|
||||
},
|
||||
});
|
||||
const user: User = await response.json();
|
||||
return ctx.render(user);
|
||||
},
|
||||
};
|
||||
|
||||
export default function Page({ data }: PageProps<User | null>) {
|
||||
if (!data) {
|
||||
return <a href="/signin">Sign In</a>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<img src={data.avatar_url} width={64} height={64} />
|
||||
<h1>{data.name}</h1>
|
||||
<p>{data.login}</p>
|
||||
<a href="/signout">Sign Out</a>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
5. Start your project with the necessary environment variables.
|
||||
|
||||
```sh
|
||||
GITHUB_CLIENT_ID=xxx GITHUB_CLIENT_SECRET=xxx deno task start
|
||||
```
|
||||
|
||||
## More on Deno KV OAuth
|
||||
|
||||
Follow the links to read more about:
|
||||
|
||||
- Using a provider from the list of
|
||||
[pre-configured providers](https://deno.land/x/deno_kv_oauth#pre-configured-oauth-20-clients)
|
||||
- Configuring a
|
||||
[custom OAuth 2.0 client](https://deno.land/x/deno_kv_oauth#custom-oauth-20-client)
|
||||
- Setting the mandatory
|
||||
[environment variables](https://deno.land/x/deno_kv_oauth#environment-variables)
|
||||
- Exploring a [live demo](https://fresh-deno-kv-oauth-demo.deno.dev/)
|
||||
@@ -0,0 +1,78 @@
|
||||
---
|
||||
description: |
|
||||
For cases where the latest release doesn't fit your needs.
|
||||
---
|
||||
|
||||
Pretend you have a use case where you need to modify your project to use a
|
||||
canary version of Fresh. Or you want to use a slightly different initialization
|
||||
script. This page has you covered.
|
||||
|
||||
## Canary Fresh in `deno.json`
|
||||
|
||||
### Specific commit
|
||||
|
||||
Let's say you like living life in the fast lane, and want a particular commit.
|
||||
How can you modify your project to no longer use the current release, but
|
||||
instead this one particular commit? Just make the following changes to your
|
||||
`deno.json`:
|
||||
|
||||
```diff
|
||||
"update": "deno run -A -r https://fresh.deno.dev/update ."
|
||||
},
|
||||
"imports": {
|
||||
- "$fresh/": "https://deno.land/x/fresh@1.2.0/",
|
||||
+ "$fresh/": "https://raw.githubusercontent.com/denoland/fresh/the-particular-commit-hash-here/",
|
||||
"preact": "https://esm.sh/preact@10.15.1",
|
||||
"preact/": "https://esm.sh/preact@10.15.1/",
|
||||
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.1.0",
|
||||
```
|
||||
|
||||
### Forked Fresh
|
||||
|
||||
Or what if you have a PR created but it's not getting merged into `main`. Don't
|
||||
worry, you can use the same approach to reference any branch in a fork as well.
|
||||
Here's an example of referencing a feature in a forked repository that hasn't
|
||||
been merged yet (at the time of writing this):
|
||||
|
||||
```diff
|
||||
"update": "deno run -A -r https://fresh.deno.dev/update ."
|
||||
},
|
||||
"imports": {
|
||||
- "$fresh/": "https://deno.land/x/fresh@1.2.0/",
|
||||
+ "$fresh/": "https://raw.githubusercontent.com/deer/fresh/state_in_props/",
|
||||
"preact": "https://esm.sh/preact@10.15.1",
|
||||
"preact/": "https://esm.sh/preact@10.15.1/",
|
||||
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.1.0",
|
||||
```
|
||||
|
||||
## Creating a new project
|
||||
|
||||
What if you're getting into open source development, and you've of course
|
||||
decided to contribute to the best, freshest project around. Maybe you want to
|
||||
create a test project based on your local changes.
|
||||
|
||||
### Creating a project from source
|
||||
|
||||
Instead of doing it like this:
|
||||
|
||||
```sh
|
||||
deno run -A -r https://fresh.deno.dev/
|
||||
```
|
||||
|
||||
do it like this:
|
||||
|
||||
```sh
|
||||
deno run -A -r path/to/fresh/init.ts
|
||||
```
|
||||
|
||||
(or wherever your local code lives)
|
||||
|
||||
### Creating a project from the latest commit
|
||||
|
||||
Of course there's no reason why you have to check out the Fresh source. You can
|
||||
create a project from the latest commit by combining the techniques on this page
|
||||
like this:
|
||||
|
||||
```sh
|
||||
deno run -A -r https://raw.githubusercontent.com/denoland/fresh/main/init.ts
|
||||
```
|
||||
@@ -0,0 +1,64 @@
|
||||
---
|
||||
description: |
|
||||
With a few tweaks one can use twind v1
|
||||
---
|
||||
|
||||
When you initialize a project with `deno run -A -r https://fresh.deno.dev`,
|
||||
you'll end up with a `main.ts` like the following:
|
||||
|
||||
```ts
|
||||
/// <reference no-default-lib="true" />
|
||||
/// <reference lib="dom" />
|
||||
/// <reference lib="dom.iterable" />
|
||||
/// <reference lib="dom.asynciterable" />
|
||||
/// <reference lib="deno.ns" />
|
||||
|
||||
import { start } from "$fresh/server.ts";
|
||||
import manifest from "./fresh.gen.ts";
|
||||
|
||||
import twindPlugin from "$fresh/plugins/twind.ts";
|
||||
import twindConfig from "./twind.config.ts";
|
||||
|
||||
await start(manifest, { plugins: [twindPlugin(twindConfig)] });
|
||||
```
|
||||
|
||||
The template generates a Twind v0 project by default. If you want to use Twind
|
||||
v1 you can follow this guide. First of all, change the import path to use the
|
||||
`twindv1` plugin:
|
||||
|
||||
```ts
|
||||
/// <reference no-default-lib="true" />
|
||||
/// <reference lib="dom" />
|
||||
/// <reference lib="dom.iterable" />
|
||||
/// <reference lib="dom.asynciterable" />
|
||||
/// <reference lib="deno.ns" />
|
||||
|
||||
import { start } from "$fresh/server.ts";
|
||||
import manifest from "./fresh.gen.ts";
|
||||
|
||||
import twindPlugin from "$fresh/plugins/twindv1.ts";
|
||||
import twindConfig from "./twind.config.ts";
|
||||
|
||||
await start(manifest, { plugins: [twindPlugin(twindConfig)] });
|
||||
```
|
||||
|
||||
The twind config object has changed significantly in v1, so we must also go
|
||||
change `twind.config.ts`. A good base looks like this:
|
||||
|
||||
```ts
|
||||
import { defineConfig, Preset } from "https://esm.sh/@twind/core@1.1.3";
|
||||
import presetTailwind from "https://esm.sh/@twind/preset-tailwind@1.1.4";
|
||||
import presetAutoprefix from "https://esm.sh/@twind/preset-autoprefix@1.0.7";
|
||||
|
||||
export default {
|
||||
...defineConfig({
|
||||
presets: [presetTailwind() as Preset, presetAutoprefix()],
|
||||
}),
|
||||
selfURL: import.meta.url,
|
||||
};
|
||||
```
|
||||
|
||||
(Note: the `as Preset` cast is required to fix a typing issue with twind.)
|
||||
|
||||
To see what other presets exist, you can go to the
|
||||
[twind docs](https://twind.style/presets).
|
||||
@@ -0,0 +1,106 @@
|
||||
---
|
||||
description: |
|
||||
You can write HTTP tests for your Fresh project by creating an application handler.
|
||||
---
|
||||
|
||||
You can write tests for your Fresh project by creating an application handler
|
||||
through
|
||||
[`createHandler()`](https://deno.land/x/fresh/server.ts?doc=&s=createHandler).
|
||||
|
||||
## 1. Create your routes
|
||||
|
||||
```tsx
|
||||
// routes/index.tsx
|
||||
|
||||
import { Handlers } from "$fresh/server.ts";
|
||||
|
||||
export const handler: Handlers = {
|
||||
async POST(req) {
|
||||
const form = await req.formData();
|
||||
|
||||
// Processing something
|
||||
|
||||
return new Response(null, {
|
||||
status: 303,
|
||||
headers: { location: "/" },
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
export default function HomePage() {
|
||||
return (
|
||||
<div>
|
||||
Hello Deno!
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
```tsx
|
||||
// routes/foo.tsx
|
||||
|
||||
export default function FooPage() {
|
||||
return (
|
||||
<div>
|
||||
Hello Foo!
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## 2. Write your tests
|
||||
|
||||
```ts
|
||||
// tests/main_test.ts
|
||||
|
||||
import { createHandler, ServeHandlerInfo } from "$fresh/server.ts";
|
||||
import manifest from "../fresh.gen.ts";
|
||||
import { assert, assertEquals } from "$std/testing/asserts.ts";
|
||||
|
||||
const CONN_INFO: ServeHandlerInfo = {
|
||||
remoteAddr: { hostname: "127.0.0.1", port: 53496, transport: "tcp" },
|
||||
};
|
||||
|
||||
Deno.test("HTTP assert test.", async (t) => {
|
||||
const handler = await createHandler(manifest);
|
||||
|
||||
await t.step("#1 GET /", async () => {
|
||||
const resp = await handler(new Request("http://127.0.0.1/"), CONN_INFO);
|
||||
assertEquals(resp.status, 200);
|
||||
});
|
||||
|
||||
await t.step("#2 POST /", async () => {
|
||||
const formData = new FormData();
|
||||
formData.append("text", "Deno!");
|
||||
const req = new Request("http://127.0.0.1/", {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
});
|
||||
const resp = await handler(req, CONN_INFO);
|
||||
assertEquals(resp.status, 303);
|
||||
});
|
||||
|
||||
await t.step("#3 GET /foo", async () => {
|
||||
const resp = await handler(
|
||||
new Request("http://127.0.0.1/foo"),
|
||||
CONN_INFO,
|
||||
);
|
||||
const text = await resp.text();
|
||||
assert(text.includes("<div>Hello Foo!</div>"));
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## 3. Run the tests
|
||||
|
||||
```sh
|
||||
$ deno test --allow-read --allow-env --allow-net
|
||||
running 1 test from ./tests/main_test.ts
|
||||
HTTP assert test. ...
|
||||
#1 GET / ... ok (31ms)
|
||||
#2 POST / ... ok (35ms)
|
||||
#3 GET /foo ... ok (12ms)
|
||||
HTTP assert test. ... ok (118ms)
|
||||
|
||||
ok | 1 passed (3 steps) | 0 failed (236ms)
|
||||
```
|
||||
@@ -0,0 +1,96 @@
|
||||
---
|
||||
description: |
|
||||
Add JavaScript based interactivity to your project without sacrificing user
|
||||
experience, by using Fresh's powerful islands system.
|
||||
---
|
||||
|
||||
Up to now none of the pages in the demo project have contained any client side
|
||||
JavaScript. This is great for resiliency and performance, but it can also limit
|
||||
the possibilities of interactivity. In many current generation web frameworks,
|
||||
you get the choice of shipping no JavaScript to the client or shipping a
|
||||
renderer for the entire page.
|
||||
|
||||
This is not very flexible, especially considering that most pages will only have
|
||||
small pieces of content that require interactivity. For example, an otherwise
|
||||
static page might need a little bit of JavaScript to power an image carousel or
|
||||
"buy now" button. This model is often called
|
||||
[islands architecture][islands-architecture]. This refers to a page having
|
||||
little "islands" of interactivity, in a sea of otherwise static content.
|
||||
|
||||
Fresh embraces this model. All pages are rendered server side, but you can
|
||||
create "island components" that are _also_ rendered client side. To do this,
|
||||
Fresh projects have a special `islands/` folder. The modules in this folder each
|
||||
encapsulate a single island component. The name of the module should be the
|
||||
[pascal case][pascal-case] or [kebab case][kebab-case] name of the island
|
||||
component. For example a counter component would be defined in the file
|
||||
`islands/Counter.tsx`. A buy now button could be defined in the file
|
||||
`islands/buy-now-button.tsx`.
|
||||
|
||||
Here is an example of an island component that counts down to a specific time.
|
||||
|
||||
```tsx
|
||||
// islands/Countdown.tsx
|
||||
|
||||
import { useSignal } from "@preact/signals";
|
||||
import { useEffect } from "preact/hooks";
|
||||
|
||||
const timeFmt = new Intl.RelativeTimeFormat("en-US");
|
||||
|
||||
// The target date is passed as a string instead of as a `Date`, because the
|
||||
// props to island components need to be JSON (de)serializable.
|
||||
export default function Countdown(props: { target: string }) {
|
||||
const target = new Date(props.target);
|
||||
const now = useSignal(new Date());
|
||||
|
||||
// Set up an interval to update the `now` date every second with the current
|
||||
// date as long as the component is mounted.
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => {
|
||||
if (now.value > target) {
|
||||
clearInterval(timer);
|
||||
}
|
||||
now.value = new Date();
|
||||
}, 1000);
|
||||
return () => clearInterval(timer);
|
||||
}, [props.target]);
|
||||
|
||||
const secondsLeft = Math.floor(
|
||||
(target.getTime() - now.value.getTime()) / 1000,
|
||||
);
|
||||
|
||||
// If the target date has passed, we stop counting down.
|
||||
if (secondsLeft <= 0) {
|
||||
return <span>🎉</span>;
|
||||
}
|
||||
|
||||
// Otherwise, we format the remaining time using `Intl.RelativeTimeFormat` and
|
||||
// render it.
|
||||
return <span>{timeFmt.format(secondsLeft, "seconds")}</span>;
|
||||
}
|
||||
```
|
||||
|
||||
To include this in a page component, one can just use the component normally.
|
||||
Fresh will take care of automatically mounting the island component on the
|
||||
client with the correct props:
|
||||
|
||||
```tsx
|
||||
// routes/countdown.tsx
|
||||
|
||||
import Countdown from "../islands/Countdown.tsx";
|
||||
|
||||
export default function Page() {
|
||||
const date = new Date();
|
||||
date.setHours(date.getHours() + 1);
|
||||
return (
|
||||
<p>
|
||||
The big event is happening <Countdown target={date.toISOString()} />.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The page that is rendered on the client now has an interactive countdown.
|
||||
|
||||
[islands-architecture]: https://jasonformat.com/islands-architecture
|
||||
[pascal-case]: https://en.wiktionary.org/wiki/Pascal_case
|
||||
[kebab-case]: https://en.wiktionary.org/wiki/kebab_case
|
||||
@@ -0,0 +1,60 @@
|
||||
---
|
||||
description: |
|
||||
Create a new Fresh project by running the Fresh project creation tool. This
|
||||
scaffolds out the various files and folders a Fresh project needs.
|
||||
---
|
||||
|
||||
New Fresh projects can be created by using the Fresh project creation tool. It
|
||||
will scaffold out a new project with some example files to get you started.
|
||||
|
||||
To create a new project, run:
|
||||
|
||||
```
|
||||
deno run -A -r https://fresh.deno.dev
|
||||
cd fresh-project
|
||||
deno task start
|
||||
```
|
||||
|
||||
This will scaffold out the new project, then switch into the newly created
|
||||
directory, and then start the development server.
|
||||
|
||||
This will create a directory containing some files and directories. There are 4
|
||||
files that are strictly necessary to run a Fresh project:
|
||||
|
||||
- **`dev.ts`**: This is the development entry point for your project. This is
|
||||
the file that you run to start your project. This file doesn't need to be
|
||||
called `dev.ts`, but this is the convention.
|
||||
- **`main.ts`**: This is the production entry point for your project. It is the
|
||||
file that you link to Deno Deploy. This file doesn't actually need to be
|
||||
`main.ts`, but this is the convention.
|
||||
- **`fresh.gen.ts`**: This is the manifest file that contains information about
|
||||
your routes and islands. This file is automatically generated in development
|
||||
based on your `routes/` and `islands/` folders.
|
||||
|
||||
A **`deno.json`** file is also created in the project directory. This file does
|
||||
two things:
|
||||
|
||||
- It defines the "imports" field. This is an [import map][import-map] that is
|
||||
used to manage dependencies for the project. This allows for easy importing
|
||||
and updating of dependencies.
|
||||
- It registers a "start" [task][task-runner] to run the project without having
|
||||
to type a long `deno run` command.
|
||||
|
||||
Two important folders are also created that contain your routes and islands
|
||||
respectively:
|
||||
|
||||
- **`routes/`**: This folder contains all of the routes in your project. The
|
||||
names of each file in this folder correspond to the path where that page will
|
||||
be accessed. Code inside of this folder is never directly shipped to the
|
||||
client. You'll learn more about how routes work in the next section.
|
||||
- **`islands/`**: This folder contains all of the interactive islands in your
|
||||
project. The name of each file corresponds to the name of the island defined
|
||||
in that file. Code inside of this folder can be run from both client and
|
||||
server. You'll learn more about islands later in this chapter.
|
||||
|
||||
Finally a **`static/`** folder is created that contains static files that are
|
||||
automatically served "as is". [Learn more about static files][static-files].
|
||||
|
||||
[import-map]: https://deno.land/manual/linking_to_external_code/import_maps
|
||||
[task-runner]: https://deno.land/manual/tools/task_runner
|
||||
[static-files]: ../concepts/static-files
|
||||
@@ -0,0 +1,60 @@
|
||||
---
|
||||
description: |
|
||||
Create a new route to a Fresh project by creating a new file in the `routes/`
|
||||
folder.
|
||||
---
|
||||
|
||||
After getting the project running locally, the next step is to add a new route
|
||||
to the project. Routes encapsulate the logic for handling requests to a
|
||||
particular path in your project. They can be used to handle API requests or
|
||||
render HTML pages. For now we are going to do the latter.
|
||||
|
||||
Routes are defined as files in the `routes` directory. The file name of the
|
||||
module is important: it is used to determine the path that the route will
|
||||
handle. For example, if the file name is `index.js`, the route will handle
|
||||
requests to `/`. If the file name is `about.js`, the route will handle requests
|
||||
to `/about`. If the file name is `contact.js` and is placed inside of the
|
||||
`routes/about/` folder, the route will handle requests to `/about/contact`. This
|
||||
concept is called _File-system routing_. You can learn more about it on the
|
||||
[_Concepts: Routing_][concepts-routing] page.
|
||||
|
||||
Route files that render HTML are JavaScript or TypeScript modules that export a
|
||||
JSX component as their default export. This component will be rendered for every
|
||||
request to the route's path. The component receives a few properties that can be
|
||||
used to customize the rendered output, such as the current route, the url of the
|
||||
request, state set by middleware, and handler data (more on the last two later).
|
||||
|
||||
In the demo project we'll create a route to handle the `/about` page. To do
|
||||
this, one needs to create a new `routes/about.tsx` file. In this file, we can
|
||||
declare a component that should be rendered every time a user visits the page.
|
||||
This is done with JSX.
|
||||
|
||||
> ℹ️ To learn more about JSX, you can read [this article][jsx] in the React
|
||||
> documentation. Beware that Fresh does not use React, but rather
|
||||
> [Preact][preact], a lighter weight virtual dom library that works similar to
|
||||
> React.
|
||||
|
||||
```tsx
|
||||
// routes/about.tsx
|
||||
|
||||
export default function AboutPage() {
|
||||
return (
|
||||
<main>
|
||||
<h1>About</h1>
|
||||
<p>This is the about page.</p>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The new page will be visible at `http://localhost:8000/about`.
|
||||
|
||||
<!-- You can find more in depth information about routes on the
|
||||
[_Concepts: Routes_][concepts-routes] documentation page. The following
|
||||
pages in the _Getting Started_ guide will also explain more features of routes. -->
|
||||
|
||||
[concepts-routing]: /docs/concepts/routing
|
||||
[jsx]: https://reactjs.org/docs/introducing-jsx.html
|
||||
[preact]: https://preactjs.com/
|
||||
|
||||
<!-- [concepts-routes]: /docs/concepts/routes -->
|
||||
@@ -0,0 +1,70 @@
|
||||
---
|
||||
description: |
|
||||
Add custom handlers to a route to customize HTTP headers, implement API
|
||||
routes, do data fetching for a rendered page, or handle form submissions.
|
||||
---
|
||||
|
||||
Routes actually consist of two parts: handlers, and the page component. Up to
|
||||
now, only the page component has been discussed in this chapter.
|
||||
|
||||
Handlers are functions in the form of `Request => Response` or
|
||||
`Request => Promise<Response>` that are called when a request is made to a
|
||||
particular route. There can be one handler that covers all HTTP methods or one
|
||||
handler per method.
|
||||
|
||||
The handler has access to the `Request` object that backs the request to the
|
||||
route and must return a `Response` object. The response object can either be
|
||||
created manually (for example a JSON response for an API route), or it can be
|
||||
created by rendering the page component. By default, all routes that don't
|
||||
define a custom handler use a default handler that just renders the page
|
||||
component.
|
||||
|
||||
To define a handler in a route module, one must export it as a named export with
|
||||
the name `handler`. Handlers can have two forms: a plain function (catchall for
|
||||
all HTTP methods) or a plain object where each property is a function named by
|
||||
the HTTP method it handles.
|
||||
|
||||
Here is an example of a custom `GET` handler that renders the page component and
|
||||
then adds a custom header to the response before returning it:
|
||||
|
||||
```tsx
|
||||
// routes/about.tsx
|
||||
|
||||
import { Handlers } from "$fresh/server.ts";
|
||||
|
||||
export const handler: Handlers = {
|
||||
async GET(_req, ctx) {
|
||||
const resp = await ctx.render();
|
||||
resp.headers.set("X-Custom-Header", "Hello");
|
||||
return resp;
|
||||
},
|
||||
};
|
||||
|
||||
export default function AboutPage() {
|
||||
return (
|
||||
<main>
|
||||
<h1>About</h1>
|
||||
<p>This is the about page.</p>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Note that handlers do not need to call `ctx.render()`. This feature can be used
|
||||
to create API routes. Here is an API route that returns a random UUID as a JSON
|
||||
response:
|
||||
|
||||
```ts
|
||||
// routes/api/random-uuid.ts
|
||||
|
||||
import { Handlers } from "$fresh/server.ts";
|
||||
|
||||
export const handler: Handlers = {
|
||||
GET(_req) {
|
||||
const uuid = crypto.randomUUID();
|
||||
return new Response(JSON.stringify(uuid), {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
},
|
||||
};
|
||||
```
|
||||
@@ -0,0 +1,31 @@
|
||||
---
|
||||
description: |
|
||||
Deploy a Fresh application to Deno Deploy in seconds, making it available on
|
||||
the edge globally - resulting in fantastic user latency worldwide.
|
||||
---
|
||||
|
||||
As a final step in the getting started guide, we'll deploy the demo site to the
|
||||
public internet using [Deno Deploy][deno-deploy]. Deno Deploy is a globally
|
||||
distributed edge runtime built by the Deno company that allows developers to
|
||||
quickly and painlessly deploy web applications to the internet. Deno Deploy has
|
||||
edge nodes all over the world that serve traffic. Because of this, users
|
||||
worldwide have fantastic latency because their traffic is served from a server
|
||||
that is physically close to them.
|
||||
|
||||
To deploy to Deno Deploy, we'll make use of the GitHub integration. To use this
|
||||
the code needs to be pushed to a repository on GitHub. Once this has been done,
|
||||
one must go to the [Deno Deploy dashboard][deno-deploy-dashboard] and create a
|
||||
new project.
|
||||
|
||||
After creating the project, head to the "Git" tab in the project settings,
|
||||
select the repository, the production branch (`main`) and the entrypoint file
|
||||
(`main.ts`). This will link the project to the repository and automatically
|
||||
deploy it to the internet. The project will now be available at
|
||||
https://$PROJECT_NAME.deno.dev.
|
||||
|
||||
Every time the code in the GitHub repository is updated, it will be deployed
|
||||
either as a preview or production deployment. Production deployments are only
|
||||
created for changes to the default/production branch (often `main`).
|
||||
|
||||
[deno-deploy]: https://deno.com/deploy
|
||||
[deno-deploy-dashboard]: https://dash.deno.com/projects
|
||||
@@ -0,0 +1,52 @@
|
||||
---
|
||||
description: |
|
||||
Create a dynamic route in Fresh by adding a dynamic segment to the route name
|
||||
in the routes' file name on disk: `/greet/[name].tsx`.
|
||||
---
|
||||
|
||||
The `/about` route created on the last page is pretty static. It does not matter
|
||||
what query or path parameters are passed to the route, it will always render the
|
||||
same page. Let's create a `/greet/:name` that will render a page with a greeting
|
||||
that contains the name passed in the path.
|
||||
|
||||
Before diving in, a quick refresher on "dynamic" routes. Dynamic routes don't
|
||||
just match a single static path, but rather a whole bunch of different paths
|
||||
based on a pattern. For example, the `/greet/:name` route will match the paths
|
||||
`/greet/Luca` and `/John`, but not `/greet/Luca/John`.
|
||||
|
||||
Fresh supports dynamic routes out of the box through file system routing. To
|
||||
make any path segment dynamic, just put square brackets around that segment in
|
||||
the file name. For example the `/greet/:name` route maps to the file name
|
||||
`routes/greet/[name].tsx`.
|
||||
|
||||
Just like the static `/about` route, the dynamic `/greet/:name` route will
|
||||
render a page. The module must once again expose a component as a default
|
||||
export. This time the component will receive the matched path segment properties
|
||||
as arguments in its `props` object though.
|
||||
|
||||
```tsx
|
||||
// routes/greet/[name].tsx
|
||||
|
||||
import { PageProps } from "$fresh/server.ts";
|
||||
|
||||
export default function GreetPage(props: PageProps) {
|
||||
const { name } = props.params;
|
||||
return (
|
||||
<main>
|
||||
<p>Greetings to you, {name}!</p>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `PageProps` interface actually contains a bunch of useful properties that
|
||||
can be used to customize the rendered output. Next to the matched url pattern
|
||||
parameters, the raw `url`, and the `route` name can also be found in here.
|
||||
|
||||
Navigating to `http://localhost:8000/greet/Luca` will now render a page showing
|
||||
"Greetings to you, Luca!".
|
||||
|
||||
The [_Concepts: Routing_][concepts-routing] page has more information about
|
||||
dynamic routes, especially about how to create more advanced dynamic routes.
|
||||
|
||||
[concepts-routing]: /docs/concepts/routing
|
||||
@@ -0,0 +1,64 @@
|
||||
---
|
||||
description: |
|
||||
Fetch data for routes dynamically by creating a custom handler and passing
|
||||
data to the render function.
|
||||
---
|
||||
|
||||
All of the pages in the demo project so far have not used any dynamic data
|
||||
during rendering. In real projects, this is often different. In many cases you
|
||||
may need to read a file from disk (e.g. markdown for a blog post), or fetch some
|
||||
user data from an API or database.
|
||||
|
||||
These operations are all asynchronous. Rendering however, is always synchronous.
|
||||
Instead of fetching data directly during rendering, it should be loaded in a
|
||||
route's `handler` function and then passed to the page component via first
|
||||
argument to `ctx.render()`.
|
||||
|
||||
The data that is passed to `ctx.render()` can then be accessed via the
|
||||
`props.data` field on the page component.
|
||||
|
||||
Here is an example of a route that fetches user data from the GitHub API and
|
||||
renders it in a page component.
|
||||
|
||||
```tsx
|
||||
// routes/github/[username].tsx
|
||||
|
||||
import { Handlers, PageProps } from "$fresh/server.ts";
|
||||
|
||||
interface User {
|
||||
login: string;
|
||||
name: string;
|
||||
avatar_url: string;
|
||||
}
|
||||
|
||||
export const handler: Handlers<User | null> = {
|
||||
async GET(_, ctx) {
|
||||
const { username } = ctx.params;
|
||||
const resp = await fetch(`https://api.github.com/users/${username}`);
|
||||
if (resp.status === 404) {
|
||||
return ctx.render(null);
|
||||
}
|
||||
const user: User = await resp.json();
|
||||
return ctx.render(user);
|
||||
},
|
||||
};
|
||||
|
||||
export default function Page({ data }: PageProps<User | null>) {
|
||||
if (!data) {
|
||||
return <h1>User not found</h1>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<img src={data.avatar_url} width={64} height={64} />
|
||||
<h1>{data.name}</h1>
|
||||
<p>{data.login}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The data is first fetched inside of the handler by making an API call to GitHub.
|
||||
If the API call succeeds, the data is passed to the page component. If the API
|
||||
call fails, the page component is rendered with `null` as the data. The page
|
||||
component grabs the data from the props and renders it.
|
||||
@@ -0,0 +1,79 @@
|
||||
---
|
||||
description: |
|
||||
Robustly handle user inputs using HTML `<form>` elements client side, and form
|
||||
submission handlers server side.
|
||||
---
|
||||
|
||||
Forms are a common mechanism for letting users interact with applications. In
|
||||
the last few years it has become more and more common for web applications to
|
||||
move form submission entirely to the client. This can have useful properties for
|
||||
interactivity, but it is much worse for resiliency and user experience as a
|
||||
whole. Browsers have great built in systems for form submission, revolving
|
||||
around the HTML `<form>` element.
|
||||
|
||||
Fresh builds the core of its form submission infrastructure around the native
|
||||
`<form>` element. This page explains how to use `<form>` in Fresh, and the next
|
||||
chapter explains how to progressively enhance your forms with client side
|
||||
JavaScript to make them more interactive.
|
||||
|
||||
The way forms work in the browser, is that they perform an HTML navigation
|
||||
action when the user submits the form. In most cases this means that when the
|
||||
form is submitted, a `GET` or `POST` request is sent to the server with the form
|
||||
data, which then responds with a new page to render.
|
||||
|
||||
Fresh can handle both `GET` and `POST` requests through the
|
||||
[custom handlers][custom-handlers] feature of routes. The handlers can perform
|
||||
any necessary processing on the form data, and then pass data to the
|
||||
`ctx.render()` call to render a new page.
|
||||
|
||||
Here is an example implementing a search form that filters an array of names
|
||||
server side:
|
||||
|
||||
```tsx
|
||||
// routes/search.tsx
|
||||
|
||||
import { Handlers, PageProps } from "$fresh/server.ts";
|
||||
|
||||
const NAMES = ["Alice", "Bob", "Charlie", "Dave", "Eve", "Frank"];
|
||||
|
||||
interface Data {
|
||||
results: string[];
|
||||
query: string;
|
||||
}
|
||||
|
||||
export const handler: Handlers<Data> = {
|
||||
GET(req, ctx) {
|
||||
const url = new URL(req.url);
|
||||
const query = url.searchParams.get("q") || "";
|
||||
const results = NAMES.filter((name) => name.includes(query));
|
||||
return ctx.render({ results, query });
|
||||
},
|
||||
};
|
||||
|
||||
export default function Page({ data }: PageProps<Data>) {
|
||||
const { results, query } = data;
|
||||
return (
|
||||
<div>
|
||||
<form>
|
||||
<input type="text" name="q" value={query} />
|
||||
<button type="submit">Search</button>
|
||||
</form>
|
||||
<ul>
|
||||
{results.map((name) => <li key={name}>{name}</li>)}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
When the user submits the form, the browser will navigate to `/search` with the
|
||||
query set as the `q` query parameter in the URL. The `GET` handler will then
|
||||
filter the names array based on the query, and pass it to the page component for
|
||||
rendering.
|
||||
|
||||
[Learn more about using forms in Fresh][concepts-forms].
|
||||
|
||||
<!-- TODO(lucacasonato): link to todo app example when that is built again -->
|
||||
|
||||
[custom-handlers]: /docs/getting-started/custom-handlers
|
||||
[concepts-forms]: /docs/concepts/forms
|
||||
@@ -0,0 +1,24 @@
|
||||
---
|
||||
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.
|
||||
---
|
||||
|
||||
In this chapter of the Fresh documentation, you'll be introduced to the
|
||||
framework. You'll learn how to create a new project, run it locally, edit and
|
||||
create pages, fetch data, handle user interactions, and how to then deploy the
|
||||
project to [Deno Deploy][deno-deploy].
|
||||
|
||||
The documentation assumes you have Deno 1.35.0 or later installed.
|
||||
|
||||
To install Deno, follow the
|
||||
[installation instructions in the Deno manual][manual-installation].
|
||||
|
||||
For the best user experience, you should also set up your editor or IDE to play
|
||||
nice with Deno. Documentation for this can also be found
|
||||
[in the manual][manual-editors].
|
||||
|
||||
[deno-deploy]: https://deno.com/deploy
|
||||
[manual-installation]: https://deno.land/manual/getting_started/installation
|
||||
[manual-editors]: https://deno.land/manual/getting_started/setup_your_environment
|
||||
@@ -0,0 +1,64 @@
|
||||
---
|
||||
description: |
|
||||
To start a Fresh project, just run `deno task start`. This will start the
|
||||
project with default permission flags, in watch mode.
|
||||
---
|
||||
|
||||
The next step after scaffolding out a new project, is to actually start it. To
|
||||
do this you can just `deno task start`. Environment variables will be
|
||||
automatically read from `.env`.
|
||||
|
||||
```
|
||||
$ deno task start
|
||||
Watcher Process started.
|
||||
🍋 Fresh ready
|
||||
Local: http://localhost:8000
|
||||
```
|
||||
|
||||
If you want to start manually without Deno task, `deno run` the `main.ts` with
|
||||
the appropriate flags. You will need to provide permission flags for:
|
||||
|
||||
- **`--allow-net`**: This is required to start the HTTP server.
|
||||
- **`--allow-read`**: This is required to read (static) files from disk.
|
||||
- **`--allow-env`**: This is required to read environment variables that can be
|
||||
used to configure your project.
|
||||
- **`--allow-run`**: This is required to shell out to `deno` and `esbuild` under
|
||||
the hood during development to do type stripping. In production this is done
|
||||
using a WebAssembly binary.
|
||||
|
||||
For development, you also want to run with the [`--watch` flag][--watch], so the
|
||||
Fresh server will automatically reload whenever you make a change to your code.
|
||||
By default `--watch` only watches over files in your module graph. Some project
|
||||
files like static files are not part of the module graph, but you probably want
|
||||
to restart/reload whenever you make a change to them too. This can be done by
|
||||
passing the extra folder as an argument: `--watch=static/`. You should also add
|
||||
`routes/` to the watch list, so that the server restarts automatically whenever
|
||||
you add a new route.
|
||||
|
||||
If you want to change the port or host, modify the options bag of the `start()`
|
||||
call in `main.ts` to include an explicit port number:
|
||||
|
||||
```js
|
||||
await start(manifest, { port: 3000 });
|
||||
```
|
||||
|
||||
You can also change the port by setting the `PORT` environment variable:
|
||||
|
||||
```
|
||||
$ PORT=3000 deno task start
|
||||
```
|
||||
|
||||
Combining all of this we get the following `deno run` command:
|
||||
|
||||
```
|
||||
$ deno run --allow-net --allow-read --allow-env --allow-run --watch=static/,routes/ main.ts
|
||||
Watcher Process started.
|
||||
🍋 Fresh ready
|
||||
Local: http://localhost:8000
|
||||
```
|
||||
|
||||
If you now visit http://localhost:8000, you can see the running project. Try
|
||||
change some of the text in `routes/index.tsx` and see how the page updates
|
||||
automatically when you save the file.
|
||||
|
||||
[--watch]: https://deno.land/manual/getting_started/command_line_interface#watch-mode
|
||||
@@ -0,0 +1,34 @@
|
||||
---
|
||||
description: |
|
||||
Various projects can integrate into Fresh to easily add functionality to your
|
||||
project.
|
||||
---
|
||||
|
||||
This section of the docs showcases modules or other projects that integrate with
|
||||
Fresh. These integrations can be used to add functionality to your project.
|
||||
|
||||
## `fresh_charts`
|
||||
|
||||
Fresh charts allows for easy integration of [Chart.js][chart-js] charts into
|
||||
your Fresh project. It provides a `Chart` JSX component that can be used to
|
||||
render charts on the server and client.
|
||||
|
||||
A live demo can be found here: https://fresh-charts.deno.dev/
|
||||
|
||||
Documentation for the module can be found here: https://deno.land/x/fresh_charts
|
||||
|
||||
[chart-js]: https://www.chartjs.org/ "Chart.js"
|
||||
|
||||
## `fresh_marionette`
|
||||
|
||||
Fresh Marionette allows you to start writing end 2 end browser tests in your
|
||||
Fresh projects with a single import. Then you can run those browser tests in a
|
||||
GitHub Actions workflow.
|
||||
|
||||
Documentation for the module can be found here:
|
||||
https://deno.land/x/fresh_marionette
|
||||
|
||||
An example project that runs the tests in a GitHub Actions workflow:
|
||||
https://marionette.deno.dev
|
||||
|
||||
Fresh Marionette works with VSCode too! - https://youtu.be/OG77NdqL164
|
||||
@@ -0,0 +1,44 @@
|
||||
---
|
||||
description: |
|
||||
Fresh is a full stack modern web framework for JavaScript and TypeScript
|
||||
developers, designed to make it trivial to create high-quality, performant,
|
||||
and personalized web applications.
|
||||
---
|
||||
|
||||
Fresh is a full stack modern web framework for JavaScript and TypeScript
|
||||
developers, designed to make it trivial to create high-quality, performant, and
|
||||
personalized web applications. You can use it to create your home page, a blog,
|
||||
a large web application like GitHub or Twitter, or anything else you can think
|
||||
of.
|
||||
|
||||
At its core, Fresh is a combination of a routing framework and templating engine
|
||||
that renders pages on demand, on the server. In addition to this just-in-time
|
||||
(JIT) rendering on the server, Fresh also provides an interface for seamlessly
|
||||
rendering some components on the client for maximum interactivity. The framework
|
||||
uses [Preact][preact] and JSX for rendering and templating on both the server
|
||||
and the client.
|
||||
|
||||
Fresh also does not have a build step. The code you write is also directly the
|
||||
code that is run on the server, and the code that is executed on the client. Any
|
||||
necessary transpilation of TypeScript or JSX to plain JavaScript is done on the
|
||||
fly, just when it is needed. This allows for insanely fast iteration loops and
|
||||
very very fast deployments.
|
||||
|
||||
Fresh projects can be deployed manually to any platform with `deno`, but it is
|
||||
intended to be deployed to an edge runtime like [Deno Deploy][deno-deploy] for
|
||||
the best experience.
|
||||
|
||||
Some stand out features:
|
||||
|
||||
- No build step
|
||||
- Zero config necessary
|
||||
- JIT rendering on the edge
|
||||
- Tiny & fast (no client JS is required by the framework)
|
||||
- Optional client side hydration of individual components
|
||||
- Highly resilient because of progressive enhancement and use of native browser
|
||||
features
|
||||
- TypeScript out of the box
|
||||
- File-system routing à la Next.js
|
||||
|
||||
[preact]: https://preactjs.com
|
||||
[deno-deploy]: https://deno.com/deploy
|
||||
Reference in New Issue
Block a user