Skip to content

Instantly share code, notes, and snippets.

@akrisiun
Forked from alexnm/server.js
Last active July 4, 2019 12:03
Show Gist options
  • Save akrisiun/4dc2e63e18e088a1f788b522820e2783 to your computer and use it in GitHub Desktop.
Save akrisiun/4dc2e63e18e088a1f788b522820e2783 to your computer and use it in GitHub Desktop.
// server.js
// https://medium.com/better-programming/demystifying-reacts-server-side-render-de335d408fe4
import express from "express";
import path from "path";
import React from "react";
import { renderToString } from "react-dom/server";
import Layout from "./components/Layout";
const app = express();
app.use( express.static( path.resolve( __dirname, "../dist" ) ) );
app.get( "/*", (req, res) => {
const jsx = (<Layout />);
const reactDom = renderToString(jsx);
res.writeHead( 200, { "Content-Type": "text/html" } );
res.end(htmlTemplate(reactDom));
} );
app.listen(2048);
function htmlTemplate(reactDom) {
return `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>React SSR</title>
</head>
<body>
<div id="app">${ reactDom }</div>
<script src="./app.bundle.js"></script>
</body>
</html>
`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment