Last active
September 8, 2018 16:44
-
-
Save danielnmai/7e7da5a70d60f71d90c6be2fff3ecc72 to your computer and use it in GitHub Desktop.
Express server for React SSR
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
import express from "express" | |
import { renderToString } from "react-dom/server" | |
import React from 'react' | |
import App from '../App.js' | |
import ContextProvider from '../ContextProvider.js' | |
const app = express() | |
//Serve the app with the public bundle.js | |
app.use(express.static("online/dist/")) | |
app.get("/", (req, res, next) => { | |
const css = new Set() | |
const context = { insertCss: (...styles) => | |
styles.forEach(style => css.add(style._getCss()))} | |
const markup = renderToString( | |
<ContextProvider context={context}> | |
<App /> | |
</ContextProvider> | |
) | |
res.send( | |
` | |
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<title>My Website</title> | |
<style type="text/css">${[...css].join('')}</style> | |
</head> | |
<body> | |
<!-- Root Element --> | |
<div id="app">${markup}</div> | |
<script src="bundle.js"></script> | |
</body> | |
</html> | |
` | |
) | |
}) | |
app.listen(3000, () => { | |
console.log(`Server is listening on port: 3000\n`) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment