Skip to content

Instantly share code, notes, and snippets.

@jaredpalmer
Last active August 26, 2017 20:12
Show Gist options
  • Save jaredpalmer/93a94c316c5acb101e518c869e13d5ac to your computer and use it in GitHub Desktop.
Save jaredpalmer/93a94c316c5acb101e518c869e13d5ac to your computer and use it in GitHub Desktop.
CRA SSR Hacking
// src/server.js
import App from './App';
import React from 'react';
import express from 'express';
import fs from 'fs';
import path from 'path';
import { renderToString } from 'react-dom/server';
const server = express();
const __PROD__ = process.env.NODE_ENV === 'production';
// Get the path to our HTML template
const pathToTemplate = __PROD__ ? 'build/index.html' : 'public/index.html';
// Load the template as a string
const template = fs.readFileSync(pathToTemplate, 'utf8');
server
.disable('x-powered-by')
.use(express.static('build'))
.get('/*', (req, res) => {
const markup = renderToString(<App />);
// Inject our markup into our template. In development,
// we need to also inject a script tag pointing to
// where CRA serves our javascript file.
const html = template
.replace(
'<div id="root"></div>',
`<div id="root">${markup}</div>
${!__PROD__ &&
'<script type="text/javascript" src="http://localhost:3000/static/js/bundle.js"></script>'}`
)
.replace('%PUBLIC_URL%', '');
res.send(html);
});
// Serve our SSR app on a DIFFERENT port than CRA's
server.listen(3001, () => {
console.log('listening on 3001');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment