Skip to content

Instantly share code, notes, and snippets.

@KidkArolis
Last active August 29, 2015 14:27
Show Gist options
  • Save KidkArolis/5da927387953db7a2cb5 to your computer and use it in GitHub Desktop.
Save KidkArolis/5da927387953db7a2cb5 to your computer and use it in GitHub Desktop.
render a react app in express using cherrytree
/**
* A generic render helper for cherrytree + react + express.
*
* To run this example locally:
*
* $ git clone https://github.com/QubitProducts/cherrytree.git
* $ cd cherrytree/examples/server-side-react
* $ npm install
* $ npm start
* $ open http://localhost:8000
*
*/
let cherrytree = require('cherrytree')
let { Router } = require('cherrytree-for-react')
let React = require('react')
/**
* This higher order function will create a render
* function that can be used as express middleware.
*
* It takes the route map function and the router options
* as arguments.
*/
module.exports = function (routes, options) {
return function render (req, res, next) {
// this is the URL that the browser has requested
let url = req.url
// create a cherrytree instance just for this pageview
// and configure it with the routes
let router = cherrytree(options).map(routes())
// on the server, we don't want to use the default
// cherrytree location - instead we use a MemoryLocation
// which we initialize with the requested url
let location = new cherrytree.MemoryLocation(url)
// kick off the routing using the custom location
let transition = router.listen(location)
// transition is a promise (or a subclass of a promise)
// after the transition completes, we render or redirect
transition
.then(function () {
let html = React.renderToString(<Router router={router} />)
res.send(html)
}).catch(function (err) {
if (err.type === 'TransitionRedirected' && err.nextPath) {
res.redirect(err.nextPath)
} else {
next(err)
}
})
// after everything - clean up
transition.then(cleanup).catch(cleanup)
function cleanup () {
router.destroy()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment