I would like to SSR the homepage from a node express server to a react nextJS client without using dangerouslySetInnerHTML.
The server and client are in separate directories.
I have verified the server successfully serves this JSX to the browser b/c I can go to localhost:5000 where the server is running and see the rendered HTML.
// server.js file in node express repo
// Serve SSR React component
app.get("/", (req, res) => {
const appHtml = ReactDOMServer.renderToString(<SSRApp />);
res.send(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SSR App</title>
</head>
<body>
<div id="root">${appHtml}</div>
</body>
</html>
`);
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
However, when running the nextJS client on port 3000, I’m only able to render the JSX from the server if I use dangerouslySetInnerHTML:
// page.js file in next client repo
import React from "react";
export default async function HomePage() {
// Fetch the SSR HTML from your Express server
const res = await fetch("http://localhost:5000", {
cache: "no-store",
});
const ssrHtml = await res.text();
return (
<div>
<div dangerouslySetInnerHTML={{ __html: ssrHtml }} />
</div>
);
}
I’m aware you can sanitize the input to reduce risk of XSS attacks but I’d prefer to avoid dangerouselySetInnerHTML all together.
How can I SSR from a node express server to a nextJS react client and allow the client to hydrate the JSX from the server in a nextJS app without using dangerouslySetInnerHTML?