Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions docs/guide/ssr.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,52 @@ createServer()

Here `vite` is an instance of [ViteDevServer](./api-javascript#vitedevserver). `vite.middlewares` is a [Connect](https://github.com/senchalabs/connect) instance which can be used as a middleware in any connect-compatible Node.js framework.

::: tip SSR-only module updates
By default, updating a module that is only imported by the SSR environment does not reload the page in the browser. Framework integrations usually handle this for you. For a low-level custom SSR setup, you can add a plugin that reloads the browser when an SSR-only module changes:

```ts twoslash
import type { EnvironmentModuleNode, Plugin } from 'vite'

export function ssrReload(): Plugin {
return {
name: 'ssr-reload',
enforce: 'post',
hotUpdate: {
order: 'post',
handler({ modules, server, timestamp }) {
if (this.environment.name !== 'ssr') return

const invalidatedModules = new Set<EnvironmentModuleNode>()
let hasSsrOnlyModules = false

for (const mod of modules) {
if (mod.id == null) continue
const clientModule =
server.environments.client.moduleGraph.getModuleById(mod.id)
if (clientModule != null) continue
Comment on lines +123 to +127

this.environment.moduleGraph.invalidateModule(
mod,
invalidatedModules,
timestamp,
true,
)
hasSsrOnlyModules = true
}

if (hasSsrOnlyModules) {
server.environments.client.hot.send({ type: 'full-reload' })
return []
}
},
},
}
}
```

Add `ssrReload()` to the `plugins` array passed to `createViteServer` in the example above. See the [`hotUpdate` hook](./api-environment-plugins#the-hotupdate-hook) for details.
:::

The next step is implementing the `*` handler to serve server-rendered HTML:

```js twoslash [server.js]
Expand Down
Loading