Skip to content

Instantly share code, notes, and snippets.

@alexnm
Created March 24, 2018 07:49
Show Gist options
  • Save alexnm/65e1c0bc1c277235653012db463bc82a to your computer and use it in GitHub Desktop.
Save alexnm/65e1c0bc1c277235653012db463bc82a to your computer and use it in GitHub Desktop.
Basic setup for React SSR
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