Repository navigation
Description
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-workerhas two problems:- 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 oferrorMiddleware. errorMiddlewarecallslogError(), which readsserver.environments.client.hot. The Service Worker-side server object has noenvironments, so the handler throws whenever it does run.
- The error handler is registered on a different Hono instance from the one that handles requests. With a non-root
- Effect:
- In Vrowzer, failed requests return Hono's plain-text
Internal Server Errorwith status 500. Vite's error page and Vite's error log are never produced. - With
basePath/, the default ofcreateServer(), the error handler throws,app.fetch()rejects, andrespondWith()should produce a network error.
- In Vrowzer, failed requests return Hono's plain-text
- 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:
createServer()creates the Hono app and immediately passes it tohandle(). The fetch handler keeps using that original app.listen()later replacesmiddlewareswithmiddlewares.basePath(basePath)whenbasePathis not/.- Hono's
basePath()returns a clone that shares the router, so middleware added through the clone still runs for the original app.errorHandler, however, is a per-instance property copied at clone time. middlewares.onError(errorMiddleware(...))therefore sets the handler on the clone only. The original app keeps Hono's default handler, which callsconsole.error()and returnsc.text('Internal Server Error', 500).- Vrowzer always uses a non-root base path:
normalizePreviewBasePath()rejects/, and the Service Worker passesresolvePreviewBasePath()asbasePath.
logError():
- The handler calls
logError(), which sends an HMRerrorpayload throughserver.environments.client.hot.send(). - The Service Worker's server object has no
environments(see theViteDevServerForServiceWorkertype). The call throwsTypeError: Cannot read properties of undefined (reading 'client'). - Hono passes that exception to the same handler again (
compose()andHono#dispatch). The handler throws again, soapp.fetch()rejects.handle()passes the rejected promise torespondWith(). - This path runs today only when
basePathis/, the default ofcreateServer(). In this repository,packages/vite-dev-server/test-public/test-sw.tsuses 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 tohandle(). - Make
logError()safe for the Service Worker's server object. The minimal fix is to skip the HMR payload whenenvironmentsis 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 fromerrorMiddleware, and the error is logged throughserver.config.logger. - With
basePath/, the same request returns a 500 response instead of rejecting. - A unit test covers
errorMiddlewarewith a server shaped like the Service Worker's (noenvironments). - The existing
errorMiddlewaretests 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
[-]Return a 500 response instead of a network error when Service Worker middleware throws[/-][+]Use Vite's error handler for failed Service Worker requests[/+]