deno icon indicating copy to clipboard operation
deno copied to clipboard

`deno serve`: support using the fetch handler as the default export

Open pomdtr opened this issue 1 year ago • 2 comments

In https://val.town, you declare a server by using the fetch handler as your module default export.

export default function(req: Request) {
   return new Response("hello world")
}

One interesting property is that it makes it easy to add middlewares on top of servers:

// cors.ts
export function cors(handler) {
    return async (req) {
       const resp = await handler(req)
       resp.headers.set("access-control-allow-origin", "*");
       return resp
    }
}

// cors_server.ts
import handler from "./server.ts"

export default cors(handler)

What do you think of adding support for this convention in deno serve ?

pomdtr avatar May 16 '24 09:05 pomdtr

Can you explain a bit more what is the proposed convention here? Using any default export as a handler?

bartlomieju avatar May 16 '24 11:05 bartlomieju

Currently deno serve expect the default export to be an object, with a fetch method:

export default {
  async fetch(request) {
    return new Response("Hello world!");
  },
};

I think exporting the fetch handler directly should also be supported.

export default async function(request) {
  return new Response("Hello world!");
}

pomdtr avatar May 16 '24 14:05 pomdtr