Skip to content

Adds isomorphic/server-side React application-shell rendering #35

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
May 18, 2016
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions app.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
runtime: nodejs
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this come with any predefined environment variables?

If not, setting NODE_ENV to production will make Express cache the view template

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

vm: true

skip_files:
- ^(.*/)?.*/node_modules/.*$
25 changes: 16 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,26 +9,33 @@
"url": "http://github.com/insin/react-hn.git"
},
"scripts": {
"build": "npm run lint && cp node_modules/sw-toolbox/sw-toolbox.js public/sw-toolbox.js && nwb build && npm run precache",
"lint": "eslint src",
"lint:fix": "eslint --fix .",
"start": "nwb serve",
"precache": "sw-precache --root=public --config=sw-precache-config.json"
"build": "npm run lint && cp node_modules/sw-toolbox/sw-toolbox.js public/sw-toolbox.js && ./node_modules/nwb/lib/bin/nwb.js build && npm run precache",

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can replace ./node_modules/nwb/lib/bin/nwb.js with ./node_modules/.bin/nwb

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. Will update.

"deploy": "gcloud preview app deploy",
"lint": "./node_modules/eslint-config-jonnybuchanan/bin/lint.js src",
"lint:fix": "./node_modules/eslint-config-jonnybuchanan/bin/lint.js --fix .",
"start": "node server.js",
"postinstall": "npm run build",
"serve": "./node_modules/lib/bin/nwb.js serve",
"precache": "./node_modules/sw-precache/cli.js --root=public --config=sw-precache-config.json"
},
"engines": {
"node": "6.1.0"
},
"main": "server.js",
"dependencies": {
"ejs": "^2.4.1",
"events": "1.1.0",
"express": "^4.13.4",
"firebase": "2.4.2",
"firetruck.js": "0.1.1",
"history": "2.1.1",
"react": "15.0.2",
"react-dom": "15.0.2",
"react-router": "2.4.0",
"react-timeago": "3.0.0",
"reactfire": "0.7.0",
"scroll-behavior": "0.5.0",
"setimmediate": "1.0.4"
},
"devDependencies": {
"setimmediate": "1.0.4",
"url-parse": "^1.1.1",
"eslint-config-jonnybuchanan": "2.0.3",
"nwb": "0.8.1",
"sw-precache": "^3.1.1",
Expand Down
File renamed without changes.
44 changes: 44 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
var express = require('express')
var React = require('react')
var renderToString = require('react-dom/server').renderToString
var ReactRouter = require('react-router')

require('babel/register')
var routes = require('./src/routes')

var app = express()
app.set('view engine', 'ejs')
app.set('views', process.cwd() + '/src/views')
app.set('port', (process.env.PORT || 5000))
app.use(express.static('public'))

app.get('*', function(req, res) {
ReactRouter.match({
routes: routes,
location: req.url
}, function(err, redirectLocation, props) {
if (err) {
res.status(500).send(err.message)
}
else if (redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search)
}
else if (props) {
var markup = renderToString(
React.createElement(ReactRouter.RouterContext, props, null)
)
res.render('index', { markup: markup })
}
else {
res.sendStatus(404)
}
})
})

app.listen(app.get('port'), function(err) {
if (err) {
console.log(err)
return
}
console.log('Running app at localhost:' + app.get('port'))
})
4 changes: 2 additions & 2 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* global __VERSION__ */
var React = require('react')
var Link = require('react-router/lib/Link')

Expand All @@ -19,10 +18,12 @@ var App = React.createClass({
SettingsStore.load()
StoryStore.loadSession()
UpdatesStore.loadSession()
if (typeof window === 'undefined') return
window.addEventListener('beforeunload', this.handleBeforeUnload)
},

componentWillUnmount() {
if (typeof window === 'undefined') return
window.removeEventListener('beforeunload', this.handleBeforeUnload)
},

Expand Down Expand Up @@ -60,7 +61,6 @@ var App = React.createClass({
{this.props.children}
</div>
<div className="App__footer">
{`react-hn v${__VERSION__} | `}
<a href="https://github.com/insin/react-hn">insin/react-hn</a>
</div>
</div>
Expand Down
2 changes: 1 addition & 1 deletion src/Stories.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ var Stories = React.createClass({
}
},

componentWillMount() {
componentDidMount() {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

more out of interest, but why is this required? Is this what gets around that weird React error I was getting?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

componentDidMount() only gets called on the client

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, of course.

setTitle(this.props.title)
this.store = new StoryStore(this.props.type)
this.store.addListener('update', this.handleUpdate)
Expand Down
18 changes: 8 additions & 10 deletions src/mixins/ItemMixin.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,16 @@ var TimeAgo = require('react-timeago').default

var SettingsStore = require('../stores/SettingsStore')
var pluralise = require('../utils/pluralise')
var urlParse = require('url-parse')

var parseHost = (function() {
var a = document.createElement('a')
return function(url) {
a.href = url
var parts = a.hostname.split('.').slice(-3)
if (parts[0] === 'www') {
parts.shift()
}
return parts.join('.')
var parseHost = function(url) {
var hostname = (urlParse(url, true)).hostname
var parts = hostname.split('.').slice(-3)
if (parts[0] === 'www') {
parts.shift()
}
})()
return parts.join('.')
}

/**
* Reusable logic for displaying an item.
Expand Down
4 changes: 4 additions & 0 deletions src/stores/StoryStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ class StoryStore extends EventEmitter {
start() {
firebaseRef = HNService.storiesRef(this.type)
firebaseRef.on('value', this.onStoriesUpdated)
if (typeof window === 'undefined') return
window.addEventListener('storage', this.onStorage)
}

Expand All @@ -107,6 +108,7 @@ class StoryStore extends EventEmitter {
firebaseRef.off()
firebaseRef = null
}
if (typeof window === 'undefined') return
window.removeEventListener('storage', this.onStorage)
}
}
Expand All @@ -124,6 +126,7 @@ extend(StoryStore, {
* Deserialise caches from sessionStorage.
*/
loadSession() {
if (typeof window === 'undefined') return
idCache = parseJSON(window.sessionStorage.idCache, {})
itemCache = parseJSON(window.sessionStorage.itemCache, {})
},
Expand All @@ -132,6 +135,7 @@ extend(StoryStore, {
* Serialise caches to sessionStorage as JSON.
*/
saveSession() {
if (typeof window === 'undefined') return
window.sessionStorage.idCache = JSON.stringify(idCache)
window.sessionStorage.itemCache = JSON.stringify(itemCache)
}
Expand Down
2 changes: 2 additions & 0 deletions src/stores/UpdatesStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,12 +100,14 @@ function handleUpdateItems(items) {

var UpdatesStore = extend(new EventEmitter(), {
loadSession() {
if (typeof window === 'undefined') return
var json = window.sessionStorage.updates
updatesCache = (json ? JSON.parse(json) : {comments: {}, stories: {}})
populateUpdates()
},

saveSession() {
if (typeof window === 'undefined') return
window.sessionStorage.updates = JSON.stringify(updatesCache)
},

Expand Down
1 change: 1 addition & 0 deletions src/utils/setTitle.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
var {SITE_TITLE} = require('./constants')

function setTitle(title) {
if (typeof document === 'undefined') return
document.title = (title ? title + ' | ' + SITE_TITLE : SITE_TITLE)
}

Expand Down
11 changes: 8 additions & 3 deletions src/utils/storage.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
module.exports = {
get(key, defaultValue) {
var value = window.localStorage[key]
return (typeof value != 'undefined' ? value : defaultValue)
if (typeof window !== 'undefined') {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if (typeof window === 'undefined') return defaultValue;

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updating to reflect feedback in just a sec.

var value = window.localStorage[key]
return (typeof value != 'undefined' ? value : defaultValue)
}
},
set(key, value) {
window.localStorage[key] = value
if (typeof window !== 'undefined') {
window.localStorage[key] = value
}
}
}

70 changes: 70 additions & 0 deletions src/views/index.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<title>React HN</title>

<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="manifest" href="manifest.json">
<meta name="theme-color" content="#222222">

<link rel="shortcut icon" href="img/favicon.ico">
<link rel="apple-touch-icon" sizes="57x57" href="img/apple-touch-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="img/apple-touch-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="img/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="img/apple-touch-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="img/apple-touch-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="img/apple-touch-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="img/apple-touch-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="img/apple-touch-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="img/apple-touch-icon-180x180.png">
<link rel="icon" type="image/png" href="img/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="img/android-chrome-192x192.png" sizes="192x192">
<link rel="icon" type="image/png" href="img/favicon-96x96.png" sizes="96x96">
<link rel="icon" type="image/png" href="img/favicon-16x16.png" sizes="16x16">
<link rel="mask-icon" href="img/safari-pinned-tab.svg" color="#222222">

<meta name="msapplication-TileColor" content="#222222">
<meta name="msapplication-TileImage" content="img/mstile-144x144.png">
<meta name="msapplication-config" content="img/browserconfig.xml">

<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="app"><%- markup %></div>
<script src="build/vendor.js"></script>
<script src="build/app.js"></script>
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./service-worker.js', {
scope: './'
})
.then(function(registration) {
registration.onupdatefound = function() {
if (navigator.serviceWorker.controller) {
var installingWorker = registration.installing;

installingWorker.onstatechange = function() {
switch (installingWorker.state) {
case 'installed':
break;
case 'redundant':
throw new Error('The installing ' +
'service worker became redundant.');
default:
// Ignore
}
};
}
};
}).catch(function(e) {
console.error('Error during service worker registration:', e);
});
} else {
console.log('service worker is not supported');
}
</script>
</body>
</html>