What I want to make happen
Let's say you've implemented SSR in express and React and an error is thrown during rendering. Consider returning the following data when it catches an error
- Returns a status code of 500.
- A custom header to determine the type of error.
In addition, because the application is so huge, we want to stream the data we pass to the client in order of what we can send, to improve the performance of the rendering. Therefore, the HTTP response body may be reached before an error occurs in SSR.
Examples include the following
<!DOCTYPE html>
- Contents of a fixed
<head>
tag
Sample code
To reproduce these requirements, we provide two example implementations using renderToStaticNodeStream
and renderToStaticMarkup
.
GitHub: https://github.com/Himenon/react-ssr-error-handle
import * as React from "react";
import express from "express";
import {
renderToStaticNodeStream,
renderToStaticMarkup,
} from "react-dom/server";
const SERVER_PORT = 9000;
const server = express();
const LargeApplication = () => {
const somethingError = () => {
console.log(`Access window object in nodejs: ${window.location.href}`);
};
somethingError();
return (
<html lang="en">
<head>
<title>React SSR Streaming Error Handle</title>
</head>
<body>
<h1>Hello world!</h1>
</body>
</html>
);
};
server.get("/sample1", (req: express.Request, res: express.Response) => {
const stream = renderToStaticNodeStream(<LargeApplication />);
res.type("html");
res.write("<!DOCTYPE html>");
stream.pipe(res, { end: true });
stream.on("error", (error) => {
res.status(500);
res.setHeader(
"Custom-Error-Code",
"REACT:RENDER_TO_STATIC_NODE_STREAM_ERROR"
);
res.write(`<pre><code>${error.stack}</code></pre>`);
res.end();
});
});
server.get("/sample2", (req: express.Request, res: express.Response) => {
try {
res.type("html");
res.write("<!DOCTYPE html>"); // can be immediately responded to
const html = renderToStaticMarkup(<LargeApplication />);
/* <---- I know that describing it here won't cause any problems. */
// res.type("html");
// res.write("<!DOCTYPE html>");
/* ----> */
res.write(html);
} catch (error) {
res.status(500);
res.setHeader(
"Custom-Error-Code",
"REACT:RENDER_TO_STATIC_NODE_STREAM_ERROR"
);
res.send(`<pre><code>${error.stack}</code></pre>`);
}
});
server.listen(SERVER_PORT, () => {
console.log(`Serve start: http://localhost:${SERVER_PORT}`);
});
This server has a URL that looks like this
- renderToStaticNodeStream: http://localhost:9000/sample1
- renderToStaticMarkup: http://localhost:9000/sample2
Execution Result
If you access /sample1
, the following error is shown and the server stops.
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:485:11)react-ssr-error-handle/src/server.tsx:33:9)
at ReactMarkupReadableStream.emit (events.js:210:5)
at ReactMarkupReadableStream.EventEmitter.emit (domain.js:475:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
error Command failed with exit code 1.
The reason is obvious, because the response header comes after the response body because the res.setHeader
to send based on the caught error is after the res.write("<!DOCTYPE html>")
.
/sample2
also throws an error for the same reason and terminates the server.
Possible Solutions
The solution is simple.
- use
renderToStaticMarkup
to return the response to the client after the complete HTML is output. - implement a complete implementation that does not throw errors at SSR (e.g., use of error boundaries).
- always return status code 200 to the client and do not render only the part that failed SSR.
The realistic implementation is *1, and this is how we are currently implementing it. There is a concern (not verified) that 3 will be indexed in Google search for error conditions.
What to do in the case of large and complex applications
The sample code shown here is a relatively small application. Therefore, it is possible to aim for a complete implementation that does not throw any errors at SSR. In practice, however, applications rely on many libraries and have a wide variety of conditional branches, making it difficult to aim for a complete implementation. Also, since front-end applications require fast rendering, developers want to implement implementations that return results faster to the user. For example, shortening the TTFB.
Do you have any other possible solutions?