Skip to main content

renderToString

renderToString is a legacy API. For new projects, use renderToPipeableStream (Node.js) or renderToReadableStream (Web Streams) instead.
Renders a React tree to an HTML string synchronously on the server.

Reference

renderToString(reactNode, options?)

Call renderToString to render your app to HTML on the server.
/src/server/ReactDOMLegacyServerNode.js:18-28

Parameters

ReactNode
required
A React node you want to render to HTML. For example, a JSX element like <App />.
ServerOptions
Optional server rendering options.

Returns

string
An HTML string with React-specific attributes like data-reactroot. This HTML can be sent to the client and hydrated with hydrateRoot.

Usage Examples

Basic Server Rendering

With Client-Side Hydration

Server:
Client:

With Express and Template

With Next.js (Legacy)

Limitations

Does Not Support Suspense

renderToString does not support Suspense. Components that suspend will cause an error.
Solution: Use renderToPipeableStream instead:

Synchronous and Blocking

renderToString is synchronous and blocks the Node.js event loop until rendering completes. This can cause performance issues for large apps.
Solution: Use streaming APIs:

No Streaming

Client must wait for entire HTML string before anything renders:

Migration Guide

From renderToString to renderToPipeableStream

Before:
After:

Benefits of Migration

  1. Suspense Support - Async components work properly
  2. Streaming - HTML sent to client as it’s generated
  3. Better Performance - Non-blocking, scales better
  4. Selective Hydration - Interactive sooner on client
  5. Error Handling - Better error recovery

When to Use renderToString

Despite being legacy, renderToString is still useful for:
  1. Static Site Generation - Pre-rendering at build time
  2. Email Templates - Generating HTML emails
  3. Testing - Simple HTML output for snapshots
  4. Simple Apps - No Suspense, small scale

Static Site Generation Example

TypeScript

Error Handling

Performance Considerations

Measure Rendering Time

Optimize Large Apps

Common Pitfalls

Don’t use browser APIs

Don’t forget to escape user content