magne4000 / universal-middleware

Write middleware once, target Hono, Cloudflare, Express, and more
https://universal-middleware.dev/
MIT License
28 stars 1 forks source link

feat: allow skipping returning a response #24

Closed brillout closed 2 months ago

brillout commented 2 months ago

The following doesn't seem to work when the condition is false and no response is returned.

// This middleware will return an early response if given header is missing
const guardMiddleware = ((config) => (request, ctx) => {
  if (!request.headers.has(config.header)) {
    return new Response("Header not present", {
      status: 401,
    });
  }
  // else we do nothing

  // Using `satisfies` to not lose return type
}) satisfies Get<[Config], UniversalMiddleware>;

This error is thrown:

TypeError: Cannot read properties of undefined (reading 'body')
    at sendResponse (file:///home/rom/tmp/my-app/node_modules/.pnpm/@universal-middleware+express@0.2.3/node_modules/@universal-middleware/express/dist/index.js:71:35)
magne4000 commented 2 months ago

Using it as a Middleware or Handler? Currently a Handler MUST always return a Response to avoid undefined behavior.

brillout commented 2 months ago

It's for writing a universal handler for Vike: if there isn't any pages/_error then it doesn't return a response. Quickly looking at the documentation I don't see the difference between middleware and handler, but let me have a closer look at the docs.

brillout commented 2 months ago

It's also needed for self-routing all the +middleware.

magne4000 commented 2 months ago

The standard approach (that still needs some documentation around it) for this use case would be to return an Error for undefined behaviors. Those undefined behaviors are ones that are server dependent, i.e. returning undefined in an Express handler does not have the same meaning for Hono.