diff --git a/docs/canary/advanced/app-wrapper.md b/docs/canary/advanced/app-wrapper.md new file mode 100644 index 00000000..984de657 --- /dev/null +++ b/docs/canary/advanced/app-wrapper.md @@ -0,0 +1,33 @@ +--- +description: | + Add a global app wrapper to provide common meta tags or context for application routes. +--- + +The app wrapper component is a Preact component that represents the outer +structure of the HTML document, typically up until the ``-tag. It is only +rendered on the server and never on the client. The passed `Component` value +represents the children of this component. + +```tsx +function AppWrapper({ Component }) { + return ( + + + + My App + + + + + + ); +} + +app.appWrapper(AppWrapper); +``` + +Every `ctx.render()` call will include the app wrapper component by default, +unless opted out. + +Note that only one app wrapper component is supported per +[`App`](/docs/canary/concepts/app) instance. diff --git a/docs/canary/advanced/error-handling.md b/docs/canary/advanced/error-handling.md new file mode 100644 index 00000000..20852b04 --- /dev/null +++ b/docs/canary/advanced/error-handling.md @@ -0,0 +1,82 @@ +--- +description: | + Error pages can be used to customize the page that is shown when an error occurs in the application. +--- + +Fresh supports customizing the `404 Not Found`, and the +`500 Internal Server Error` pages. These are shown when a request is made but no +matching route exists, and when a middleware, route handler, or page component +throws an error respectively. + +### 404: Not Found + +The 404 page can be customized by creating a `_404.tsx` file in the `routes/` +folder. The file must have a default export that is a regular Preact component. +A props object of type `PageProps` is passed in as an argument. + +```tsx routes/_404.tsx +import { PageProps } from "$fresh/server.ts"; + +export default function NotFoundPage({ url }: PageProps) { + return

404 not found: {url.pathname}

; +} +``` + +#### Manually render 404 pages + +The `_404.tsx` file will be invoked automatically when no route matches the URL. +In some cases, one needs to manually trigger the rendering of the 404 page, for +example when the route did match, but the requested resource does not exist. +This can be achieved with `ctx.renderNotFound`. + +```tsx routes/blog/[slug].tsx +import { Handlers, PageProps } from "$fresh/server.ts"; + +export const handler: Handlers = { + async GET(req, ctx) { + const blogpost = await fetchBlogpost(ctx.params.slug); + if (!blogpost) { + return ctx.renderNotFound({ + custom: "prop", + }); + } + return ctx.render({ blogpost }); + }, +}; + +export default function BlogpostPage({ data }) { + return ( +
+

{data.blogpost.title}

+ {/* rest of your page */} +
+ ); +} +``` + +This can also be achieved by throwing an error, if you're uninterested in +passing specific data to your 404 page: + +```tsx +import { Handlers } from "$fresh/server.ts"; + +export const handler: Handlers = { + GET(_req, _ctx) { + throw new Deno.errors.NotFound(); + }, +}; +``` + +### 500: Internal Server Error + +The 500 page can be customized by creating a `_500.tsx` file in the `routes/` +folder. The file must have a default export that is a regular Preact component. +A props object of type `PageProps` is passed in as an argument. + +```tsx routes/_500.tsx +import { PageProps } from "$fresh/server.ts"; + +export default function Error500Page({ error }: PageProps) { + return

500 internal error: {(error as Error).message}

; +} +``` diff --git a/docs/canary/advanced/forms.md b/docs/canary/advanced/forms.md new file mode 100644 index 00000000..fd7dcc06 --- /dev/null +++ b/docs/canary/advanced/forms.md @@ -0,0 +1,120 @@ +--- +description: | + Robustly handle user inputs using HTML `
` 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 `` element. + +In the browser, a `` submit will send an HTML action (usually `GET` or +`POST`) to the server, which responds with a new page to render. + +## POST request with `application/x-www-form-urlencoded` + +Forms typically submit as a `GET` request with data encoded in the URL's search +parameters, or as a `POST` request with either an +`application/x-www-form-urlencoded` or `multipart/form-data` body. + +This example demonstrates how to handle `application/x-www-form-urlencoded` +`` 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 ( + <> + + + +
+ + ); +} +``` + +When the user submits the form, Deno will retrieve the `email` value using the +request's `formData()` method, add the email to a list, and redirect the user to +a thank you page. + +## Handling file uploads + +File uploads can be handled in a very similar manner to the example above. Note +that this time, we have to explicitly declare the form's encoding to be +`multipart/form-data`. + +```tsx routes/subscribe.tsx +import { Handlers, type PageProps } from "$fresh/server.ts"; + +interface Props { + message: string | null; +} + +export const handler: Handlers = { + async GET(req, ctx) { + return await ctx.render({ + message: null, + }); + }, + async POST(req, ctx) { + const form = await req.formData(); + const file = form.get("my-file") as File; + + if (!file) { + return ctx.render({ + message: `Please try again`, + }); + } + + const name = file.name; + const contents = await file.text(); + + console.log(contents); + + return ctx.render({ + message: `${name} uploaded!`, + }); + }, +}; + +export default function Upload(props: PageProps) { + const { message } = props.data; + return ( + <> +
+ + +
+ {message ?

{message}

: null} + + ); +} +``` + +## A note of caution + +These examples are simplified to demonstrate how Deno and Fresh handle HTTP +requests. In the Real World™, you'll want to validate your data (_especially the +file type_) and protect against cross-site request forgery. Consider yourself +warned. diff --git a/docs/canary/advanced/layouts.md b/docs/canary/advanced/layouts.md new file mode 100644 index 00000000..35831536 --- /dev/null +++ b/docs/canary/advanced/layouts.md @@ -0,0 +1,47 @@ +--- +description: "Create re-usable layouts across routes" +--- + +Layouts are plain Preact components that are inherited based on the matching +pattern. When you have a section on your site where all pages share the same +HTML structure and only the content changes, a layout is a neat way to abstract +this. Layouts only ever render on the server. The passed `Component` value +represents the children of this component. + +```tsx +function PageLayout({ Component }) { + return ( +
+ + +
+ ); +} + +const app = new App() + .layout("*", PageLayout) + .get("/", (ctx) => ctx.render(

hello

)); +``` + +If you browse to the `/` route, Fresh will render the following HTML + +```html +
+

hello world

+ +
+``` + +## Options + +Add a layout and ignore all previously inherited ones. + +```ts +app.layout("/foo/bar", MyComponent, { skipInheritedLayouts: true }); +``` + +Ignore the app wrapper component: + +```ts +app.layout("/foo/bar", MyComponent, { skipAppWrapper: true }); +``` diff --git a/docs/canary/advanced/partials.md b/docs/canary/advanced/partials.md new file mode 100644 index 00000000..559cab42 --- /dev/null +++ b/docs/canary/advanced/partials.md @@ -0,0 +1,228 @@ +--- +description: | + Partials allow areas of a page to be updated without causing the browser to reload the page. They enable optimized fine grained UI updates and can be used to do client-side navigation. +--- + +Partials allow areas of the page to be updated with new content by the server +without causing the browser to reload the page. They make your website feel more +app-like because only the parts of the page that need to be updated will be +updated. + +## Enabling partials + +Partials are enabled by adding a `f-client-nav` attribute to an HTML element and +wrapping one or more areas in the page with a +``-component. + +The quickest way to get started is to enable partials for every page in +`routes/_app.tsx` by making the following changes. + +```diff routes/_app.tsx + import { PageProps } from "$fresh/server.ts"; ++ import { Partial } from "$fresh/runtime.ts"; + + export default function App({ Component }: PageProps) { + return ( + + + + + My Fresh app + +- ++ ++ + ++ + + + ); + } +``` + +By adding the `f-client-nav` attribute, we enable partials for every element +beneath the ``-tag. To mark an area of the page as a partial we wrap it +with a ``-component with a unique name. + +Behind the scenes, when the user clicks an ``-tag, Fresh fetches the new page +and only pulls out the relevant content out of the HTML response. When it finds +a matching partial area it will update the content inside the partial. + +> [info]: The `name` prop of the `` component is expected to be unique +> among Partials. That's how Fresh knows which parts of the response need to go +> on the current page. + +> [info]: Passing `f-client-nav={false}` disables client side navigation for all +> elements below the current node. + +### Optimizing partial requests + +By default, with `f-client-nav` set, Fresh fetches the full next page and only +picks out the relevant parts of the response. We can optimize this pattern +further by only rendering the parts we need, instead of always rendering the +full page. This is done by adding the `f-partial` attribute to a link. + +```diff +- Routes ++ Routes +``` + +When the `f-partial` attribute is present, Fresh will navigate to the page URL +defined in the `href` attribute, but fetch the updated UI from the URL specified +in `f-partial` instead. This can be a highly optimized route that only delivers +the content you care about. + +Let's use a typical documentation page layout as an example. It often features a +main content area and a sidebar of links to switch between pages of the +documentation (marked green here). + +![A sketched layout of a typical documentation page with the sidebar on the left composed of green links and a main content area on the right. The main content area is labeled as Partial docs-content](/docs/fresh-partial-docs.png) + +The code for such a page (excluding styling) might look like this: + +```tsx routes/docs/[id].tsx +export default defineRoute(async (req, ctx) => { + const content = await loadContent(ctx.params.id); + + return ( +
+ + + {content} + +
+ ); +}); +``` + +An optimal route that only renders the content instead of the outer layout with +the sidebar might look like this respectively. + +```tsx routes/partials/docs/[id].tsx +import { defineRoute, RouteConfig } from "$fresh/server.ts"; +import { Partial } from "$fresh/runtime.ts"; + +// We only want to render the content, so disable +// the `_app.tsx` template as well as any potentially +// inherited layouts +export const config: RouteConfig = { + skipAppWrapper: true, + skipInheritedLayouts: true, +}; + +export default defineRoute(async (req, ctx) => { + const content = await loadContent(ctx.params.id); + + // Only render the new content + return ( + + {content} + + ); +}); +``` + +By adding the `f-partial` attribute we tell Fresh to fetch the content from our +newly added `/partials/docs/[id].tsx` route. + +```diff routes/docs/[id].tsx + +``` + +With this in place, Fresh will navigate to the new page when clicking any of the +two links and _only_ load the content rendered by our optimized partial route. + +> Currently, `f-partial` is scoped to ``, ` + + ); +} +``` + +An island can be used anywhere like a regular Preact component. Fresh will take +care of making it interactive on the client. + +```tsx +import MyIsland from "../islands/my-island.tsx"; + +const app = new App() + .get("/", (ctx) => ctx.render()); +``` + +## Passing props to islands + +Passing props to islands is supported, but only if the props are serializable. +Fresh can serialize the following types of values: + +- Primitive types `string`, `number`, `boolean`, `bigint`, and `null` +- `Infinity`, `-Infinity`, and `NaN` +- `Uint8Array` +- `Date` +- `RegExp` +- `JSX` Elements +- Plain objects with string keys and serializable values +- Arrays containing serializable values +- Preact Signals (if the inner value is serializable) + +Circular references are supported. If an object or signal is referenced multiple +times, it is only serialized once and the references are restored upon +deserialization. + +> [warn]: Passing functions to an island is not supported. +> +> ```tsx +> // WRONG +> console.log("hey")} />; +> ``` + +### Passing JSX + +A powerful feature of Fresh is that you can pass server-rendered JSX to an +island via props. + +```tsx routes/index.tsx +import MyIsland from "../islands/my-island.tsx"; + +const app = new App() + .get("/", (ctx) => { + return ctx.render( + hello}> +

This text is rendered on the server

+
, + ); + }); +``` + +### Nesting islands + +Islands can be nested within other islands as well. In that scenario they act +like a normal Preact component, but still receive the serialized props if any +were present. + +In essence, Fresh allows you to mix static and interactive parts in your app in +a way that's most optimal for your app. We'll keep sending only the JavaScript +that is needed for the islands to the browser. + +```tsx route/index.tsx +import MyIsland from "../islands/my-island.tsx"; +import OtherIsland from "../islands/other-island.tsx"; + +// Later... +
+ + + +

Some more server rendered text

+
; +``` + +## Rendering islands on client only + +When using client-only APIs, like `EventSource` or `navigator.getUserMedia`, +this component will not run on the server as it will produce an error. To fix +this use the `IS_BROWSER` flag as a guard: + +```tsx islands/my-island.tsx +import { IS_BROWSER } from "fresh/runtime"; + +export function MyIsland() { + // Return any prerenderable JSX here which makes sense for your island + if (!IS_BROWSER) return
; + + // All the code which must run in the browser comes here! + // Like: EventSource, navigator.getUserMedia, etc. + return
; +} +``` diff --git a/docs/canary/concepts/layouts.md b/docs/canary/concepts/layouts.md new file mode 100644 index 00000000..9de5130e --- /dev/null +++ b/docs/canary/concepts/layouts.md @@ -0,0 +1,124 @@ +--- +description: | + Add a layout to provide common meta tags, context for application sub routes, and common layout. +--- + +A layout is defined in a `_layout.tsx` file in any sub directory (at any level) +under the `routes/` folder. It must contain a default export that is a regular +Preact component. Only one such layout is allowed per sub directory. + +```txt Project structure +└── routes +    ├── sub +    │ ├── page.tsx +    │   └── index.tsx + ├── other + │ ├── _layout.tsx # will be applied on top of `routes/_layout.tsx` + │ └── page.tsx + ├── _layout.tsx # will be applied to all routes + └── _app.tsx +``` + +The component to be wrapped is received via props, in addition to a few other +things. This allows for the introduction of a global container functioning as a +template which can be conditioned based on state and params. Note that any state +set by middleware is available via `props.state`. + +```tsx routes/sub/_layout.tsx +import { PageProps } from "$fresh/server.ts"; + +export default function Layout({ Component, state }: PageProps) { + // do something with state here + return ( +
+ +
+ ); +} +``` + +## Async layouts + +In case you need to fetch data asynchronously before rendering the layout, you +can use an async layout to do so. + +```tsx routes/sub/_layout.tsx +import { FreshContext } from "$fresh/server.ts"; + +export default async function Layout(req: Request, ctx: FreshContext) { + // do something with state here + const data = await loadData(); + + return ( +
+

{data.greeting}

+ +
+ ); +} +``` + +### Define helper + +To make it a little quicker to write async layouts, Fresh ships with a +`defineLayout` helper which automatically infers the correct types for the +function arguments. + +```tsx +import { defineLayout } from "$fresh/server.ts"; + +export default defineLayout(async (req, ctx) => { + const data = await loadData(); + + return ( +
+

{data.greeting}

+ +
+ ); +}); +``` + +## Opting out of layout inheritance + +Sometimes you want to opt out of the layout inheritance mechanism for a +particular route. This can be done via route configuration. Picture a directory +structure like this: + +```txt Project structure +└── routes +    ├── sub +    │ ├── _layout_.tsx +    │ ├── special.tsx # should not inherit layouts +    │   └── index.tsx + └── _layout.tsx +``` + +To make `routes/sub/special.tsx` opt out of rendering layouts we can set +`skipInheritedLayouts: true`. + +```tsx routes/sub/special.tsx +import { RouteConfig } from "$fresh/server.ts"; + +export const config: RouteConfig = { + skipInheritedLayouts: true, // Skip already inherited layouts +}; + +export default function MyPage() { + return

Hello world

; +} +``` + +You can skip already inherited layouts inside a layout file: + +```tsx routes/special/_layout.tsx +import { LayoutConfig } from "$fresh/server.ts"; + +export const config: LayoutConfig = { + skipInheritedLayouts: true, // Skip already inherited layouts +}; + +export default function MyPage() { + return

Hello world

; +} +``` diff --git a/docs/canary/concepts/middleware.md b/docs/canary/concepts/middleware.md new file mode 100644 index 00000000..7380e3db --- /dev/null +++ b/docs/canary/concepts/middleware.md @@ -0,0 +1,88 @@ +--- +description: | + Add middleware routes to intercept requests or responses for analytics purposes, access control, or anything else. +--- + +A middleware is a function that receives a [`Context`](/docs/canary/context) +object with the +[`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) and +returns a +[`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response). They +are typically used to set HTTP Headers, measure response times or fetch data and +pass it to another middleware. + +```tsx +const app = new App<{ greeting: string }>() + .use((ctx) => { + // Middleware to pass data + ctx.state.greeting = "Hello world"; + return ctx.next(); + }) + .use(async (ctx) => { + // Middleware to add a HTTP header + const res = await ctx.next(); + res.headers.set("server", "fresh server"); + return res; + }) + // A handler is a form of middleware that responds. Here we + // render HTML and return it. + .get("/", (ctx) => { + return ctx.render(

{ctx.state.greeting}

); + }); +``` + +Middlewares can be chained and combined in whatever way you desire. They are an +excellent way to make http-related logic reusable on the server. + +## Middleware helper + +Use the `define.middleware()` helper to get typings out of the box: + +```ts +import { define } from "./utils.ts"; + +const middleware = define.middleware(async (ctx) => { + console.log("my middleware"); + return await ctx.next(); +}); +``` + +## Included middlewares + +Fresh ships with the following middlewares built-in: + +- [cors()](/docs/canary/plugins/cors) - Set CORS HTTP headers +- [trailingSlash()](/docs/canary/plugins/trailing-slashes) - Enforce trailing + slashes + +## Filesystem-based middlewares + +With file system based routing you can define a middleware in a `_middleware.ts` +file inside the `routes/` folder or any of it's subfolders. + +```ts routes/foo/_middleware.ts +import { define } from "./utils.ts"; + +export default define.middleware(async (ctx) => { + console.log("my middleware"); + return await ctx.next(); +}); +``` + +You can also export an array of middlewares: + +```ts routes/foo/_middleware.ts +import { define } from "./utils.ts"; + +const middleware1 = define.middleware(async (ctx) => { + console.log("A"); + return await ctx.next(); +}); + +const middleware1 = define.middleware(async (ctx) => { + console.log("B"); + return await ctx.next(); +}); + +export default [middleware1, middleware2]; +``` diff --git a/docs/canary/concepts/routing.md b/docs/canary/concepts/routing.md new file mode 100644 index 00000000..e45a800d --- /dev/null +++ b/docs/canary/concepts/routing.md @@ -0,0 +1,32 @@ +--- +description: | + File based routing is the simplest way to do routing in Fresh apps. Additionally custom patterns can be configured per route. +--- + +Routing defines which middlewares and routes should respond to a particular +request. + +```ts +const app = new App() + .get("/", () => new Response("hello")) // Responds to: GET / + .get("/other", () => new Response("other")) // Responds to: GET /other + .post("/upload", () => new Response("upload")); // Responds to: POST /upload + .get("/books/:id", (ctx) => { + // Responds to: GET /books/my-book, /books/cool-book, etc + const id = ctx.params.id + return new Response(`Book id: ${id}`)); + }) + .get("/blog/:post/comments", () => { + // Responds to: GET /blog/my-post/comments, /blog/hello/comments, etc + const post = ctx.params.post + return new Response(`Blog post comments for post: ${post}`) + }) + .get("/foo/*", (ctx) => { + // Responds to: GET /foo/bar, /foo/bar/baz, etc + return new Response("foo")); + }) +``` + +Fresh supports the full +[`URLPattern`](https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API) +syntax for setting pathnames. diff --git a/docs/canary/concepts/static-files.md b/docs/canary/concepts/static-files.md new file mode 100644 index 00000000..98f8ca9b --- /dev/null +++ b/docs/canary/concepts/static-files.md @@ -0,0 +1,47 @@ +--- +description: | + Fresh has built-in support for serving static files. This is useful for serving images, CSS, and other static assets. +--- + +Static assets placed in the `static/` directory are served at the root of the +webserver via the `staticFiles()` middleware. They are streamed directly from +disk for optimal performance with +[`ETag`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/ETag) +headers. + +```ts +import { staticFiles } from "fresh"; + +const app = new App() + .use(staticFiles()); +``` + +## Caching headers + +By default, Fresh adds caching headers for the `src` and `srcset` attributes on +`` and `` tags. + +```jsx +// Caching headers will be automatically added +; +``` + +You can always opt out of this behaviour per tag, by adding the +`data-fresh-disable-lock` attribute. + +```jsx +// Opt-out of automatic caching headers +; +``` + +## Adding caching headers manually + +Use the `asset()` function to add caching headers manually. It will be served +with a cache lifetime of one year. + +```jsx +import { asset } from "fresh/runtime"; + +// Adding caching headers manually +View brochure; +``` diff --git a/docs/canary/deployment/deno-deploy.md b/docs/canary/deployment/deno-deploy.md new file mode 100644 index 00000000..dce3d4e0 --- /dev/null +++ b/docs/canary/deployment/deno-deploy.md @@ -0,0 +1,16 @@ +--- +description: "Deploy Fresh on Deno Deploy" +--- + +The recommended way to deploy Fresh is by using +[Deno Deploy](https://deno.com/deploy). It will automatically create branch +previews for pull requests, collect request and HTTP metrics, as well has +collect traces for you out of the box. + +1. Log in to [Deno Deploy](https://deno.com/deploy) +1. Create a new app +1. Link your GitHub repository +1. Pick the "Fresh" preset if it's not already detected automatically + +Every time you merge into the `main` branch a new production deployment will be +created. diff --git a/docs/canary/deployment/docker.md b/docs/canary/deployment/docker.md new file mode 100644 index 00000000..1543ac48 --- /dev/null +++ b/docs/canary/deployment/docker.md @@ -0,0 +1,50 @@ +--- +description: "Deploy Fresh with Docker" +--- + +You can deploy Fresh to any platform that can run Docker containers. Docker is a +tool to containerize projects and portably run them on any supported platform. + +When packaging your Fresh app for Docker, it is important that you set the +`DENO_DEPLOYMENT_ID` environment variable in your container. This variable needs +to be set to an opaque string ID that represents the version of your application +that is currently being run. This could be a Git commit hash, or a hash of all +files in your project. It is critical for the function of Fresh that this ID +changes when _any_ file in your project changes - if it doesn't, incorrect +caching **will** cause your project to not function correctly. + +Here is an example `Dockerfile` for a Fresh project: + +```dockerfile Dockerfile +FROM denoland/deno:1.38.3 + +ARG GIT_REVISION +ENV DENO_DEPLOYMENT_ID=${GIT_REVISION} + +WORKDIR /app + +COPY . . +RUN deno cache main.ts + +EXPOSE 8000 + +CMD ["run", "-A", "main.ts"] +``` + +To build your Docker image inside of a Git repository: + +```sh Terminal +$ docker build --build-arg GIT_REVISION=$(git rev-parse HEAD) -t my-fresh-app . +``` + +Then run your Docker container: + +```sh Terminal +$ docker run -t -i -p 80:8000 my-fresh-app +``` + +To deploy to a cloud provider, push it to a container registry and follow their +documentation. + +- [Amazon Web Services](https://docs.aws.amazon.com/AmazonECS/latest/userguide/create-container-image.html#create-container-image-push-ecr) +- [Google Cloud](https://cloud.google.com/container-registry/docs/pushing-and-pulling) diff --git a/docs/canary/deployment/production.md b/docs/canary/deployment/production.md new file mode 100644 index 00000000..7f83cce0 --- /dev/null +++ b/docs/canary/deployment/production.md @@ -0,0 +1,35 @@ +--- +description: "Create a production build of your app" +--- + +When shipping an app to production, we can run a build step that optimizes +assets for consumption in the browser. This step can be invoked by running: + +```sh Terminal +deno task build +# or +deno run -A dev.ts build +``` + +Once completed, it will have created a `_fresh` folder in the project directory +which contains the optimized assets. + +> [info]: The `_fresh` folder should not be committed to git. Exclude it via +> `.gitignore`. +> +> ```sh .gitignore +> # Ignore fresh build directory +> _fresh/ +> ``` + +## Running a production build + +To run Fresh in production mode, run the `start` task: + +```sh Terminal +deno task start +# or +deno run -A main.ts +``` + +Fresh will automatically pick up the optimized assets in the `_fresh` directory. diff --git a/docs/canary/getting-started/index.md b/docs/canary/getting-started/index.md new file mode 100644 index 00000000..df2864c5 --- /dev/null +++ b/docs/canary/getting-started/index.md @@ -0,0 +1,122 @@ +--- +description: | + In this chapter of the Fresh documentation, you'll be introduced to the + framework. Create a new project, run it locally, edit and create pages, fetch + data, handle user interactions, and deploy it. +--- + +Let's set up your first Fresh project. To create a new project, run this +command: + +```sh Terminal +deno run -Ar jsr:@fresh/init +``` + +This will span a short wizard that guides you through the setup, like the +project name, if you want to use tailwindcss and if you're using vscode. Your +project folder should look like this: + +```sh Project structure + +├── islands/ # Components that need JS to run client-side +│ └── Counter.tsx +├── routes/ # File system based routes +│   ├── api/ +│   │ └── [name].tsx # API route for /api/:name +│   ├── _app.tsx # Renders the outer content structure +│   └── index.tsx # Renders / +├── static/ # Contains static assets like css, logos, etc +│   └── ... +│   +├── deno.json # Contains dependencies, tasks, etc +├── dev.ts # Run this during development +└── main.ts # Run this for production +``` + +Run the `dev` task to launch your app in development mode: + +```sh Terminal +deno task dev +``` + +Go to the URL printed in the terminal to view your app. + +TODO IMAGE + +## Creating our first route + +Let's create a new about page at `/about`. We can do that by adding a new file +at `routes/about.tsx`. + +```tsx routes/about.tsx +import { define } from "../utils.ts"; + +export default define.page(() => { + return ( +
+

About

+

This is the about page.

+
+ ); +} +``` + +If we navigate to `/about` in the browser we'll see our newly created page. + +TODO: IMAGE + +## Create an island + +We're going to create a countdown component that requires JavaScript to function +in the browser. + +Create a new file at `islands/Countdown.tsx` + +```tsx islands/Countdown.tsx +export function Countdown(props: { target: string }) { + const count = useSignal(10); + + useEffect(() => { + const timer = setInterval(() => { + if (count.value <= 0) { + clearInterval(timer); + } + + count.value -= 1; + }, 1000); + + return () => clearInterval(timer); + }, []); + + if (count.value <= 0) { + return

Countdown: 🎉

; + } + + return

Countdown: {count}

; +} +``` + +Let's add the countdown to our about page: + +```tsx routes/about.tsx +import { define } from "../utils.ts"; +import { Countdown } from "../islands/Countdown.tsx"; + +export default define.page(() => { + return ( +
+

About

+

This is the about page.

+ +
+ ); +} +``` + +Now, we can see our countdown in action: + +TODO: IMAGE + +## Next steps + +TODO diff --git a/docs/canary/introduction/index.md b/docs/canary/introduction/index.md new file mode 100644 index 00000000..3eb7d00f --- /dev/null +++ b/docs/canary/introduction/index.md @@ -0,0 +1,75 @@ +--- +description: | + Fresh is a full stack modern web framework for JavaScript and TypeScript + developers, designed to build high-quality, performant, + and personalized web applications. +--- + +Fresh is a small, fast and extensible full stack web framework built on Web +Standards. It's designed for building high-quality, performant, and personalized +web applications. + +```tsx +import { App } from "fresh"; + +const app = new App() + .get("/", () => new Response("hello world")); + .get("/jsx", ctx => ctx.render(

render JSX!

)); + +app.listen(); +``` + +## Quick Start + +Create a new Fresh app by running: + +```sh Terminal +deno run -Ar jsr:@fresh/init +``` + +## Features + +The core idea powering Fresh is to render server generated HTML pages and only +ship JavaScript for areas in the page that need to be interactive. This is often +referred to as the +[Island Architecture](https://jasonformat.com/islands-architecture). + +- **Fast** 🚀 - Rendering is super fast thanks to [Preact][preact] and Deno's + [`precompile` transform](https://docs.deno.com/runtime/reference/jsx/#jsx-precompile-transform) +- **Lightweight** 🏎️ - Only ship the JavaScript you need +- **Extensible** 🧩 - Nearly every aspect can be customized +- **Powerful & small API** 🤗 - Familiar APIs make you productive quickly +- **Built-in OpenTelemetry** 📈 - Built-in support for OpenTelemetry + +## When to use Fresh + +Fresh is ideal for sites and apps that are primarily server rendered, like a +home page, an e-commerce shop or something like GitHub or Bluesky. + +- Web APIs +- E-Commerce shops +- Portfolio sites +- Landing pages & Documentation +- CRUD apps + +That said, if you want to build a Single-Page-App (=SPA), then Fresh is not the +right framework. + +## Who is using Fresh? + +Fresh powers [deno.com](https://deno.com) and [Deno Deploy][deno-deploy] among +many other projects at Deno. It's also used by [deco.cx](https://deco.cx/) for +e-commerce projects. + +## Where to host Fresh apps? + +Fresh is most often deployed on [Deno Deploy][deno-deploy] where it can be +deployed with 1-click and has out of the box integrations with metrics among +other things. + +Fresh projects can be deployed manually to any platform with [Deno][deno] like +via docker containers too. + +[preact]: https://preactjs.com +[deno]: https://deno.com +[deno-deploy]: https://deno.com/deploy diff --git a/docs/canary/plugins/cors.md b/docs/canary/plugins/cors.md new file mode 100644 index 00000000..0158932f --- /dev/null +++ b/docs/canary/plugins/cors.md @@ -0,0 +1,28 @@ +--- +description: "Set CORS HTTP headers with the cors middleware" +--- + +The `cors()` middleware can be used to add +[Cross-Origin-Resource-Sharing headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) +to HTTP requests. These allow the server to indicate which origins (domains, +scheme or port) other than its own is permitted to load resources from. + +```ts +import { cors } from "fresh"; + +const app = new App() + .use(cors({ + origin: "http://example.com", + allowHeaders: ["X-Custom-Header", "Upgrade-Insecure-Requests"], + allowMethods: ["POST", "GET", "OPTIONS"], + exposeHeaders: ["Content-Length", "X-Kuma-Revision"], + maxAge: 600, + credentials: true, + })) + .get("/", () => new Response("hello")); +``` + +## Options + +See the [API docs](https://jsr.io/@fresh/core/doc/~/cors) for a list of all +supported options diff --git a/docs/canary/plugins/index.md b/docs/canary/plugins/index.md new file mode 100644 index 00000000..36f8d47c --- /dev/null +++ b/docs/canary/plugins/index.md @@ -0,0 +1,25 @@ +--- +description: "Extend fresh with plugins" +--- + +Fresh itself can be extended through the methods available on the +[`App`](/docs/canary/concepts/app) class or on the `Builder` class. Most of the +features in Fresh itself are built using these APIs. + +## Custom middlewares + +If you need to modify requests, add HTTP headers or pass additional data to +other middlewares via `ctx.state`, then going with a middleware is the way to +go. + +```ts +const addXFreshHeader = define.middleware(async (ctx) => { + const res = await ctx.next(); + res.headers.set("X-Fresh", "served by Fresh"); + return res; +}); +``` + +Learn more about [middlewares](/docs/canary/concepts/middleware). + +TODO: Show more ways diff --git a/docs/canary/plugins/trailing-slashes.md b/docs/canary/plugins/trailing-slashes.md new file mode 100644 index 00000000..0ea34752 --- /dev/null +++ b/docs/canary/plugins/trailing-slashes.md @@ -0,0 +1,25 @@ +--- +description: "Ensure URLs always end or never end with trailing slashes" +--- + +The `trailingSlashes()` middleware can be used to ensure URL pathnames always +end with a slash character or will never end with one. It redirects the user's +request respectively. + +```ts +import { trailingSlashes } from "fresh"; + +const app = new App() + .use(trailingSlashes("never")) + .get("/", () => new Response("hello")); +``` + +Always append a trailing slash: + +```ts +import { trailingSlashes } from "fresh"; + +const app = new App() + .use(trailingSlashes("always")) + .get("/", () => new Response("hello")); +``` diff --git a/docs/canary/testing/index.md b/docs/canary/testing/index.md new file mode 100644 index 00000000..f3049b6e --- /dev/null +++ b/docs/canary/testing/index.md @@ -0,0 +1,105 @@ +--- +description: | + Add a global app wrapper to provide common meta tags or context for application routes. +--- + +To ensure that your application works as expected we can write tests. Any aspect +of Fresh can be tested as a whole together or in isolation. We use Deno's +built-in [test runner](https://docs.deno.com/runtime/fundamentals/testing/) to +write tests. + +## Testing middlewares + +To test [middlewares](/docs/canary/concepts/middleware) we're going to create a +dummy app and return the relevant info we want to check in a custom `/` handler. + +```ts +import { expect } from "@std/expect"; +import { App } from "fresh"; + +const middleware = define.middleware((ctx) => { + ctx.state.text = "middleware text"; + return await ctx.next(); +}); + +Deno.test("My middleware - sets ctx.state.text", async () => { + const handler = new App() + .use(middleware) + .get("/", (ctx) => new Response(ctx.state.text)) + .handler(); + + const res = await handler(new Request("http://localhost")); + const text = await res.text(); + + expect(text).toEqual("middleware text"); +}); +``` + +You can extend this pattern for other middlewares. When you have a middleware +that adds a header to the returned response, you can assert against that too. + +## Testing app wrapper or layouts + +Both the [app wrapper](/docs/canary/advanced/app-wrapper) component and +[layouts](/docs/canary/advanced/layouts) can be tested in the same way. + +```tsx +import { expect } from "@std/expect"; +import { App } from "fresh"; + +function AppWrapper({ Component }) { + return ( + + + + My App + + + + + + ); +} + +Deno.test("App Wrapper - renders title and content", async () => { + const handler = new App() + .appWrapper(AppWrapper) + .get("/", (ctx) => ctx.render(

hello

)) + .handler(); + + const res = await handler(new Request("http://localhost")); + const text = await res.text(); + + expect(text).toContain("My App"); + expect(text).toContain("Hello"); +}); +``` + +Same can be done for layouts. + +```tsx +import { expect } from "@std/expect"; +import { App } from "fresh"; + +function MyLayout({ Component }) { + return ( +
+

My Layout

+ +
+ ); +} + +Deno.test("MyLayout - renders heading and content", async () => { + const handler = new App() + .layout("*", MyLayout) + .get("/", (ctx) => ctx.render(

hello

)) + .handler(); + + const res = await handler(new Request("http://localhost")); + const text = await res.text(); + + expect(text).toContain("My Layout"); + expect(text).toContain("Hello"); +}); +``` diff --git a/docs/toc.ts b/docs/toc.ts index a337c4b9..51715540 100644 --- a/docs/toc.ts +++ b/docs/toc.ts @@ -18,54 +18,61 @@ const toc: RawTableOfContents = { canary: { label: "canary", content: { - "the-canary-version": { - title: "The canary version", - }, introduction: { title: "Introduction", - link: "latest", + link: "canary", }, "getting-started": { title: "Getting Started", - link: "latest", - pages: [ - ["create-a-project", "Create a project", "link:latest"], - ["running-locally", "Running locally", "link:latest"], - ["create-a-route", "Create a route", "link:latest"], - ["dynamic-routes", "Dynamic routes", "link:latest"], - ["custom-handlers", "Custom handlers", "link:latest"], - ["form-submissions", "Form submissions", "link:latest"], - ["adding-interactivity", "Adding interactivity", "link:latest"], - ["deploy-to-production", "Deploy to production", "link:latest"], - ], + link: "canary", }, concepts: { title: "Concepts", - link: "latest", + link: "canary", pages: [ - ["architecture", "Architecture", "link:latest"], - ["server-components", "Server Components", "link:latest"], - ["routing", "Routing", "link:latest"], - ["routes", "Routes", "link:latest"], - ["app-wrapper", "App wrapper", "link:latest"], - ["layouts", "Layouts", "link:latest"], - ["forms", "Forms", "link:latest"], - ["islands", "Interactive islands", "link:latest"], - ["static-files", "Static files", "link:latest"], - ["middleware", "Middlewares", "link:latest"], - ["error-pages", "Error pages", "link:latest"], - ["partials", "Partials", "link:latest"], - ["data-fetching", "Data fetching", "link:latest"], - ["ahead-of-time-builds", "Ahead-of-time Builds", "link:latest"], - ["deployment", "Deployment", "link:latest"], - ["plugins", "Plugins", "link:latest"], - ["updating", "Updating Fresh", "link:latest"], - ["server-configuration", "Server configuration", "link:latest"], + ["app", "App", "link:canary"], + ["middleware", "Middlewares", "link:canary"], + ["context", "Context", "link:canary"], + + ["routing", "Routing", "link:canary"], + + ["islands", "Islands", "link:canary"], + ["static-files", "Static files", "link:canary"], + + ["file-routing", "File routing", "link:canary"], ], }, - integrations: { - title: "Integrations", - link: "latest", + advanced: { + title: "Advanced", + link: "canary", + pages: [ + ["app-wrapper", "App wrapper", "link:canary"], + ["layouts", "Layouts", "link:canary"], + ["error-handling", "Error handling", "link:canary"], + ["partials", "Partials", "link:canary"], + ["forms", "Forms", "link:canary"], + ], + }, + deployment: { + title: "Deployment", + link: "canary", + pages: [ + ["production", "Production builds", "link:canary"], + ["deno-deploy", "Deno Deploy", "link:canary"], + ["docker", "Docker", "link:canary"], + ], + }, + testing: { + title: "Testing", + link: "canary", + }, + plugins: { + title: "Plugins", + link: "canary", + pages: [ + ["cors", "cors", "link:canary"], + ["trailing-slashes", "trailingSlashes", "link:canary"], + ], }, examples: { title: "Examples", @@ -73,16 +80,7 @@ const toc: RawTableOfContents = { pages: [ ["migration-guide", "Migration Guide", "link:canary"], ["modifying-the-head", "Modifying the ", "link:latest"], - ["writing-tests", "Writing tests", "link:latest"], - [ - "changing-the-src-dir", - "Changing the source directory", - "link:latest", - ], - ["init-the-server", "Initializing the server", "link:latest"], - ["dealing-with-cors", "Dealing with CORS", "link:latest"], ["creating-a-crud-api", "Creating a CRUD API", "link:latest"], - ["handling-complex-routes", "Handling complex routes", "link:latest"], ["rendering-markdown", "Rendering markdown", "link:latest"], ["rendering-raw-html", "Rendering raw HTML", "link:latest"], [ diff --git a/src/app.ts b/src/app.ts index 8dd732b1..583b2815 100644 --- a/src/app.ts +++ b/src/app.ts @@ -166,6 +166,10 @@ export let getBuildCache: (app: App) => BuildCache | null; // deno-lint-ignore no-explicit-any export let setBuildCache: (app: App, cache: BuildCache | null) => void; +/** + * Create an application instance that passes the incoming `Request` + * instance through middlewares and routes. + */ export class App { #router: Router> = new UrlPatternRouter< MiddlewareFn @@ -221,6 +225,9 @@ export class App { return this; } + /** + * Add one or more middlewares at the top or the specified path. + */ use(...middleware: MiddlewareFn[]): this; use(path: string, ...middleware: MiddlewareFn[]): this; use( @@ -244,6 +251,9 @@ export class App { return this; } + /** + * Set the app's 404 error handler. Can be a {@linkcode Route} or a {@linkcode MiddlewareFn}. + */ notFound(routeOrMiddleware: Route | MiddlewareFn): this { const route = typeof routeOrMiddleware === "function" ? { handler: routeOrMiddleware } @@ -304,31 +314,52 @@ export class App { return this; } + /** + * Add middlewares for GET requests at the specified path. + */ get(path: string, ...middlewares: MiddlewareFn[]): this { this.#addMiddleware("GET", path, middlewares); return this; } + /** + * Add middlewares for POST requests at the specified path. + */ post(path: string, ...middlewares: MiddlewareFn[]): this { this.#addMiddleware("POST", path, middlewares); return this; } + /** + * Add middlewares for PATCH requests at the specified path. + */ patch(path: string, ...middlewares: MiddlewareFn[]): this { this.#addMiddleware("PATCH", path, middlewares); return this; } + /** + * Add middlewares for PUT requests at the specified path. + */ put(path: string, ...middlewares: MiddlewareFn[]): this { this.#addMiddleware("PUT", path, middlewares); return this; } + /** + * Add middlewares for DELETE requests at the specified path. + */ delete(path: string, ...middlewares: MiddlewareFn[]): this { this.#addMiddleware("DELETE", path, middlewares); return this; } + /** + * Add middlewares for HEAD requests at the specified path. + */ head(path: string, ...middlewares: MiddlewareFn[]): this { this.#addMiddleware("HEAD", path, middlewares); return this; } + /** + * Add middlewares for all HTTP verbs at the specified path. + */ all(path: string, ...middlewares: MiddlewareFn[]): this { this.#addMiddleware("ALL", path, middlewares); return this; @@ -356,6 +387,10 @@ export class App { this.#routeDefs.push({ method, pattern: path, fns }); } + /** + * Merge another {@linkcode App} instance into this app at the + * specified path. + */ mountApp(path: string, app: App): this { const segmentPath = mergePath("", path); const segment = getOrCreateSegment(this.#root, segmentPath, true); @@ -484,6 +519,9 @@ export class App { }; } + /** + * Spawn a server for this app. + */ async listen(options: ListenOptions = {}): Promise { if (!options.onListen) { options.onListen = createOnListen(this.config.basePath, options); diff --git a/src/config.ts b/src/config.ts index 927f6154..5987c6da 100644 --- a/src/config.ts +++ b/src/config.ts @@ -43,6 +43,10 @@ export interface ResolvedFreshConfig { build: { outDir: string; }; + /** + * Serve fresh from a base path instead of from the root. + * "/foo/bar" -> http://localhost:8000/foo/bar + */ basePath: string; staticDir: string; /** diff --git a/src/context.ts b/src/context.ts index 243f2387..39c44b07 100644 --- a/src/context.ts +++ b/src/context.ts @@ -62,11 +62,14 @@ export class Context { * certain search parameters are set. */ readonly url: URL; - /** The original incoming `Request` object` */ + /** The original incoming {@linkcode Request} object. */ readonly req: Request; + /** The url parameters of the matched route pattern. */ readonly params: Record; + /** State object that is shared with all middlewares. */ readonly state: State = {} as State; data: unknown = undefined; + /** Error value if an error was caught (Default: null) */ error: unknown | null = null; readonly info: Deno.ServeHandlerInfo | Deno.ServeHandlerInfo; /** @@ -174,6 +177,12 @@ export class Context { }); } + /** + * Render JSX and return an HTML `Response` instance. + * ```tsx + * ctx.render(

hello world

); + * ``` + */ async render( // deno-lint-ignore no-explicit-any vnode: VNode | null, diff --git a/src/middlewares/cors.ts b/src/middlewares/cors.ts index 32f7ed5c..ce00651a 100644 --- a/src/middlewares/cors.ts +++ b/src/middlewares/cors.ts @@ -1,33 +1,40 @@ -import type { FreshContext } from "../context.ts"; +import type { Context } from "../context.ts"; import type { MiddlewareFn } from "./mod.ts"; export type CORSOptions = { + /** + * The value of [`Access-Control-Allow-Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Allow-Origin) CORS header + */ origin: | string | string[] - | (( - requestOrigin: string, - ctx: FreshContext, - ) => string | undefined | null); + | ((origin: string, ctx: Context) => string | undefined | null); + /** + * Sets the permitted methods for the [`Access-Control-Allow-Methods`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Allow-Methods) CORS header. + */ allowMethods?: string[]; + /** + * Indicate the HTTP headers that can be used during the actual request. Sets the [`Access-Control-Allow-Headers`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Allow-Headers) header + */ allowHeaders?: string[]; + /** + * The value of [`Access-Control-Max-Age`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Max-Age) CORS header + */ maxAge?: number; + /** + * The value of [`Access-Control-Allow-Credentials`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Allow-Credentials) CORS header + */ credentials?: boolean; + /** + * The value of [`Access-Control-Expose-Headers`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Expose-Headers) CORS header + */ exposeHeaders?: string[]; }; /** - * CORS Middleware for Fresh. - * Adapted from Hono's CORS middleware. - * Would like to express my gratitude to all the developers of Hono. + * CORS Middleware to set [`Cross-Origin-Resource-Sharing`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) headers. * * @param {CORSOptions} [options] - The options for the CORS middleware. - * @param {string | string[] | ((requestOrigin: string, ctx: FreshContext) => string | undefined | null)} [options.origin='*'] - The value of "Access-Control-Allow-Origin" CORS header. - * @param {string[]} [options.allowMethods=['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH']] - The value of "Access-Control-Allow-Methods" CORS header. - * @param {string[]} [options.allowHeaders=[]] - The value of "Access-Control-Allow-Headers" CORS header. - * @param {number} [options.maxAge] - The value of "Access-Control-Max-Age" CORS header. - * @param {boolean} [options.credentials] - The value of "Access-Control-Allow-Credentials" CORS header. - * @param {string[]} [options.exposeHeaders=[]] - The value of "Access-Control-Expose-Headers" CORS header. * @returns {(req: Request, ctx: FreshContext) => Promise} The Fresh middleware handler function. * * @example diff --git a/www/utils/markdown.ts b/www/utils/markdown.ts index f7d96046..72230e97 100644 --- a/www/utils/markdown.ts +++ b/www/utils/markdown.ts @@ -6,6 +6,7 @@ import "prismjs/components/prism-diff.js"; import "prismjs/components/prism-json.js"; import "prismjs/components/prism-bash.js"; import "prismjs/components/prism-yaml.js"; +import denoJson from "../../deno.json" with { type: "json" }; export { extractYaml as frontMatter } from "@std/front-matter"; @@ -55,7 +56,15 @@ class DefaultRenderer extends Marked.Renderer { depth, raw, }: Marked.Tokens.Heading): string { - const slug = slugger.slug(raw); + let slugInput = tokens.length === 1 && tokens[0].type === "codespan" + ? tokens[0].text + : raw; + + if (/^\..*\(\)$/.test(slugInput)) { + slugInput = slugInput.slice(1, -2); + } + + const slug = slugger.slug(slugInput); const text = this.parser.parseInline(tokens); this.headings.push({ id: slug, html: text }); return `${text}`; @@ -76,6 +85,12 @@ class DefaultRenderer extends Marked.Renderer { } override code({ lang: info, text }: Marked.Tokens.Code): string { + // For canary only + text = text.replaceAll( + /(@fresh\/init)/g, + `@fresh/init@${denoJson.version}`, + ); + // format: tsx // format: tsx my/file.ts // format: tsx "This is my title"