Skip to content

Instantly share code, notes, and snippets.

@danielnmai
Last active September 8, 2018 16:44
Show Gist options
  • Save danielnmai/7e7da5a70d60f71d90c6be2fff3ecc72 to your computer and use it in GitHub Desktop.
Save danielnmai/7e7da5a70d60f71d90c6be2fff3ecc72 to your computer and use it in GitHub Desktop.
Express server for React SSR
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