-
-
Save akrisiun/4dc2e63e18e088a1f788b522820e2783 to your computer and use it in GitHub Desktop.
Basic setup for React SSR - https://medium.com/better-programming/demystifying-reacts-server-side-render-de335d408fe4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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