Server-Side Rendering
Server-Side Rendering (SSR) allows you to render Vue components on the server and send fully-rendered HTML to the client. This improves initial load time, SEO, and provides a better experience for users on slower connections.Why SSR?
Benefits
- Better SEO - Search engines can crawl fully-rendered content
- Faster Time-to-Content - Users see content immediately without waiting for JavaScript
- Better Performance on Low-End Devices - Less JavaScript to parse and execute
- Social Media Sharing - Proper meta tags and Open Graph data
Trade-offs
- Increased Server Load - Each request requires rendering
- More Complex Setup - Requires Node.js server and build configuration
- Development Constraints - Some browser APIs are not available during SSR
- Higher Hosting Costs - Need a Node.js server instead of static hosting
The Server Renderer Package
Vue’s@vue/server-renderer package (version 3.5.29) provides APIs for rendering Vue components on the server. As of Vue 3.2.13+, this package is included as a dependency of the main vue package and can be accessed as vue/server-renderer.
Basic API
renderToString
Renders a Vue application to an HTML string:SSR Context
The context object allows you to access additional information:Streaming API
For better performance with large applications, use streaming:renderToNodeStream
Note: Only available in CommonJS build. UsepipeToNodeWritable in ESM.
pipeToNodeWritable
Render and pipe to a Node.js Writable stream:renderToWebStream
For modern edge environments (Cloudflare Workers, Deno, etc.):pipeToWebWritable
For environments with WritableStream:renderToSimpleStream
Low-level streaming with custom readable interface:Complete SSR Setup
Server Entry
Create a server entry point:Client Entry
Hydrate the server-rendered HTML:Shared App Creation
Handling Teleports
Teleports require special handling in SSR:Data Prefetching
Fetch data before rendering:State Serialization
Serialize and transfer state to the client:SSR with Router
SSR with Pinia
Development vs Production
Development
Production
Build separate client and server bundles:Error Handling
Best Practices
- Use streaming for large pages to improve TTFB
- Cache rendered pages when possible to reduce server load
- Implement proper error handling with fallback to client-side rendering
- Prefetch critical data during server-side rendering
- Serialize state properly to avoid XSS vulnerabilities
- Test both server and client rendering paths
- Monitor server performance and optimize bottlenecks
- Use HTTP/2 Server Push for critical resources
Common Pitfalls
Browser APIs
Avoid using browser-only APIs during SSR:Component Lifecycle
OnlybeforeCreate and created run during SSR:
Deployment
Node.js Server
Deploy to any Node.js hosting provider:Edge Functions
Deploy to edge platforms like Cloudflare Workers:Resources
- Server Renderer Source Code
- SSR Guide
- Nuxt.js - Full-featured SSR framework
- Vite SSR Plugin