Skip to content

Instantly share code, notes, and snippets.

@drenther drenther/server.index.js
Last active Jul 9, 2019

What would you like to do?
server/index.js for react-ssr
import express from 'express';
import cors from 'cors';
import React from 'react';
import { Helmet } from 'react-helmet';
import { renderToString } from 'react-dom/server';
import { matchPath, StaticRouter } from 'react-router-dom';
import App from '../shared/App';
import routes from '../shared/routes';
import template from './template';
const app = express();
app.get('*', (req, res, next) => {
const activeRoute = routes.find(path => matchPath(req.path, path)) || {};
const apiResponse = activeRoute.getInitialData ? activeRoute.getInitialData(req.path) : Promise.resolve();
.then(data => {
const markup = renderToString(
<StaticRouter location={req.url} context={{ data }}>
<App />
const title = Helmet.renderStatic();
res.send(template(data, markup, title));
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
export default (data, markup, title) => `
<!DOCTYPE html>
<link rel="stylesheet" href="">
<script>window.__SERIALIZED_DATA__ = ${JSON.stringify(data)}</script>
<div id="app">${markup}</div>
<script src="/bundle.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.