Skip to content

Use Vite's error handler for failed Service Worker requests #56

Closed

Description

@kazupon

Summary

  • Goal: When middleware throws while the Service Worker handles a request, respond with Vite's error response and log the error through the Vite logger.
  • Current gap: createServer() from @vrowzer/vite-dev-server/service-worker has two problems:
    1. The error handler is registered on a different Hono instance from the one that handles requests. With a non-root basePath, which Vrowzer always uses, Hono's default error handler answers instead of errorMiddleware.
    2. errorMiddleware calls logError(), which reads server.environments.client.hot. The Service Worker-side server object has no environments, so the handler throws whenever it does run.
  • Effect:
    • In Vrowzer, failed requests return Hono's plain-text Internal Server Error with status 500. Vite's error page and Vite's error log are never produced.
    • With basePath /, the default of createServer(), the error handler throws, app.fetch() rejects, and respondWith() should produce a network error.
  • Request: Register the error handler on the app that handles requests, and make logError() safe for the Service Worker's server object. Fix both together: fixing only the registration would turn Vrowzer's 500 responses into network errors.
  • Verification status: Both paths were reproduced with temporary unit tests (see Details). Browser behavior has not been checked.
  • Related: Found while analyzing #44.
  • Note: This issue was rewritten after filing. The first version described only the basePath / case and did not apply to Vrowzer's configuration.

Details

Failure paths, verification, requested behavior, and acceptance criteria

Current implementation

Reviewed at 71c1a71.

Error handler registration:

logError():

  • The handler calls logError(), which sends an HMR error payload through server.environments.client.hot.send().
  • The Service Worker's server object has no environments (see the ViteDevServerForServiceWorker type). The call throws TypeError: Cannot read properties of undefined (reading 'client').
  • Hono passes that exception to the same handler again (compose() and Hono#dispatch). The handler throws again, so app.fetch() rejects. handle() passes the rejected promise to respondWith().
  • This path runs today only when basePath is /, the default of createServer(). In this repository, packages/vite-dev-server/test-public/test-sw.ts uses it, but the browser test that loads it is not part of any test project.

Requests that reach the error handler include transform failures rethrown by the transform middleware and index.html failures rethrown by the index HTML middleware.

The existing errorMiddleware tests register the handler on the app that handles the request, with a mock server that has environments.client.hot.send. They cover neither problem.

Verification

Temporary unit tests in the vite-dev-server:unit:node project reproduced both paths, and were removed afterwards. They follow the order in service-worker.ts: the app later given to handle() is created first, basePath() replaces it before middleware and onError() are registered, and requests are dispatched through the original app.

function setup(basePath: string) {
  const server = { config: { base: basePath, logger: { error: vi.fn() } } } as unknown as ViteDevServer
  let middlewares = new Hono<ViteEnv, BlankSchema, '/'>()
  const dispatchApp = middlewares // what handle(middlewares) keeps
  if (basePath !== '/') {
    middlewares = middlewares.basePath(basePath) as typeof middlewares
  }
  middlewares.use('*', async (_c, next) => {
    await next()
  })
  middlewares.use('*', async () => {
    throw new Error('transform failed')
  })
  middlewares.onError(errorMiddleware(server, false))
  return { dispatchApp, server }
}

// Non-root basePath, as in Vrowzer: Hono's default handler answers
const preview = setup('/__preview__/')
const res = await preview.dispatchApp.request('/__preview__/x')
expect(res.status).toBe(500)
expect(await res.text()).toBe('Internal Server Error')
expect(preview.server.config.logger.error).not.toHaveBeenCalled()

// basePath '/': errorMiddleware runs, throws, and the request rejects
await expect(setup('/').dispatchApp.request('/x')).rejects.toThrow(
  new TypeError("Cannot read properties of undefined (reading 'client')")
)

Requested behavior

  • Register the error handler on the Hono instance that handles requests. For example, apply basePath() before passing the app to handle().
  • Make logError() safe for the Service Worker's server object. The minimal fix is to skip the HMR payload when environments is absent. Delivering the payload to the Web Worker's HMR channel, so the client can show the error overlay, can be handled separately.
  • Fix both in the same change.
  • Mark changes to the forked Vite code with a NOTE(kazupon) comment, following the existing convention.

Acceptance criteria

  • With a non-root basePath, a request whose middleware throws returns the 500 HTML response from errorMiddleware, and the error is logged through server.config.logger.
  • With basePath /, the same request returns a 500 response instead of rejecting.
  • A unit test covers errorMiddleware with a server shaped like the Service Worker's (no environments).
  • The existing errorMiddleware tests still pass.
  • In a browser, a Vrowzer preview request for a module with a transform error returns Vite's error page with status 500 instead of the plain-text response.

Errors that cross from the Web Worker keep only name, message, stack, code, and id (serializeRpcMessage()), so the error page will not include loc or frame. Carrying more detail is outside this issue.

Activity

  1. added
    bug
    on Sep 30, 2026
  2. changed the title [-]Return a 500 response instead of a network error when Service Worker middleware throws[/-] [+]Use Vite's error handler for failed Service Worker requests[/+] on Oct 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions