/** Example usage of React Router 4 to handle: - Known routes to render a specific component, e.g. / - An array of valid top level slugs, e.g. /:pageId - A dictionary of top level slugs that should redirect, e.g. /:redirectId - An array of valid slugs for a known subroute, e.g. /items/:itemId - 404 for anything that is not handled, including invalid slugs, with a correct http response - Server side example, but ReactApp is written so that routing would work universally **/ import { createServer } from 'http' import express from 'express' import React, { PropTypes } from 'react' import { renderToString } from 'react-dom/server' import { StaticRouter, Route, Switch, Redirect } from 'react-router-dom' const app = express(); const pages = ['page-one', 'page-two'] const items = ['item-one', 'item-two'] const redirects = { 'redirect-one': '/item/item-one', 'redirect-two': '/page-one', 'redirect-three': '/invalid-slug', 'redirect-four': '//google.com' } const Item = () => { return

This is a valid item

} class NotFound extends React.Component { componentWillMount() { if(this.context.router.staticContext) { // running on the server, so specify response status // TODO: this might not be the right place to bubble data up to Express this.context.router.staticContext.status = 404 } } render() { return

404

} } NotFound.contextTypes = { router: PropTypes.shape({ staticContext: PropTypes.object }).isRequired } const ReactApp = () => (

Routing POC

Home

{ if(items.includes(itemId)) { return } else { return } }} /> { if(pages.includes(topLevelSlug)) { return

This is a valid page: {topLevelSlug}

} else if(redirects[topLevelSlug]) { return } else { return } }}/>
) app.get('*', function(req, res, next) { const context = {}; console.log(req.url) const html = renderToString( ); if(context.status) { res.status(context.status) } if (context.url) { res.writeHead(302, { Location: context.url }) res.end() } else { res.send(html); } }); createServer(app).listen(8008)