Why Use SSR?
Better Performance
Users see content faster since HTML is sent immediately instead of waiting for JavaScript to load and execute.
Improved SEO
Search engines can index your content immediately without executing JavaScript.
Social Media
Social media crawlers can read your content for previews and cards.
Accessibility
Content is available even if JavaScript fails to load or is disabled.
Installation
SSR requires thepreact-render-to-string package:
Basic Usage
- renderToString
- renderToStaticMarkup
The most common SSR function. Renders a component tree to an HTML string:This is a synchronous function that returns a complete HTML string.
Integration with Servers
Hydration
After sending server-rendered HTML, you need to “hydrate” it on the client. Hydration attaches event listeners and makes the app interactive.Streaming SSR
For large applications, streaming can improve Time To First Byte (TTFB):- renderToReadableStream (Web)
- renderToPipeableStream (Node)
Returns a ReadableStream for use in modern web environments:
Compat Layer
When usingpreact/compat, SSR functions are re-exported for React compatibility:
compat/server.d.ts
You can import from preact/compat/server just like react-dom/server:
Data Fetching
For SSR with data fetching, you’ll need to fetch data on the server before rendering:Best Practices
Common Patterns
Next Steps
TypeScript
Add type safety to your Preact application
Hooks
Master hooks for SSR-compatible components