vite-ssr
vite-ssr copied to clipboard
[Bug] Crashing Completely if Error Occurs in SSR During Development
Currently facing a issue where vite and everything crashes during development is a error occurs during SSR in development. The error is as follows:
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at new NodeError (internal/errors.js:322:7)
at writeAfterEnd (_http_outgoing.js:694:15)
at ServerResponse.end (_http_outgoing.js:815:7)
at viteErrorMiddleware (/home/director/repositories/@social/testing/node_modules/vite/dist/node/chunks/dep-611778e0.js:36138:17)
at call (/home/director/repositories/@social/testing/node_modules/vite/dist/node/chunks/dep-611778e0.js:41433:7)
at next (/home/director/repositories/@social/testing/node_modules/vite/dist/node/chunks/dep-611778e0.js:41381:5)
at call (/home/director/repositories/@social/testing/node_modules/vite/dist/node/chunks/dep-611778e0.js:41446:3)
at next (/home/director/repositories/@social/testing/node_modules/vite/dist/node/chunks/dep-611778e0.js:41381:5)
at call (/home/director/repositories/@social/testing/node_modules/vite/dist/node/chunks/dep-611778e0.js:41446:3)
at next (/home/director/repositories/@social/testing/node_modules/vite/dist/node/chunks/dep-611778e0.js:41381:5)
Emitted 'error' event on ServerResponse instance at:
at writeAfterEndNT (_http_outgoing.js:753:7)
at processTicksAndRejections (internal/process/task_queues.js:83:21) {
code: 'ERR_STREAM_WRITE_AFTER_END'
}
After some digging I found that this bit of code is where the issues start.
https://github.com/frandiox/vite-ssr/blob/fad2ca867992e544110cbc228cba3fc6041222fa/src/dev/server.ts#L132-L139
As we can see, if there is a error while rendering, it is caught here and the response is ended with the template html being passed back to the browser. That's all fine and dandy till we call next and then vite's error middleware is ran, which as we can see with the link below:
https://github.com/vitejs/vite/blob/main/packages/vite/src/node/server/middlewares/error.ts#L65-L90
Also ends the response, causing a write after end error.
I'm not sure the solution but it's probably going to be checking if the dev server is in middleware mode similarly to this bit here
https://github.com/frandiox/vite-ssr/blob/fad2ca867992e544110cbc228cba3fc6041222fa/src/dev/server.ts#L175-L177
And not send the template html/end the response if it's not enabled. Looking at vite's code here
https://github.com/vitejs/vite/blob/main/packages/vite/src/node/server/index.ts#L572
Shows that it could also be fixed by having the dev server run in middleware mode which prevents vite's error handler from ending the response.