Error Handling with onError
What You'll Learn
You'll learn how to catch and handle errors during streaming SSR using the onError callback to prevent server crashes and log issues gracefully.
The Problem with Streaming Errors
When you're streaming HTML to the client with renderToPipeableStream, errors can occur at different stages: while rendering the initial shell, while resolving suspended components, or during streaming. Without proper error handling, these errors could crash your Node.js server or leave clients with broken HTML.
The onError Callback
The onError callback is your safety net during SSR. It's called whenever React encounters an error during the render process:
const { pipe } = renderToPipeableStream(<App />, {
onShellReady() {
res.statusCode = 200;
pipe(res);
},
onError(error) {
console.error('SSR Error:', error);
// Log to monitoring service
// Send error details to error tracking
// Prevent server crash
}
});
When onError Fires
The onError callback is invoked for:
- Errors thrown during shell rendering (before
onShellReady) - Errors in Suspense boundaries while streaming
- Component errors that occur after streaming starts
Important: If an error occurs before the shell is ready, you should set an appropriate HTTP status code in onError before the response is sent.
Real-World Pattern
onError(error) {
console.error('Render error:', error);
if (!res.headersSent) {
res.statusCode = 500;
}
}
Key Takeaway: The onError callback lets you gracefully handle SSR errors, log them for debugging, and prevent server crashes while maintaining a smooth client experience.