Skip to content

Instantly share code, notes, and snippets.

@yusukebe
Created March 25, 2025 02:22
Show Gist options
  • Save yusukebe/a454ef0c72b9317b11aa7b7d5b814d15 to your computer and use it in GitHub Desktop.
Save yusukebe/a454ef0c72b9317b11aa7b7d5b814d15 to your computer and use it in GitHub Desktop.
import { ServerResponse } from 'node:http'
function ssrHotReload(): Plugin {
return {
name: 'vite-plugin-ssr-hot-reload',
apply: 'serve',
configureServer(server) {
const injectScript = `<script type="module" src="/@vite/client"></script>`
server.middlewares.use((req, res, next) => {
let buffer = ''
const originalWrite = res.write.bind(res) as ServerResponse['write']
const originalEnd = res.end.bind(res) as ServerResponse['end']
res.write = ((chunk: any) => {
buffer += chunk.toString()
return true
}) as typeof res.write
res.end = ((chunk: any) => {
if (chunk) {
buffer += chunk.toString()
}
const contentType = res.getHeader('content-type') || ''
if (typeof contentType === 'string' && contentType.includes('text/html')) {
buffer += `\n${injectScript}\n`
res.setHeader('content-length', Buffer.byteLength(buffer))
}
originalWrite(buffer)
originalEnd()
}) as typeof res.end
next()
})
},
handleHotUpdate: ({ server, modules }) => {
const isSSR = modules.some((mod) => mod._ssrModule)
if (isSSR) {
server.hot.send({ type: 'full-reload' })
return []
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment