Understanding Server-Side Rendering (SSR) in Vue: Principles and Implementation
This article explains the principles and implementation of server‑side rendering (SSR) in Vue, comparing CSR and SSR, detailing how Vue’s vue‑server‑renderer creates a bundle renderer, executes code via Node’s vm, traverses the virtual DOM to generate HTML strings, and relates SSR rendering to the generate phase of front‑end compilation.
In component‑based front‑end development, browsers render components by manipulating the DOM via the DOM API, while on the server we can render components into an HTML string and deliver it directly, eliminating the need for JavaScript execution and resulting in faster page display.
Client‑side rendering (CSR) runs in the browser, whereas server‑side rendering (SSR) generates HTML on the server. SSR speeds up the first paint because the browser only parses HTML, and it provides better SEO since crawlers can read the content immediately. These benefits are especially important for pages embedded in apps and for low‑end devices where JavaScript execution may be slow.
Vue templates or JSX are compiled into render functions that produce a virtual DOM (vdom). In the browser the vdom is patched to the real DOM; on the server the vdom is traversed and its nodes are concatenated into an HTML string.
Vue’s vue‑server‑renderer package offers the createBundleRenderer API. The “bundle” is the server‑side code produced by webpack. The renderer provides renderToString and renderToStream methods. Internally it uses Node’s vm.runInContext to execute the bundle, creating a Vue instance in a Node context (without DOM), and then renders the instance’s vdom into an HTML string.
const bundle = fs.readFileSync(resolve('./dist/server-bundle.js'), 'utf-8');
createBundleRenderer(bundle);During rendering the bundle is executed (runInVm), which returns a Vue instance. Because there is no DOM API in Node, the render step simply walks the vdom and concatenates strings, producing the final HTML that is sent to the browser.
This process mirrors the generate phase of front‑end compilation. In a typical compiler the source is parsed into an AST, transformed, and then the generate phase recursively walks the AST and prints each node to produce the output code. Tools like Babel implement this by printing nodes such as while or condition into strings, just as SSR prints vdom nodes.
In summary, SSR delivers fast first‑screen rendering and improves search‑engine indexing; its core mechanism is converting a tree‑structured vdom into an HTML string, which is conceptually identical to the code‑generation step of a compiler.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.