typeshttpresponsehttphandlerfreshjs

How and when to use the Handler and Handlers types?


There is no documentation for the Handler and Handlers types:

export type Handler<T = any, State = Record<string, unknown>> = (
  req: Request,
  ctx: FreshContext<State, T>,
) => Response | Promise<Response>;

export type Handlers<T = any, State = Record<string, unknown>> = {
  [K in router.KnownMethod]?: Handler<T, State>;
};

From Custom handlers | Fresh docs:

Handlers can have two forms: a plain function (catchall for all HTTP methods) or a plain object where each property is a function named by the HTTP method it handles.

With this examples:


export const handler: Handlers = {
  async GET(_req, ctx) {
    const resp = await ctx.render();
    resp.headers.set("X-Custom-Header", "Hello");
    return resp;
  },
};

So I take that Handlers is for the object version and Handler is for the function version. Still, I don't know what their type variables mean. I guess that they are the type of the response, but there is no error yielded to me with this test:

export const handler: Handlers<number> = {
  GET() {
    return new Response('a string')
  }
}

So how to use them correctly?


Solution

  • Look closely at Handler:

    export type Handler<T = any, State = Record<string, unknown>> = (
      req: Request,
      ctx: FreshContext<State, T>,
    ) => Response | Promise<Response>;
    

    Type variables T and State are for FreshContext. As HTTP response is just a string, there is no need for the Response to have any type variable. Hence the type variables for it are just there to help you remember what kind of context you have, and not affect on the return statement.