Created
March 24, 2018 07:49
-
-
Save alexnm/65e1c0bc1c277235653012db463bc82a to your computer and use it in GitHub Desktop.
Basic setup for React SSR
This file contains hidden or 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
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