0
0
DenoHow-ToBeginner ยท 4 min read

How to Use Handlers in Fresh Framework for Deno

In Fresh, you use handlers by exporting a handler object with HTTP method functions like GET or POST from your page or API route file. Each function receives a Request and returns a Response, letting you control how your app responds to requests.
๐Ÿ“

Syntax

Handlers in Fresh are exported as an object named handler. Each key in this object is an HTTP method (like GET, POST, etc.) and its value is an async function that takes a Request and returns a Response.

This pattern lets you define how your app responds to different HTTP methods on the same route.

typescript
export const handler = {
  GET: async (req: Request) => {
    return new Response("Hello from GET handler!");
  },
  POST: async (req: Request) => {
    const data = await req.json();
    return new Response(`Received POST data: ${JSON.stringify(data)}`);
  },
};
๐Ÿ’ป

Example

This example shows a Fresh route handler that responds differently to GET and POST requests. The GET returns a simple greeting, and the POST echoes back JSON data sent by the client.

typescript
import { Handlers } from "$fresh/server.ts";

export const handler: Handlers = {
  GET: async (req) => {
    return new Response("Welcome to Fresh GET handler!");
  },
  POST: async (req) => {
    try {
      const json = await req.json();
      return new Response(`You sent: ${JSON.stringify(json)}`, { status: 200 });
    } catch {
      return new Response("Invalid JSON", { status: 400 });
    }
  },
};
Output
GET request response: Welcome to Fresh GET handler! POST request response with JSON {"name":"Deno"}: You sent: {"name":"Deno"}
โš ๏ธ

Common Pitfalls

  • Not exporting the handler object correctly will cause Fresh to ignore your handlers.
  • Forgetting to return a Response object from handler functions leads to errors.
  • Mixing up async/await can cause unhandled promises; always use async functions.
  • Not handling different HTTP methods properly can cause unexpected behavior.
typescript
/* Wrong: Missing export and not returning Response */
const handler = {
  GET(req) {
    "Hello"; // Does not return a Response
  },
};

/* Right: Exported and returns Response */
export const handler = {
  GET: async (req) => {
    return new Response("Hello");
  },
};
๐Ÿ“Š

Quick Reference

Use this quick guide to remember how to define handlers in Fresh:

PartDescription
export const handlerExports the handler object for Fresh to use
GET, POST, etc.HTTP methods as keys in the handler object
async function(req)Function that handles the request
return new Response()Send back an HTTP response
req.json()Parse JSON body from request (for POST, PUT)
โœ…

Key Takeaways

Always export a handler object with HTTP method keys in Fresh route files.
Each handler method must return a Response object to send back to the client.
Use async functions to handle requests and parse JSON bodies safely.
Handle different HTTP methods explicitly to control route behavior.
Avoid common mistakes like missing exports or not returning Response.