www: move latest docs into latest folder (#1522)
This commit is contained in:
@@ -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)
|
||||
```
|
||||
Reference in New Issue
Block a user