### 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 Hero; } ``` -------------------------------- ### 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 (

Here comes a markdown post:

{/* deno-lint-ignore react-no-danger */}