Server-Side Rendering (SSR)
Note
SSR specifically refers to front-end frameworks (for example React, Preact, Vue, and Svelte) that support running the same application in Node.js, pre-rendering it to HTML, and finally hydrating it on the client. If you are looking for integration with traditional server-side frameworks, check out the Backend Integration guide instead.
The following guide also assumes prior experience working with SSR in your framework of choice, and will only focus on Vite-specific integration details.
Low-level API
This is a low-level API meant for library and framework authors. If your goal is to create an application, make sure to check out the higher-level SSR plugins and tools at Awesome Vite SSR section first. That said, many applications are successfully built directly on top of Vite's native low-level API.
Currently, Vite is working on an improved SSR API with the Environment API. Check out the link for more details.
Example Projects
Vite provides built-in support for server-side rendering (SSR). create-vite-extra contains example SSR setups you can use as references for this guide:
You can also scaffold these projects locally by running create-vite and choose Others > create-vite-extra under the framework option.
Source Structure
A typical SSR application will have the following source file structure:
- index.html
- server.js # main application server
- src/
- main.js # exports env-agnostic (universal) app code
- entry-client.js # mounts the app to a DOM element
- entry-server.js # renders the app using the framework's SSR APIThe index.html will need to reference entry-client.js and include a placeholder where the server-rendered markup should be injected:
<div id="app"><!--ssr-outlet--></div>
<script type="module" src="/src/entry-client.js"></script>You can use any placeholder you prefer instead of <!--ssr-outlet-->, as long as it can be precisely replaced.
Conditional Logic
If you need to perform conditional logic based on SSR vs. client, you can use
if (import.meta.envImportMeta.env: ImportMetaEnv.SSRImportMetaEnv.SSR: boolean) {
// ... server only logic
}This is statically replaced during build so it will allow tree-shaking of unused branches.
Setting Up the Dev Server
When building an SSR app, you likely want to have full control over your main server and decouple Vite from the production environment. It is therefore recommended to use Vite in middleware mode. Here is an example with express:
import fsmodule "node:fs" from 'node:fs'
import pathconst path: path.PlatformPath from 'node:path'
import expressfunction express(): ExpressCreates an Express application. The express() function is a top-level function exported by the express module.
from 'express'
import { createServerfunction createServer(inlineConfig?: InlineConfig | ResolvedConfig): Promise<ViteDevServer> as createViteServerfunction createViteServer(inlineConfig?: InlineConfig | ResolvedConfig): Promise<ViteDevServer> } from 'vite'
async function createServerfunction createServer(): Promise<void>() {
const appconst app: Express = expressfunction express(): ExpressCreates an Express application. The express() function is a top-level function exported by the express module.
()
// Create Vite server in middleware mode and configure the app type as
// 'custom', disabling Vite's own HTML serving logic so parent server
// can take control
const viteconst vite: ViteDevServer = await createViteServerfunction createViteServer(inlineConfig?: InlineConfig | ResolvedConfig): Promise<ViteDevServer>({
serverserver: {
middlewareMode: true;
}
: { middlewareModemiddlewareMode: true: true },
appTypeappType: "custom": 'custom'
})
// Use vite's connect instance as middleware. If you use your own
// express router (express.Router()), you should use router.use
// When the server restarts (for example after the user modifies
// vite.config.js), `vite.middlewares` is still going to be the same
// reference (with a new internal stack of Vite and plugin-injected
// middlewares). The following is valid even after restarts.
appconst app: Express.useApplication<Record<string, any>>.use: (...handlers: RequestHandler<ParamsDictionary, any, any, QueryString.ParsedQs, Record<string, any>>[]) => Express (+8 overloads)(viteconst vite: ViteDevServer.middlewaresViteDevServer.middlewares: Connect.ServerA connect app instance.
- Can be used to attach custom middlewares to the dev server.
- Can also be used as the handler function of a custom http server
or as a middleware in any connect-style Node.js frameworks
)
appconst app: Express.useApplication<Record<string, any>>.use: <"*all", {
all: string[];
}, any, any, QueryString.ParsedQs, Record<string, any>>(path: "*all", ...handlers: RequestHandler<{
all: string[];
}, any, any, QueryString.ParsedQs, Record<string, any>>[]) => Express (+8 overloads)
('*all', async (reqreq: Request<{
all: string[];
}, any, any, QueryString.ParsedQs, Record<string, any>>
, resres: Response<any, Record<string, any>, number>) => {
// serve index.html - we will tackle this next
})
appconst app: Express.listenApplication<Record<string, any>>.listen(port: number, callback?: (error?: Error) => void): Server (+5 overloads)Listen for connections.
A node http.Server is returned, with this
application (which is a Function) as its
callback. If you wish to create both an HTTP
and HTTPS server you may do so with the "http"
and "https" modules as shown here:
var http = require('http')
, https = require('https')
, express = require('express')
, app = express();
http.createServer(app).listen(80);
https.createServer({ ... }, app).listen(443);
(5173)
}
createServerfunction createServer(): Promise<void>()Here vite is an instance of ViteDevServer. vite.middlewares is a Connect instance which can be used as a middleware in any connect-compatible Node.js framework.
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:
import type { EnvironmentModuleNodeclass EnvironmentModuleNode, Plugininterface Plugin<A = any>There are two types of plugins in Vite. App plugins and environment plugins.
Environment Plugins are defined by a constructor function that will be called
once per each environment allowing users to have completely different plugins
for each of them. The constructor gets the resolved environment after the server
and builder has already been created simplifying config access and cache
management for environment specific plugins.
Environment Plugins are closer to regular rollup plugins. They can't define
app level hooks (like config, configResolved, configureServer, etc).
} from 'vite'
export function ssrReloadfunction ssrReload(): Plugin(): Plugininterface Plugin<A = any>There are two types of plugins in Vite. App plugins and environment plugins.
Environment Plugins are defined by a constructor function that will be called
once per each environment allowing users to have completely different plugins
for each of them. The constructor gets the resolved environment after the server
and builder has already been created simplifying config access and cache
management for environment specific plugins.
Environment Plugins are closer to regular rollup plugins. They can't define
app level hooks (like config, configResolved, configureServer, etc).
{
return {
nameOutputPlugin.name: stringThe name of the plugin, for use in error messages and logs.
: 'ssr-reload',
enforcePlugin<any>.enforce?: "pre" | "post" | undefinedEnforce plugin invocation tier similar to webpack loaders. Hooks ordering
is still subject to the order property in the hook object.
Plugin invocation order:
- alias resolution
enforce: 'pre' plugins
- vite core plugins
- normal plugins
- vite build plugins
enforce: 'post' plugins
- vite build post plugins
: 'post',
hotUpdatePlugin<any>.hotUpdate?: ObjectHook<(this: MinimalPluginContext & {
environment: DevEnvironment;
}, options: HotUpdateOptions) => Array<EnvironmentModuleNode> | void | Promise<Array<EnvironmentModuleNode> | void>> | undefined
Perform custom handling of HMR updates.
The handler receives an options containing changed filename, timestamp, a
list of modules affected by the file change, and the dev server instance.
-
The hook can return a filtered list of modules to narrow down the update.
e.g. for a Vue SFC, we can narrow down the part to update by comparing
the descriptors.
-
The hook can also return an empty array and then perform custom updates
by sending a custom hmr payload via environment.hot.send().
-
If the hook doesn't return a value, the hmr update will be performed as
normal.
: {
orderorder?: PluginOrder | undefined: 'post',
handlerhandler: (this: MinimalPluginContext & {
environment: DevEnvironment;
}, options: HotUpdateOptions) => Array<EnvironmentModuleNode> | void | Promise<Array<EnvironmentModuleNode> | void>
({ modulesmodules: EnvironmentModuleNode[], serverserver: ViteDevServer, timestamptimestamp: number }) {
if (this.environmentenvironment: DevEnvironmentVite-specific environment instance
.namePartialEnvironment.name: string !== 'ssr') return
const invalidatedModulesconst invalidatedModules: Set<EnvironmentModuleNode> = new Setvar Set: SetConstructor
new <EnvironmentModuleNode>(iterable?: Iterable<EnvironmentModuleNode> | null | undefined) => Set<EnvironmentModuleNode> (+1 overload)
<EnvironmentModuleNodeclass EnvironmentModuleNode>()
let hasSsrOnlyModuleslet hasSsrOnlyModules: boolean = false
for (const modconst mod: EnvironmentModuleNode of modulesmodules: EnvironmentModuleNode[]) {
if (modconst mod: EnvironmentModuleNode.fileEnvironmentModuleNode.file: string | null == null) continue
const clientModulesconst clientModules: Set<EnvironmentModuleNode> | undefined =
serverserver: ViteDevServer.environmentsViteDevServer.environments: Record<"client" | "ssr" | (string & {}), DevEnvironment>Module execution environments attached to the Vite server.
.clientclient: DevEnvironment.moduleGraphDevEnvironment.moduleGraph: EnvironmentModuleGraph.getModulesByFileEnvironmentModuleGraph.getModulesByFile(file: string): Set<EnvironmentModuleNode> | undefined(modconst mod: EnvironmentModuleNode.fileEnvironmentModuleNode.file: string)
if (clientModulesconst clientModules: Set<EnvironmentModuleNode> | undefined != null) continue
this.environmentenvironment: DevEnvironmentVite-specific environment instance
.moduleGraphDevEnvironment.moduleGraph: EnvironmentModuleGraph.invalidateModuleEnvironmentModuleGraph.invalidateModule(mod: EnvironmentModuleNode, seen?: Set<EnvironmentModuleNode>, timestamp?: number, isHmr?: boolean, softInvalidate?: boolean): void(
modconst mod: EnvironmentModuleNode,
invalidatedModulesconst invalidatedModules: Set<EnvironmentModuleNode>,
timestamptimestamp: number,
true,
)
hasSsrOnlyModuleslet hasSsrOnlyModules: boolean = true
}
if (hasSsrOnlyModuleslet hasSsrOnlyModules: boolean) {
serverserver: ViteDevServer.environmentsViteDevServer.environments: Record<"client" | "ssr" | (string & {}), DevEnvironment>Module execution environments attached to the Vite server.
.clientclient: DevEnvironment.hotDevEnvironment.hot: NormalizedHotChannel<any>Hot channel for this environment. If not provided or disabled,
it will be a noop channel that does nothing.
.sendNormalizedHotChannel<any>.send(payload: HotPayload): void (+1 overload)Broadcast events to all clients
({ typeFullReloadPayload.type: "full-reload": 'full-reload' })
return []
}
},
},
}
}Add ssrReload() to the plugins array passed to createViteServer in the example above. See the hotUpdate hook for details.
The next step is implementing the * handler to serve server-rendered HTML:
appvar app: e.Express.useApplication<Record<string, any>>.use: <"*all", {
all: string[];
}, any, any, QueryString.ParsedQs, Record<string, any>>(path: "*all", ...handlers: RequestHandler<{
all: string[];
}, any, any, QueryString.ParsedQs, Record<string, any>>[]) => e.Express (+8 overloads)
('*all', async (reqreq: Request<{
all: string[];
}, any, any, QueryString.ParsedQs, Record<string, any>>
, resres: Response<any, Record<string, any>, number>, nextnext: NextFunction) => {
const urlconst url: string = reqreq: Request<{
all: string[];
}, any, any, QueryString.ParsedQs, Record<string, any>>
.originalUrlRequest<P = ParamsDictionary, ResBody = any, ReqBody = any, ReqQuery = QueryString.ParsedQs, LocalsObj extends Record<string, any> = Record<string, any>>.originalUrl: string
try {
// 1. Read index.html
let templatelet template: string = fsmodule "node:fs".readFileSyncfunction readFileSync(path: fs.PathOrFileDescriptor, options: fs.ReadFileSyncOptionsWithStringEncoding | BufferEncoding): string (+3 overloads)Returns the contents of the path.
For detailed information, see the documentation of the asynchronous version of
this API: fs.readFile().
If the encoding option is specified then this function returns a
string. Otherwise it returns a buffer.
If buffer is provided and no encoding is specified, the returned {Buffer} is
a view over the supplied buffer containing only the bytes read. If the
supplied buffer is too small to contain the entire file, an error will be
thrown.
Similar to fs.readFile(), when the path is a directory, the behavior of
fs.readFileSync() is platform-specific.
import { readFileSync } from 'node:fs';
// macOS, Linux, and Windows
readFileSync('<directory>');
// => [Error: EISDIR: illegal operation on a directory, read <directory>]
// FreeBSD
readFileSync('<directory>'); // => <data>
(
pathconst path: path.PlatformPath.resolvepath.PlatformPath.resolve(...paths: string[]): stringThe right-most parameter is considered {to}. Other parameters are considered an array of {from}.
Starting from leftmost {from} parameter, resolves {to} to an absolute path.
If {to} isn't already absolute, {from} arguments are prepended in right to left order,
until an absolute path is found. If after using all {from} paths still no absolute path is found,
the current working directory is used as well. The resulting path is normalized,
and trailing slashes are removed unless the path gets resolved to the root directory.
(import.meta.dirnameImportMeta.dirname: stringThe directory name of the current module.
This is the same as the path.dirname() of the import.meta.filename.
Caveat: only present on file: modules.
, 'index.html'),
'utf-8',
)
// 2. Apply Vite HTML transforms. This injects the Vite HMR client,
// and also applies HTML transforms from Vite plugins, e.g. global
// preambles from @vitejs/plugin-react
templatelet template: string = await vitevar vite: ViteDevServer.transformIndexHtmlViteDevServer.transformIndexHtml(url: string, html: string, originalUrl?: string): Promise<string>Apply vite built-in HTML transforms and any plugin HTML transforms.
(urlconst url: string, templatelet template: string)
// 3. Load the server entry. ssrLoadModule automatically transforms
// ESM source code to be usable in Node.js! There is no bundling
// required, and provides efficient invalidation similar to HMR.
const { renderconst render: any } = await vitevar vite: ViteDevServer.ssrLoadModuleViteDevServer.ssrLoadModule(url: string, opts?: {
fixStacktrace?: boolean;
}): Promise<Record<string, any>>
Load a given URL as an instantiated module for SSR.
('/src/entry-server.js')
// 4. render the app HTML. This assumes entry-server.js's exported
// `render` function calls appropriate framework SSR APIs,
// e.g. ReactDOMServer.renderToString()
const appHtmlconst appHtml: any = await renderconst render: any(urlconst url: string)
// 5. Inject the app-rendered HTML into the template.
const htmlconst html: string = templatelet template: string.replaceString.replace(searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string (+3 overloads)Replaces text in a string, using a regular expression or search string.
(`<!--ssr-outlet-->`, () => appHtmlconst appHtml: any)
// 6. Send the rendered HTML back.
resres: Response<any, Record<string, any>, number>.statusResponse<any, Record<string, any>, number>.status(code: number): Response<any, Record<string, any>, number>Set status code.
(200).setResponse<any, Record<string, any>, number>.set(field: any): Response<any, Record<string, any>, number> (+1 overload)Set header field to val, or pass
an object of header fields.
Examples:
res.set('Foo', ['bar', 'baz']);
res.set('Accept', 'application/json');
res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
Aliased as res.header().
({ 'Content-Type': 'text/html' }).endStream.Writable.end(chunk: any, cb?: () => void): Response<any, Record<string, any>, number> (+2 overloads)Signals that no more data will be written, with one final chunk of data.
(htmlconst html: string)
} catch (efunction (local var) e: unknown) {
// If an error is caught, let Vite fix the stack trace so it maps back
// to your actual source code.
vitevar vite: ViteDevServer.ssrFixStacktraceViteDevServer.ssrFixStacktrace(e: Error): voidMutates the given SSR error by rewriting the stacktrace
(efunction (local var) e: unknown)
nextnext: NextFunction
(err?: any) => void (+2 overloads)
(efunction (local var) e: unknown)
}
})The dev script in package.json should also be changed to use the server script instead:
"scripts": {
- "dev": "vite"
+ "dev": "node server"
}Building for Production
To ship an SSR project for production, we need to:
- Produce a client build as normal;
- Produce an SSR build, which can be directly loaded via
import()so that we don't have to go through Vite'sssrLoadModule;
Our scripts in package.json will look like this:
{
"scripts": {
"dev": "node server",
"build:client": "vite build --outDir dist/client",
"build:server": "vite build --outDir dist/server --ssr src/entry-server.js"
}
}Note the --ssr flag which indicates this is an SSR build. It should also specify the SSR entry.
Then, in server.js we need to add some production specific logic by checking process.env.NODE_ENV:
Instead of reading the root
index.html, use thedist/client/index.htmlas the template, since it contains the correct asset links to the client build.Instead of
await vite.ssrLoadModule('/src/entry-server.js'), useimport('./dist/server/entry-server.js')(this file is the result of the SSR build).Move the creation and all usage of the
vitedev server behind dev-only conditional branches, then add static file serving middlewares to serve files fromdist/client.
Refer to the example projects for a working setup.
Generating Preload Directives
vite build supports the --ssrManifest flag which will generate .vite/ssr-manifest.json in build output directory:
- "build:client": "vite build --outDir dist/client",
+ "build:client": "vite build --outDir dist/client --ssrManifest",The above script will now generate dist/client/.vite/ssr-manifest.json for the client build (Yes, the SSR manifest is generated from the client build because we want to map module IDs to client files). The manifest contains mappings of module IDs to their associated chunks and asset files.
To leverage the manifest, frameworks need to provide a way to collect the module IDs of the components that were used during a server render call.
@vitejs/plugin-vue supports this out of the box and automatically registers used component module IDs on to the associated Vue SSR context:
const ctx = {}
const html = await vueServerRenderer.renderToString(app, ctx)
// ctx.modules is now a Set of module IDs that were used during the renderIn the production branch of server.js we need to read and pass the manifest to the render function exported by src/entry-server.js. This would provide us with enough information to render preload directives for files used by async routes! See demo source for a full example. You can also use this information for 103 Early Hints.
Pre-Rendering / SSG
If the routes and the data needed for certain routes are known ahead of time, we can pre-render these routes into static HTML using the same logic as production SSR. This can also be considered a form of Static-Site Generation (SSG). See demo pre-render script for working example.
SSR Externals
Dependencies are "externalized" from Vite's SSR transform module system by default when running SSR. This speeds up both dev and build.
If a dependency needs to be transformed by Vite's pipeline, for example, because Vite features are used untranspiled in them, they can be added to ssr.noExternal.
For linked dependencies, they are not externalized by default to take advantage of Vite's HMR. If this isn't desired, for example, to test dependencies as if they aren't linked, you can add it to ssr.external.
Working with Aliases
If you have configured aliases that redirect one package to another, you may want to alias the actual node_modules packages instead to make it work for SSR externalized dependencies. Both Yarn and pnpm support aliasing via the npm: prefix.
SSR-specific Plugin Logic
Some frameworks such as Vue or Svelte compile components into different formats based on client vs. SSR. To support conditional transforms, Vite passes an additional ssr property in the options object of the following plugin hooks:
resolveIdloadtransform
Example:
export function mySSRPluginfunction mySSRPlugin(): import("vite").Plugin() {
return {
nameOutputPlugin.name: stringThe name of the plugin, for use in error messages and logs.
: 'my-ssr',
transformPlugin<any>.transform?: ObjectHook<(this: TransformPluginContext, code: string, id: string, options?: {
moduleType: ModuleType;
ssr?: boolean | undefined;
}) => Promise<TransformResult> | TransformResult, {
filter?: {
id?: StringFilter<string | RegExp>;
code?: StringFilter<string | RegExp>;
moduleType?: ModuleTypeFilter;
};
}> | undefined
Can be used to transform individual modules.
Note that it's possible to return only properties and no code transformations.
You can use
{@linkcode
PluginContext.getModuleInfo
this.getModuleInfo()
}
to find out the previous values of meta, moduleSideEffects inside this hook.
(codecode: string, idid: string, optionsoptions: {
moduleType: ModuleType;
ssr?: boolean | undefined;
} | undefined
) {
if (optionsoptions: {
moduleType: ModuleType;
ssr?: boolean | undefined;
} | undefined
?.ssrssr?: boolean | undefined) {
// perform ssr-specific transform...
}
},
}
}The options object in load and transform is optional, Rollup is not currently using this object but may extend these hooks with additional metadata in the future.
Note
Before Vite 2.7, this was informed to plugin hooks with a positional ssr param instead of using the options object. All major frameworks and plugins are updated but you may find outdated posts using the previous API.
SSR Target
The default target for the SSR build is a node environment, but you can also run the server in a Web Worker. Packages entry resolution is different for each platform. You can configure the target to be Web Worker using the ssr.target set to 'webworker'.
SSR Bundle
In some cases like webworker runtimes, you might want to bundle your SSR build into a single JavaScript file. You can enable this behavior by setting ssr.noExternal to true. This will do two things:
- Treat all dependencies as
noExternal - Throw an error if any Node.js built-ins are imported
SSR Resolve Conditions
By default package entry resolution will use the conditions set in resolve.conditions for the SSR build. You can use ssr.resolve.conditions and ssr.resolve.externalConditions to customize this behavior.
Vite CLI
The CLI commands $ vite dev and $ vite preview can also be used for SSR apps. You can add your SSR middlewares to the development server with configureServer and to the preview server with configurePreviewServer.
Note
Use a post hook so that your SSR middleware runs after Vite's middlewares.
