### Initialize and start a Fresh App
Source: https://fresh.deno.dev/docs/concepts/app
Basic setup for creating an App instance, defining routes, and starting the server.
```typescript
const app = new App()
.use(staticFiles())
.get("/", () => new Response("hello"));
// Start server
app.listen();
```
--------------------------------
### Clone and Setup Fresh Repository
Source: https://fresh.deno.dev/docs/contributing
Clone the Fresh repository and run the initial setup task to format, lint, type-check, and test the entire suite. This should be run before submitting any pull requests.
```bash
git clone https://github.com/denoland/fresh.git
cd fresh
deno task ok
```
--------------------------------
### Server Listening (`.listen()`)
Source: https://fresh.deno.dev/docs/concepts/app
Starts the Fresh development server.
```APIDOC
## Server Listening (`.listen()`)
### Description
Starts the Fresh development server, making the application accessible.
### Method
`.listen()`
### Endpoint
N/A
### Parameters
N/A
### Request Example
```typescript
// Start the server
app.listen();
```
### Response
N/A
```
--------------------------------
### Start production server
Source: https://fresh.deno.dev/docs/deployment
Runs the production server using the optimized assets in the _fresh directory.
```bash
deno task start
```
--------------------------------
### Install Dependencies
Source: https://fresh.deno.dev/docs/advanced/troubleshooting
Use this command to install project dependencies. Add the `-r` flag for a clean reinstall if caching issues are suspected.
```bash
deno install --allow-scripts
```
--------------------------------
### Quick Start with app.ws()
Source: https://fresh.deno.dev/docs/advanced/websockets
Use `app.ws()` for the simplest way to add a WebSocket endpoint. It automatically handles the upgrade and event wiring.
```typescript
import { App } from "fresh";
const app = new App()
.ws("/ws", {
open(socket) {
console.log("Client connected");
},
message(socket, event) {
socket.send(`Echo: ${event.data}`);
},
close(socket, code, reason) {
console.log("Client disconnected", code, reason);
},
});
```
--------------------------------
### Install @std/http package
Source: https://fresh.deno.dev/docs/examples/session-management
Add the standard library HTTP package to your project using the Deno CLI.
```bash
deno add jsr:@std/http
```
--------------------------------
### Setup Define Helper
Source: https://fresh.deno.dev/docs/advanced/define
Initialize the define helper once to share state types across the application.
```typescript
import { createDefine } from "fresh";
// Setup, do this once in a file and import it everywhere else.
export const define = createDefine<{ foo: string }>();
```
--------------------------------
### Listen for connections
Source: https://fresh.deno.dev/docs/concepts/app
Starts the server. Note that this should not be used when running via Vite dev server or deno serve.
```typescript
const app = new App()
.get("/", () => new Response("hello"));
app.listen();
```
```typescript
app.listen({ port: 4000 });
```
--------------------------------
### Build-time image optimization with Vite
Source: https://fresh.deno.dev/docs/concepts/static-files
Install and configure vite-imagetools to process images during the build pipeline.
```bash
deno add -D npm:vite-imagetools
```
```typescript
import { defineConfig } from "vite";
import { fresh } from "@fresh/plugin-vite";
import { imagetools } from "vite-imagetools";
export default defineConfig({
plugins: [fresh(), imagetools()],
});
```
```typescript
import heroAvif from "../static/hero.jpg?format=avif&w=800";
export default function Page() {
return ;
}
```
--------------------------------
### Define Routes in Fresh
Source: https://fresh.deno.dev/docs
Basic example showing how to define routes and render responses or JSX content using the App class.
```typescript
import { App } from "fresh";
const app = new App()
.get("/", () => new Response("hello world"))
.get("/jsx", (ctx) => ctx.render(
render JSX!
));
app.listen();
```
--------------------------------
### Fresh Test Utilities: Build and Server Setup
Source: https://fresh.deno.dev/docs/testing
These helper functions are essential for setting up your Fresh application for testing. `buildFreshApp` creates and builds the app, while `startTestServer` launches a local server for testing.
```typescript
import { createBuilder, type InlineConfig } from "vite";
import * as path from "@std/path";
// Default Fresh build configuration
export const FRESH_BUILD_CONFIG: InlineConfig = {
logLevel: "error",
root: "./",
build: { emptyOutDir: true },
environments: {
ssr: { build: { outDir: path.join("_fresh", "server") } },
client: { build: { outDir: path.join("_fresh", "client") } },
},
};
// Helper function to create and build the Fresh app
export async function buildFreshApp(config: InlineConfig = FRESH_BUILD_CONFIG) {
const builder = await createBuilder(config);
await builder.buildApp();
return await import("../_fresh/server.js");
}
// Helper function to start a test server
export function startTestServer(app: {
default: {
fetch: (req: Request) => Promise;
};
}) {
const server = Deno.serve({
port: 0,
handler: app.default.fetch,
});
const { port } = server.addr as Deno.NetAddr;
const address = `http://localhost:${port}`;
return { server, address };
}
```
--------------------------------
### Run Development Servers for Docs and Vite Demo
Source: https://fresh.deno.dev/docs/contributing
Start development servers for the documentation website and the Vite plugin demo. These use local Fresh packages, serving as integration tests.
```bash
deno task www # docs site dev server
deno task build-www # docs site production build
deno task demo # vite demo dev server
denodenotask demo:build # vite demo production build
denotask demo:start # serve vite demo production build
```
--------------------------------
### Upgrade Deno
Source: https://fresh.deno.dev/docs/advanced/troubleshooting
Run this command to install the latest Deno version, which may resolve issues fixed in newer releases.
```bash
deno upgrade
```
--------------------------------
### App Wrapper (`.appWrapper()`)
Source: https://fresh.deno.dev/docs/concepts/app
Applies a wrapper function around the entire application, useful for global context or setup.
```APIDOC
## App Wrapper (`.appWrapper()`)
### Description
Applies a wrapper function around the entire application. This is useful for setting up global context or performing actions before/after all requests.
### Method
`.appWrapper()`
### Endpoint
N/A
### Parameters
#### Wrapper Function
- **wrapper** (Function) - Required - A function that takes the application instance and returns a new application instance with the wrapper applied.
### Request Example
```typescript
// Example of using appWrapper (specific implementation not provided in source)
// const wrappedApp = app.appWrapper(async (app) => {
// await initializeGlobalState();
// return app;
// });
```
### Response
N/A
```
--------------------------------
### Example Dockerfile for Fresh Project
Source: https://fresh.deno.dev/docs/deployment/docker
This Dockerfile sets up a Fresh project for containerization. Ensure the DENO_DEPLOYMENT_ID is set to a unique identifier that changes with project file modifications to prevent caching issues.
```docker
FROM denoland/deno:latest
ARG GIT_REVISION
ENV DENO_DEPLOYMENT_ID=${GIT_REVISION}
WORKDIR /app
COPY . .
RUN deno install --allow-scripts
RUN deno task build
EXPOSE 8000
CMD ["deno", "serve", "-A", "_fresh/server.js"]
```
--------------------------------
### Configure build tasks in deno.json
Source: https://fresh.deno.dev/docs/deployment/deno-deploy
Ensure the build and start tasks are correctly defined to support the Deno Deploy build process.
```json
{
"tasks": {
"build": "vite build",
"start": "deno serve -A _fresh/server.js"
}
}
```
--------------------------------
### Test API Route Handler with Fresh App
Source: https://fresh.deno.dev/docs/testing
Test individual route handlers and business logic using the App pattern. This example imports an actual route handler and tests its GET method.
```typescript
import { expect } from "@std/expect";
import { App } from "fresh";
import { type State } from "../utils.ts";
// Import actual route handlers
import { handler as apiHandler } from "../routes/api/[name].tsx";
Deno.test("API route returns name", async () => {
const app = new App()
.get("/api/:name", apiHandler.GET)
.handler();
const response = await app(new Request("http://localhost/api/joe"));
const text = await response.text();
expect(text).toEqual("Hello, Joe!");
});
```
--------------------------------
### GET Request Handling (`.get()`)
Source: https://fresh.deno.dev/docs/concepts/app
Defines how to handle HTTP GET requests for specific routes.
```APIDOC
## GET Request Handling (`.get()`)
### Description
Responds to a `GET` request with the specified middlewares or handlers.
### Method
`.get()`
### Endpoint
[Full endpoint path with any path parameters]
### Parameters
#### Path Parameters
- **path** (string) - Required - The route path to match.
#### Middlewares/Handlers
- **middlewareOrHandler** (Function) - Required - One or more middleware functions or handlers.
### Request Example
```typescript
// Respond to GET request at /about
app.get("/about", async (ctx) => {
return new Response(`GET: ${ctx.url.pathname}`);
});
// Respond with multiple middlewares
app.get("/about", middleware1, middleware2, async (ctx) => {
return new Response(`GET: ${ctx.url.pathname}`);
});
// Respond with lazy middleware/handler
app.get("/about", async () => {
const mod = await import("./middleware-or-handler.ts");
return mod.default;
});
```
### Response
N/A
```
--------------------------------
### Vite Development and Build Commands
Source: https://fresh.deno.dev/docs/advanced/vite
Provides the Deno task commands to start Vite with Hot Module Replacement (HMR) and to build client assets.
```bash
deno task dev # starts Vite with HMR
deno task build # writes _fresh/server.js and client assets
deno task start # deno serve -A _fresh/server.js
```
--------------------------------
### Initialize and Use Builder
Source: https://fresh.deno.dev/docs/advanced/builder
Instantiate the Builder class with options and use it to build production assets or start a development server with live reload. Ensure to import Builder from 'fresh/dev'.
```typescript
import { Builder } from "fresh/dev";
const builder = new Builder({ target: "safari12" });
if (Deno.args.includes("build")) {
// This creates a production build
await builder.build();
} else {
// This starts a development server with live reload
await builder.listen(() => import("./main.ts"));
}
```
--------------------------------
### Handle GET requests with .get()
Source: https://fresh.deno.dev/docs/concepts/app
Define handlers for GET requests using single, multiple, or lazy middlewares.
```typescript
app.get("/about", async (ctx) => {
return new Response(`GET: ${ctx.url.pathname}`);
});
```
```typescript
app.get("/about", middleware1, middleware2, async (ctx) => {
return new Response(`GET: ${ctx.url.pathname}`);
});
```
```typescript
app.get("/about", async () => {
const mod = await import("./middleware-or-handler.ts");
return mod.default;
});
```
--------------------------------
### Documentation Page with Partials
Source: https://fresh.deno.dev/docs/advanced/partials
This example shows a typical documentation page structure with a sidebar and main content area. Partials can be used to update only the content section.
```typescript
import { define } from "../../utils.ts";
export default define.page(async (ctx) => {
const content = await loadContent(ctx.params.id);
return (
{content}
);
});
```
--------------------------------
### Install Vite and Fresh Vite Plugin
Source: https://fresh.deno.dev/docs/migration-guide
Add `jsr:@fresh/plugin-vite` and `npm:vite` to your `deno.json` imports. Note that Fresh’s Tailwind plugin is not needed when using Vite; use the Vite integration instead.
```bash
deno install npm:vite jsr:@fresh/plugin-vite
```
--------------------------------
### Ambiguous Route Conflict Example
Source: https://fresh.deno.dev/docs/concepts/file-routing
Illustrates an invalid configuration where two different route groups contain files that map to the same URL, causing ambiguity.
```text
└── /routes
├── (group-1)
│ └── about.tsx # Bad: Maps to same `/about` url
└── (group-2)
└── about.tsx # Bad: Maps to same `/about` url
```
--------------------------------
### Route Matching Priority Example
Source: https://fresh.deno.dev/docs/concepts/routing
Dynamic routes are checked in the order they are registered. The first matching route wins. Static routes always take precedence.
```typescript
const app = new App()
// This is checked first since it's registered first
.get("/posts/featured", () => new Response("Featured posts"))
// This is checked second - won't match "/posts/featured" because it's
// already handled above
.get("/posts/:id", (ctx) => new Response(`Post: ${ctx.params.id}`));
```
--------------------------------
### Custom OpenTelemetry Exporter Setup
Source: https://fresh.deno.dev/docs/advanced/opentelemetry
Set up a custom OpenTelemetry exporter in your application's entry point using the NodeSDK and a specific exporter like OTLPTraceExporter. Ensure the exporter URL is correctly configured.
```typescript
import { NodeSDK } from "@opentelemetry/sdk-node";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
const sdk = new NodeSDK({
traceExporter: new OTLPTraceExporter({
url: "https://your-collector.example.com/v1/traces",
}),
});
sdk.start();
```
--------------------------------
### Test Middleware with Fresh App
Source: https://fresh.deno.dev/docs/testing
Test custom middlewares by creating a dummy app and asserting the state changes. This example assumes a 'State' object with a 'text' property.
```typescript
import { expect } from "@std/expect";
import { App } from "fresh";
import { define, type State } from "../utils.ts";
const middleware = define.middleware((ctx) => {
ctx.state.text = "middleware text";
return ctx.next();
});
Deno.test("My middleware - sets ctx.state.text", async () => {
const handler = new App()
.use(middleware)
.get("/", (ctx) => {
return new Response(ctx.state.text || "");
})
.handler();
const res = await handler(new Request("http://localhost"));
const text = await res.text();
expect(text).toEqual("middleware text");
});
```
--------------------------------
### Render Markdown in a Fresh Route
Source: https://fresh.deno.dev/docs/examples/markdown
This Fresh route reads a markdown file, converts its content to HTML using @deno/gfm, and renders it on the page. Ensure the @deno/gfm package is installed.
```typescript
import { define } from "@/utils.ts";
import { CSS, render as renderMarkdown } from "@deno/gfm";
export default define.page(async () => {
const content = await Deno.readTextFile("./content/example.md");
const html = renderMarkdown(content);
return (
);
});
```
--------------------------------
### Test Layout Component with Fresh App
Source: https://fresh.deno.dev/docs/testing
Test custom layout components to ensure they render their heading and content as expected. This example demonstrates rendering a layout with a nested component.
```typescript
import { expect } from "@std/expect";
import { App } from "fresh";
import { define, type State } from "../utils.ts";
const MyLayout = define.layout(function MyLayout({ Component }) {
return (
))
.handler();
const res = await handler(new Request("http://localhost"));
const text = await res.text();
expect(text).toContain("My Layout");
expect(text).toContain("hello");
});
```
--------------------------------
### App Initialization and Basic Usage
Source: https://fresh.deno.dev/docs/concepts/app
Demonstrates how to initialize the App class and set up basic routes and middleware.
```APIDOC
## App Initialization and Basic Usage
### Description
Initializes the Fresh `App` class and configures basic routing and middleware.
### Method
Constructor and chaining methods
### Endpoint
N/A
### Parameters
#### Constructor Options
- **basePath** (string) - Optional - Serve the app from a sub-path instead of root. All routes will be prefixed with this path.
- **trustProxy** (boolean) - Optional - Set to `true` to make `ctx.url` reflect the client-facing URL when behind a trusted reverse proxy.
### Request Example
```typescript
const app = new App({
basePath: "/my-app",
trustProxy: true,
})
.use(staticFiles())
.get("/", () => new Response("hello"));
// Start server
app.listen();
```
### Response
N/A
```
--------------------------------
### Example Markdown Content
Source: https://fresh.deno.dev/docs/examples/markdown
This is an example of markdown content that will be converted to HTML. It includes headings, plain text, and a blockquote.
```markdown
## some heading
and some interesting text here
> oh look a blockquote
```
--------------------------------
### Initialize a Fresh Application
Source: https://fresh.deno.dev/docs
Use this command to scaffold a new Fresh project in your environment.
```bash
deno run -Ar jsr:@fresh/init
```
--------------------------------
### Instantiate independent islands
Source: https://fresh.deno.dev/docs/examples/sharing-state-between-islands
Example usage of the Counter component where each instance maintains its own state.
```tsx
```
--------------------------------
### listen() - Spawning a Server
Source: https://fresh.deno.dev/docs/concepts/app
Spawns a server and listens for incoming connections, internally calling `Deno.serve()`.
```APIDOC
## listen(options?)
### Description
Spawns a server and listens for incoming connections. This calls `Deno.serve()` internally.
### Method
`listen`
### Endpoint
N/A (This is a method call on the App instance)
### Parameters
#### Request Body
- **options** (Object) - Optional - An object to customize server behavior, such as the port.
### Request Example
```typescript
const app = new App()
.get("/", () => new Response("hello"));
// Listen on default port
app.listen();
// Listen on a specific port
app.listen({ port: 4000 });
```
> **Important:** `.listen()` is only used when running your app directly with `deno run -A main.ts`. The default project setup uses `deno task dev` (Vite dev server) and `deno task start` (`deno serve`), which spawn their own servers - calling `.listen()` alongside these will create a second server and cause `AddrInUse` errors.
> To customize the port in the default setup:
> * **Dev:** set `server.port` in `vite.config.ts`
> * **Prod:** pass `--port` to `deno serve` in your task, e.g. `"start": "deno serve --port 4000 -A _fresh/server.js"`
```
--------------------------------
### Identify non-serializable island props
Source: https://fresh.deno.dev/docs/advanced/serialization
Examples of invalid prop types that cannot be serialized for island hydration.
```tsx
// WRONG - functions cannot be serialized
console.log("clicked")} />
// WRONG - class instance loses its prototype
```
--------------------------------
### Run development server
Source: https://fresh.deno.dev/docs/getting-started
Launch the application in development mode.
```bash
deno task dev
```
--------------------------------
### Retrieve route pattern with .route
Source: https://fresh.deno.dev/docs/concepts/context
Get the matched route pattern string, or null if no match occurred.
```typescript
app.get("/foo/:id", (ctx) => {
console.log(ctx.route); // Logs: "/foo/:id"
// ...
});
```
--------------------------------
### Build and Compile Deno App
Source: https://fresh.deno.dev/docs/deployment/deno-compile
First, build your Deno app using `deno task build`. Then, generate a self-contained executable using `deno compile`. The `--include _fresh` flag embeds built assets, and `-A` grants all permissions.
```bash
deno task build
deno compile --output my-app --include _fresh -A _fresh/compiled-entry.js
```
--------------------------------
### Project file structure
Source: https://fresh.deno.dev/docs/getting-started
The standard directory layout for a Fresh project.
```text
├── components/ # Store other components here. Can be named differently
│ └── Button.tsx
├── islands/ # Components that need JS to run client-side
│ └── Counter.tsx
├── routes/ # [File system based routes](/docs/concepts/file-routing)
│ ├── api/
│ │ └── [name].tsx # API route for /api/:name
│ ├── [_app.tsx](/docs/concepts/app) # Renders the outer content structure
│ └── index.tsx # Renders /
├── static/ # Contains static assets like css, logos, etc
│ └── ...
│
├── client.ts # Client entry file that's loaded on every page.
├── main.ts # The server entry file of your app
├── deno.json # Contains dependencies, tasks, etc
└── [vite.config.ts](/docs/advanced/vite) # Vite configuration file
```
--------------------------------
### Build production assets
Source: https://fresh.deno.dev/docs/deployment
Executes the build task to optimize assets, creating a _fresh directory.
```bash
deno task build
```
--------------------------------
### Middleware Integration (`.use()`)
Source: https://fresh.deno.dev/docs/concepts/app
Explains how to add middlewares to the application pipeline using the `.use()` method.
```APIDOC
## Middleware Integration (`.use()`)
### Description
Adds one or more middlewares to the application. Middlewares are processed in the order they are added.
### Method
`.use()`
### Endpoint
N/A
### Parameters
#### Path Parameters
- **path** (string) - Optional - The path at which to apply the middleware.
#### Middlewares
- **middleware** (Function) - Required - A middleware function or a series of middleware functions.
### Request Example
```typescript
// Add a middleware at the root
app.use(async (ctx) => {
console.log("my middleware");
return await ctx.next();
});
// Add multiple middlewares
app.use(middleware1, middleware2, middleware3);
// Add middleware at a specific path
app.use("/foo/bar", middleware);
// Add lazy middleware
app.use("/foo/bar", async () => {
const mod = await import("./path/to/my/middleware.ts");
return mod.default;
});
```
### Response
N/A
```
--------------------------------
### Configure Vite with Fresh Plugin
Source: https://fresh.deno.dev/docs/migration-guide
Replace dev.ts with vite.config.ts and pass custom Fresh configuration to the Vite plugin. This setup is used for development builds.
```typescript
import {
defineConfig
} from "vite";
import {
fresh
} from "@fresh/plugin-vite";
import tailwindcss from "@tailwindcss/vite";
export default defineConfig({
plugins: [
fresh(),
tailwindcss(),
],
});
```
--------------------------------
### Basic JSON API Route
Source: https://fresh.deno.dev/docs/examples/api-routes
Define a basic API endpoint that returns a JSON response. This route handles GET requests and returns an array of users.
```typescript
import { define } from "@/utils.ts";
export const handlers = define.handlers({
GET(ctx) {
const users = [{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }];
return Response.json(users);
},
});
```
--------------------------------
### Passing State from Middleware in Fresh
Source: https://fresh.deno.dev/docs/concepts/data-fetching
Middleware can set values on `ctx.state` which are then accessible to downstream handlers and components. This example shows setting user information from a session.
```typescript
import { define } from "@/utils.ts";
export default define.middleware(async (ctx) => {
const session = await getSession(ctx.req);
ctx.state.user = session?.user ?? null;
return ctx.next();
});
```
--------------------------------
### Run Fresh Test Suite
Source: https://fresh.deno.dev/docs/contributing
Execute the full test suite for Fresh. Use flags to run specific test files, filter by name, or update snapshots after intentional output changes. All tests require the `-A` flag.
```bash
# All tests (parallel)
denotask test
# A specific test file
denotask test -A packages/fresh/src/app_test.ts
# Filter by test name
denotask test -A --filter "test name pattern"
# Update snapshots after intentional output changes
denotask test -A --update-snapshots path/to/test.ts
```
--------------------------------
### ALL Method Handling
Source: https://fresh.deno.dev/docs/concepts/app
Handles requests for all HTTP verbs to a specified path with optional middlewares.
```APIDOC
## ALL /api/foo
### Description
Respond to a request for all HTTP verbs with the specified middlewares.
### Method
ALL (GET, POST, PUT, DELETE, etc.)
### Endpoint
`/api/foo`
### Request Example
```json
{
"example": "Request body depends on the HTTP verb"
}
```
### Response
#### Success Response (200)
- **body** (string) - A response message.
#### Response Example
```json
{
"example": "hehe"
}
```
```
--------------------------------
### File-based Route Handler for Specific Methods
Source: https://fresh.deno.dev/docs/concepts/routing
In file-based routes, export a `handlers` object with method-specific functions like GET and POST. Ensure to import `define` from '@/utils.ts'.
```typescript
import { define } from "@/utils.ts";
export const handlers = define.handlers({
GET(ctx) {
return new Response(JSON.stringify({ users: [] }), {
headers: { "Content-Type": "application/json" },
});
},
POST(ctx) {
return new Response("Created", { status: 201 });
},
});
```
--------------------------------
### Connect to WebSocket from Browser
Source: https://fresh.deno.dev/docs/advanced/websockets
This snippet demonstrates how to establish a WebSocket connection from the browser. It dynamically determines the protocol (ws or wss) based on the current page's protocol and connects to the server. It also includes handlers for opening the connection, sending an initial message, and receiving messages.
```javascript
const protocol = location.protocol === "https:" ? "wss:" : "ws:";
const ws = new WebSocket(`${protocol}//${location.host}/ws`);
ws.onopen = () => {
ws.send("Hello from the client!");
};
ws.onmessage = (event) => {
console.log("Received:", event.data);
};
```
--------------------------------
### Managed Mode with ctx.upgrade()
Source: https://fresh.deno.dev/docs/advanced/websockets
Use `ctx.upgrade()` within a GET handler for file-based routes or when more control is needed. This mode automatically manages the WebSocket lifecycle with provided event handlers.
```typescript
import { define } from "@/utils.ts";
export const handlers = define.handlers({
GET(ctx) {
return ctx.upgrade({
open(socket) {
console.log("Client connected");
},
message(socket, event) {
socket.send(`Echo: ${event.data}`);
},
close(socket, code, reason) {
console.log("Disconnected", code, reason);
},
error(socket, event) {
console.error("WebSocket error", event);
},
});
},
});
```
--------------------------------
### Mounting Sub-applications (`.mountApp()`)
Source: https://fresh.deno.dev/docs/concepts/app
Allows mounting another Fresh application at a specific path.
```APIDOC
## Mounting Sub-applications (`.mountApp()`)
### Description
Mounts another Fresh application at a specified path, enabling modular application structures.
### Method
`.mountApp()`
### Endpoint
N/A
### Parameters
#### Path
- **path** (string) - Required - The base path where the sub-application will be mounted.
#### App Instance
- **subApp** (App) - Required - The Fresh `App` instance to mount.
### Request Example
```typescript
// Assume 'adminApp' is another Fresh App instance
// app.mountApp("/admin", adminApp);
```
### Response
N/A
```
--------------------------------
### Define a basic app wrapper
Source: https://fresh.deno.dev/docs/advanced/app-wrapper
Create a file-based app wrapper using the define.page utility to set global HTML tags.
```typescript
import { define } from "../utils.ts";
export default define.page(({ Component, url }) => {
return (
My App
);
});
```
--------------------------------
### Build Docker Image with Git Revision
Source: https://fresh.deno.dev/docs/deployment/docker
Builds a Docker image for your Fresh application, tagging it with the current Git commit hash as the build argument for DENO_DEPLOYMENT_ID.
```bash
docker build --build-arg GIT_REVISION=$(git rev-parse HEAD) -t my-fresh-app .
```
--------------------------------
### Method-Specific API Handlers
Source: https://fresh.deno.dev/docs/examples/api-routes
Implement different logic for various HTTP methods (GET, PUT, DELETE) within a single API route. Unhandled methods will return a 405 error.
```typescript
import { define } from "@/utils.ts";
export const handlers = define.handlers({
async GET(ctx) {
const post = await db.posts.find(ctx.params.id);
if (!post) {
return Response.json({ error: "Not found" }, { status: 404 });
}
return Response.json(post);
},
async PUT(ctx) {
const body = await ctx.req.json();
const post = await db.posts.update(ctx.params.id, body);
return Response.json(post);
},
async DELETE(ctx) {
await db.posts.delete(ctx.params.id);
return new Response(null, { status: 204 });
},
});
```
--------------------------------
### ALL Request Handling (`.all()`)
Source: https://fresh.deno.dev/docs/concepts/app
Defines how to handle requests for any HTTP method for specific routes.
```APIDOC
## ALL Request Handling (`.all()`)
### Description
Responds to requests for any HTTP method with the specified middlewares or handlers.
### Method
`.all()`
### Endpoint
[Full endpoint path with any path parameters]
### Parameters
#### Path Parameters
- **path** (string) - Required - The route path to match.
#### Middlewares/Handlers
- **middlewareOrHandler** (Function) - Required - One or more middleware functions or handlers.
### Request Example
```typescript
// Example for handling all methods at a path (specific implementation not provided in source)
// app.all("/api/data", async (ctx) => {
// // Handle GET, POST, PUT, DELETE, etc. for /api/data
// return new Response("Handled by .all()");
// });
```
### Response
N/A
```
--------------------------------
### Runtime Utilities: `fresh/runtime`
Source: https://fresh.deno.dev/docs/advanced/api-reference
Shared runtime utilities for both server and client code, safe to import in islands.
```APIDOC
## `fresh/runtime` API
### Description
Shared runtime utilities for both server and client code. Safe to import in islands.
### Exports
- **`IS_BROWSER`** (Constant): `true` in the browser, `false` on the server. Use to guard browser-only code.
- **`asset`** (Function): Add cache-busting query params to asset URLs. See Static Files documentation.
- **`assetSrcSet`** (Function): Apply `asset()` to all URLs in a `srcset` string.
- **`Partial`** (Component): Mark a region for partial updates. See Partials documentation.
- **`Head`** (Component): Add elements to the document ``. See `` element documentation.
- **`HttpError`** (Class): HTTP error class (re-exported from `fresh`).
### Types
(No specific types exported directly from `fresh/runtime` are listed in the provided text, beyond re-exports.)
```
--------------------------------
### Style Active Links with Tailwind CSS
Source: https://fresh.deno.dev/docs/examples/active-links
Apply styles to elements with the `aria-current` attribute in Tailwind CSS using bracket notation. This example shows how to style the current page link.
```javascript
function Menu() {
return (
Link to some page
);
}
```
--------------------------------
### Configure Runtime Port and Host
Source: https://fresh.deno.dev/docs/deployment/deno-compile
Set the `PORT` and `HOSTNAME` environment variables to configure the runtime behavior of your compiled Deno application.
```bash
PORT=4000 ./my-app
```
```bash
HOSTNAME=0.0.0.0 ./my-app
```
--------------------------------
### Import Fresh server-side utilities
Source: https://fresh.deno.dev/docs/advanced/api-reference
Use this import to access the main application class, middleware, and core server-side helpers.
```typescript
import { App, createDefine, HttpError, page, staticFiles } from "fresh";
```
--------------------------------
### Import Fresh development tools
Source: https://fresh.deno.dev/docs/advanced/api-reference
Use these tools specifically within build scripts or development configuration files.
```typescript
import { Builder } from "fresh/dev";
```
--------------------------------
### Configure Multiple Static Directories
Source: https://fresh.deno.dev/docs/advanced/builder
Specify an array of directories for static files using the `staticDir` option. The Builder will serve files from these directories in the order provided, with the first match taking precedence. This is useful for separating generated assets from hand-authored static files.
```typescript
const builder = new Builder({
staticDir: ["static", "generated"],
});
```
--------------------------------
### Bare Mode with ctx.upgrade()
Source: https://fresh.deno.dev/docs/advanced/websockets
In bare mode, `ctx.upgrade()` returns the raw `WebSocket` object, allowing you to manage its lifecycle and integrate with shared structures like chat rooms or pub/sub systems.
```typescript
import { define } from "@/utils.ts";
const clients = new Set();
export const handlers = define.handlers({
GET(ctx) {
const { socket, response } = ctx.upgrade();
socket.onopen = () => {
clients.add(socket);
};
socket.onmessage = (event) => {
// Broadcast to all connected clients
for (const client of clients) {
if (client.readyState === WebSocket.OPEN) {
client.send(event.data);
}
}
};
socket.onclose = () => {
clients.delete(socket);
};
return response;
},
});
```
--------------------------------
### Integrate Tailwind CSS Plugin
Source: https://fresh.deno.dev/docs/advanced/builder
Add the official Tailwind CSS plugin to your Fresh project by installing it via JSR and importing it into your `dev.ts`. This enables utility-first CSS generation based on class names used in JSX. Ensure `nodeModulesDir` is set to `manual` in `deno.json`.
```json
{
"name": "@example/my-cool-project"
+ "nodeModulesDir": "manual",
"imports": {
...
}
}
```
```typescript
import { Builder } from "fresh/dev";
import { tailwind } from "@fresh/plugin-tailwind";
const builder = new Builder();
tailwind(builder);
```
--------------------------------
### Define Basic Routes with HTTP Methods
Source: https://fresh.deno.dev/docs/concepts/routing
Use methods like .get(), .post(), .put(), .delete(), .head(), .patch(), and .options() to define specific route handlers. Use .all() to handle any HTTP method.
```typescript
import { App } from "fresh";
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", (ctx) => {
// 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");
});
```
```typescript
app.all("/api/health", () => new Response("ok"));
```
--------------------------------
### Main Entry Point: `fresh`
Source: https://fresh.deno.dev/docs/advanced/api-reference
The main entry point for server-side code in Fresh. It exports core classes and functions for building applications.
```APIDOC
## `fresh` API
### Description
The main entry point for server-side code. Exports core classes and functions.
### Exports
- **`App`** (Class): The main application class. See App documentation.
- **`staticFiles`** (Function): Middleware for serving static files. See Static Files documentation.
- **`createDefine`** (Function): Create type-safe `define.*` helpers. See Define Helpers documentation.
- **`page`** (Function): Return data from a handler to a page component. See Data Fetching documentation.
- **`HttpError`** (Class): Throw HTTP errors with status codes. See Error Handling documentation.
- **`cors`** (Function): CORS middleware. See cors documentation.
- **`csrf`** (Function): CSRF protection middleware. See csrf documentation.
- **`csp`** (Function): Content Security Policy middleware. See csp documentation.
- **`trailingSlashes`** (Function): Trailing slash enforcement middleware. See trailingSlashes documentation.
### Types
- **`Context` / `FreshContext`** (Interface): The request context passed to all middlewares and handlers.
- **`PageProps`** (Type): Props received by page components (`data`, `url`, `params`, `state`, etc.).
- **`Middleware` / `MiddlewareFn`** (Type): Middleware function type.
- **`HandlerFn`** (Type): Single handler function type.
- **`HandlerByMethod`** (Type): Object with per-method handler functions.
- **`RouteHandler`** (Type): Union of `HandlerFn` and `HandlerByMethod`.
- **`PageResponse`** (Type): Return type of `page()`.
- **`RouteConfig`** (Interface): Route configuration (`routeOverride`, `skipInheritedLayouts`, etc.).
- **`LayoutConfig`** (Interface): Layout configuration (`skipInheritedLayouts`, `skipAppWrapper`).
- **`Define`** (Interface): Type of the object returned by `createDefine()`.
- **`FreshConfig` / `ResolvedFreshConfig`** (Interface): App configuration types.
- **`ListenOptions`** (Interface): Options for `app.listen()`.
- **`Island`** (Type): Island component type.
- **`Method`** (Type): HTTP method union type.
- **`RouteData`** (Type): Data type returned by route handlers via `page()`.
- **`Lazy` / `MaybeLazy`** (Type): Utility types for lazily-loaded routes and middleware.
- **`CORSOptions`** (Interface): Options for `cors()`.
- **`CsrfOptions`** (Interface): Options for `csrf()`.
- **`CSPOptions`** (Interface): Options for `csp()`.
```
--------------------------------
### Create Cloudflare Worker Entry File
Source: https://fresh.deno.dev/docs/deployment/cloudflare-workers
Define the entry point for your Cloudflare Worker by creating a `server.js` file. This file should export a `fetch` handler that uses the Fresh server.
```javascript
import server from "./_fresh/server.js";
export default {
fetch: server.fetch,
};
```
--------------------------------
### Create and use a reusable plugin
Source: https://fresh.deno.dev/docs/plugins
Export a function returning a MiddlewareFn to create reusable logic, then register it using the App instance.
```typescript
import type { MiddlewareFn } from "fresh";
export function requestId(): MiddlewareFn<{ requestId: string }> {
return async (ctx) => {
ctx.state.requestId = crypto.randomUUID();
const res = await ctx.next();
res.headers.set("X-Request-Id", ctx.state.requestId);
return res;
};
}
```
```typescript
import { App, staticFiles } from "fresh";
import { requestId } from "./plugins/request-id.ts";
const app = new App()
.use(staticFiles())
.use(requestId())
.fsRoutes();
```
--------------------------------
### Serve static files
Source: https://fresh.deno.dev/docs/concepts/static-files
Use the staticFiles middleware to serve assets from the static directory at the root of the webserver.
```typescript
import { staticFiles } from "fresh";
const app = new App()
.use(staticFiles());
```
--------------------------------
### Attach Debugger to Vite with Deno
Source: https://fresh.deno.dev/docs/advanced/troubleshooting
Commands to run Vite with Deno and attach a debugger. Use `--inspect-brk` to pause execution on the first line.
```bash
deno run -A --inspect npm:vite
```
```bash
deno run -A --inspect-brk npm:vite
```
--------------------------------
### Enable Deno's Built-in OpenTelemetry
Source: https://fresh.deno.dev/docs/advanced/opentelemetry
Enable Deno's built-in OpenTelemetry support by setting the OTEL_DENO environment variable. This exports traces to an OTLP-compatible collector.
```bash
OTEL_DENO=true deno task start
```
--------------------------------
### Link Local Fresh Packages in External Projects
Source: https://fresh.deno.dev/docs/contributing
Configure your project's `deno.json` to use local Fresh packages instead of published JSR versions. This allows immediate reflection of local changes without rebuilding.
```json
{
"imports": {
"@fresh/core": "jsr:@fresh/core@^2.0.0",
"@fresh/plugin-vite": "jsr:@fresh/plugin-vite@^1.0.0"
},
"links": [
"../path/to/fresh/packages/fresh",
"../path/to/fresh/packages/plugin-vite"
]
}
```
--------------------------------
### Customize Global Transitions with CSS
Source: https://fresh.deno.dev/docs/advanced/view-transitions
Use the ::view-transition-old and ::view-transition-new pseudo-elements to define custom animations for the root transition.
```css
::view-transition-old(root) {
animation: fade-out 0.2s ease-in;
}
::view-transition-new(root) {
animation: fade-in 0.2s ease-out;
}
```
--------------------------------
### Basic ipFilter Configuration
Source: https://fresh.deno.dev/docs/plugins/ip-filter
Configure ipFilter with both deny and allow lists to manage access. Deny rules take precedence over allow rules.
```typescript
import { App, ipFilter } from "fresh";
const app = new App()
.use(ipFilter({
denyList: ["192.168.1.10", "10.0.0.0/8"],
allowList: ["192.168.1.0/24"],
}))
.get("/", () => new Response("hello"));
```
--------------------------------
### Import Fresh runtime utilities
Source: https://fresh.deno.dev/docs/advanced/api-reference
These utilities are safe to use in both server-side code and client-side islands.
```typescript
import {
asset,
assetSrcSet,
Head,
HttpError,
IS_BROWSER,
Partial,
} from "fresh/runtime";
```
--------------------------------
### Static File Routing (`.fsRoute()`)
Source: https://fresh.deno.dev/docs/concepts/app
Configures routing for static files from a specified directory.
```APIDOC
## Static File Routing (`.fsRoute()`)
### Description
Configures routing for static files from a specified directory.
### Method
`.fsRoute()`
### Endpoint
[Full endpoint path with any path parameters]
### Parameters
#### Path Parameters
- **path** (string) - Required - The route path prefix for static files.
- **directory** (string) - Required - The directory containing the static files.
### Request Example
```typescript
// Serve static files from the "./public" directory at the "/static" path
app.fsRoute("/static", "./public");
```
### Response
N/A
```
--------------------------------
### Development Tools: `fresh/dev`
Source: https://fresh.deno.dev/docs/advanced/api-reference
Development and build tools, primarily used in build scripts.
```APIDOC
## `fresh/dev` API
### Description
Development and build tools. Only used in `dev.ts` (legacy) or build scripts.
### Exports
- **`Builder`** (Class): Pre-Vite build system (legacy). See Builder documentation.
### Types
- **`BuildOptions`** (Interface): Options for `new Builder()`.
- **`ResolvedBuildConfig`** (Interface): Resolved build configuration.
- **`OnTransformArgs` / `OnTransformOptions` / `TransformFn`** (Type): Build plugin hook types.
```
--------------------------------
### Basic CSP Configuration
Source: https://fresh.deno.dev/docs/plugins/csp
Use this middleware to add Content-Security-Policy headers. Configure reportOnly, reportTo, and custom CSP directives as needed. Ensure correct imports.
```typescript
import { csp } from "fresh";
const app = new App()
.use(csp({
// If true, sets Content-Security-Policy-Report-Only header instead
// of Content-Security-Policy
reportOnly: true,
// If set, adds Reporting-Endpoints, report-to, and report-uri
// directive.
reportTo: "/api/csp-reports",
// Additional CSP directives to add or override the defaults
csp: [
"script-src 'self' 'unsafe-inline' 'https://example.com'",
],
}))
.get("/", () => new Response("hello"));
```
--------------------------------
### Supported Methods for Environment Variable Inlining
Source: https://fresh.deno.dev/docs/advanced/environment-variables
Demonstrates the correct and incorrect ways to access environment variables that Fresh can inline. Only direct access with literal strings is supported.
```typescript
// CORRECT
Deno.env.get("FRESH_PUBLIC_FOO");
process.env.FRESH_PUBLIC_FOO;
```
```typescript
// WRONG
const name = "FRESH_PUBLIC_FOO";
Deno.env.get(name);
process.env[name];
```
```typescript
// WRONG
const obj = Deno.env.toObject();
obj.FRESH_PUBLIC_FOO;
```
--------------------------------
### Testing with Builder Snapshots
Source: https://fresh.deno.dev/docs/advanced/builder
Integrate the Builder into your testing workflow by creating a build snapshot. This snapshot can then be applied to app instances to ensure consistent testing environments. It's recommended to create the snapshot once for performance.
```typescript
// Best to do this once instead of for every test case for
// performance reasons.
const builder = new Builder();
const applySnapshot = await builder.build({ snapshot: "memory" });
function testApp() {
const app = new App()
.get("/", () => new Response("hello"))
.fsRoutes();
// Applies build snapshot to this app instance.
applySnapshot(app);
return app;
}
Deno.test("My Test", async () => {
const handler = testApp().handler();
const response = await handler(new Request("http://localhost"));
const text = await response.text();
if (text !== "hello") {
throw new Error("fail");
}
});
```
--------------------------------
### Add middlewares with .use()
Source: https://fresh.deno.dev/docs/concepts/app
Register middlewares globally, at specific paths, or lazily.
```typescript
// Add a middleware at the root
app.use(async (ctx) => {
console.log("my middleware");
return await ctx.next();
});
```
```typescript
app.use(middleware1, middleware2, middleware3);
```
```typescript
app.use("/foo/bar", middleware);
```
```typescript
app.use("/foo/bar", async () => {
const mod = await import("./path/to/my/middleware.ts");
return mod.default;
});
```