> This package is auto-generated. For pull requests please see [src/entries/web-server-renderer.js](https://github.com/vuejs/vue/blob/dev/src/platforms/web/server-renderer.js).
Creates a `bundleRenderer` instance using pre-compiled application bundle. The `bundle` argument can be one of the following:
- An absolute path to generated bundle file (`.js` or `.json`). Must start with `/` to be treated as a file path.
- A bundle object generated by `vue-ssr-webpack-plugin`.
- A string of JavaScript code.
See [Creating the Server Bundle](#creating-the-server-bundle) for more details.
For each render call, the code will be re-run in a new context using Node.js' `vm` module. This ensures your application state is discrete between requests, and you don't need to worry about structuring your application in a limiting pattern just for the sake of SSR.
Render the bundled app to a string. Same callback interface with `renderer.renderToString`. The optional context object will be passed to the bundle's exported function.
Render the bundled app to a stream. Same stream interface with `renderer.renderToStream`. The optional context object will be passed to the bundle's exported function.
Note that the cache object should at least implement `get` and `set`. In addition, `get` and `has` can be optionally async if they accept a second argument as callback. This allows the cache to make use of async APIs, e.g. a redis client:
Provide a template for the entire page's HTML. The template should contain a comment `<!--vue-ssr-outlet-->` which serves as the placeholder for rendered app content.
In addition, when both a template and a render context is provided (e.g. when using the `bundleRenderer`), the renderer will also automatically inject the following properties found on the render context:
-`context.styles`: (string) any inline CSS that should be injected into the head of the page. Note that `vue-loader` 10.2.0+ (which uses `vue-style-loader` 2.0) will automatically populate this property with styles used in rendered components.
-`context.state`: (Object) initial Vuex store state that should be inlined in the page as `window.__INITIAL_STATE__`. The inlined JSON is automatically sanitized with [serialize-javascript](https://github.com/yahoo/serialize-javascript).
Explicitly declare the base directory for the server bundle to resolve node_modules from. This is only needed if your generated bundle file is placed in a different location from where the externalized NPM dependencies are installed.
Note that the `basedir` is automatically inferred if you use `vue-ssr-webpack-plugin` or provide an absolute path to `createBundleRenderer` as the first argument, so in most cases you don't need to provide this option. However, this option does allow you to explicitly overwrite the inferred value.
- only used when the `template` option is also provided
Provide a client build manifest object generated by `vue-ssr-webpack-plugin`. With the client manifest, the `bundleRenderer` has webpack build information of both the server and client, and thus will be able to automatically infer and inject asset links into the rendered HTML. For more details, see [Creating the Client Manifest](#creating-the-client-manifest).
---
### shouldPreload
> New in 2.3.0
- only used in `createBundleRenderer`
- only used when the `template` and `clientManifest` options are also provided
When a client manifest is present, the renderer will automatically inject [preload and prefetch directives](https://medium.com/reloading/preload-prefetch-and-priorities-in-chrome-776165961bbf) into the `<head>` section.
For other types of assets such as images or fonts, how much and what to preload will be scenario-dependent. You can control precisely what to preload using the `shouldPreload` option:
When we bundle our front-end code with a module bundler such as webpack, it can introduce some complexity when we want to reuse the same code on the server. For example, if we use `vue-loader`, TypeScript or JSX, the code cannot run natively in Node. Our code may also rely on some webpack-specific features such as file handling with `file-loader` or style injection with `style-loader`, both of which can be problematic when running inside a native Node module environment.
The most straightforward solution to this is to leverage webpack's `target: 'node'` feature and simply use webpack to bundle our code on both the client AND the server.
Having a compiled server bundle also provides another advantage in terms of code organization. In a typical Node.js app, the server is a long-running process. If we run our application modules directly, the instantiated modules will be shared across every request. This imposes some inconvenient restrictions to the application structure: we will have to avoid any use of global stateful singletons (e.g. the store), otherwise state mutations caused by one request will affect the result of the next.
Instead, it's more straightforward to run our app "fresh", in a sandboxed context for each request, so that we don't have to think about avoiding state contamination across requests.
The application bundle can be either a string of bundled code (not recommended due to lack of source map support), or a special object of the following type:
Although theoretically you can use any build tool to generate the bundle, it is recommended to use webpack + `vue-loader` + [vue-ssr-webpack-plugin](https://github.com/vuejs/vue-ssr-webpack-plugin) for this purpose. The plugin will automatically turn the build output into a single JSON file that you can then pass to `createBundleRenderer`. This setup works seamlessly even if you use webpack's on-demand code splitting features such as dynamic `import()`.
The typical workflow is setting up a base webpack configuration file for the client-side, then modify it to generate the server-side bundle with the following changes:
1. Set `target: 'node'` and `output: { libraryTarget: 'commonjs2' }` in your webpack config.
2. Add [vue-ssr-webpack-plugin](https://github.com/vuejs/vue-ssr-webpack-plugin) to your webpack plugins. This plugin automatically generates the bundle as a single JSON file which contains all the files and source maps of the entire bundle. This is particularly important if you use Webpack's code-splitting features that result in a multi-file bundle.
3. In your server-side entry point, export a function. The function will receive the render context object (passed to `bundleRenderer.renderToString` or `bundleRenderer.renderToStream`), and should return a Promise, which should eventually resolve to the app's root Vue instance:
When using the `bundleRenderer`, we will by default bundle every dependency of our app into the server bundle as well. This means on each request these depdencies will need to be parsed and evaluated again, which is unnecessary in most cases.
We can optimize this by externalizing dependencies from your bundle. During the render, any raw `require()` calls found in the bundle will return the actual Node module from your rendering process. With Webpack, we can simply list the modules we want to externalize using the [`externals` config option](https://webpack.github.io/docs/configuration.html#externals):
``` js
// webpack.config.js
module.exports = {
// this will externalize all modules listed under "dependencies"
Since externalized modules will be shared across every request, you need to make sure that the dependency is **idempotent**. That is, using it across different requests should always yield the same result - it cannot have global state that may be changed by your application. Interactions between externalized modules are fine (e.g. using a Vue plugin).
`vue-server-renderer` 2.2 supports rendering the entire HTML page with the `template` option. 2.3 introduces another new feature, which allows us to pass a manifest of our client-side build to the `bundleRenderer`. This provides the renderer with information of both the server AND client builds, so it can automatically infer and inject preload / prefetch directives and script tags into the rendered HTML. This is particularly useful when rendering a bundle that leverages webpack's on-demand code splitting features: we can ensure the right chunks are preloaded / prefetched, and also directly embed `<script>` tags for needed async chunks in the HTML to avoid waterfall requests on the client, thus improving TTI (time-to-interactive).
To generate a client manifest, you need to add the client plugin to your client webpack config. In addition:
- Make sure to use `CommonsChunkPlugin` to split the webpack runtime into its own entry chunk, so that async chunks can be injected **after** the runtime and **before** your main app code.
- Since in this case `vue-server-renderer` will be dynamically injecting the asset links, you don't need to use `html-webpack-plugin`. However, the setup only handles JavaScript. If you want to use `html-webpack-plugin` for embedding other types of assets (e.g fonts), you can still use it - just make sure to configure it with `inject: false` so that it doesn't duplicate-inject the scripts.
Note that cachable component **must also define a unique "name" option**. This is necessary for Vue to determine the identity of the component when using the
bundle renderer.
With a unique name, the cache key is thus per-component: you don't need to worry about two components returning the same key. A cache key should contain sufficient information to represent the shape of the render result. The above is a good implementation if the render result is solely determined by `props.item.id`. However, if the item with the same id may change over time, or if render result also relies on another prop, then you need to modify your `getCacheKey` implementation to take those other variables into account.
If the renderer hits a cache for a component during render, it will directly reuse the cached result for the entire sub tree. So **do not cache a component containing child components that rely on global state**.
In most cases, you shouldn't and don't need to cache single-instance components. The most common type of components that need caching are ones in big lists. Since these components are usually driven by objects in database collections, they can make use of a simple caching strategy: generate their cache keys using their unique id plus the last updated timestamp:
In server-rendered output, the root element will have the `server-rendered="true"` attribute. On the client, when you mount a Vue instance to an element with this attribute, it will attempt to "hydrate" the existing DOM instead of creating new DOM nodes.
In development mode, Vue will assert the client-side generated virtual DOM tree matches the DOM structure rendered from the server. If there is a mismatch, it will bail hydration, discard existing DOM and render from scratch. **In production mode, this assertion is disabled for maximum performance.**
### Hydration Caveats
One thing to be aware of when using SSR + client hydration is some special HTML structures that may be altered by the browser. For example, when you write this in a Vue template:
``` html
<table>
<tr><td>hi</td></tr>
</table>
```
The browser will automatically inject `<tbody>` inside `<table>`, however, the virtual DOM generated by Vue does not contain `<tbody>`, so it will cause a mismatch. To ensure correct matching, make sure to write valid HTML in your templates.