Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

react-easy-universal

keystonejs11MIT2.0.0

Universal Routing & Rendering with React & Redux was too hard. Now it's easy.

react, redux, routing, rendering, universal, javascript

readme

React Easy Universal

Universal Routing & Rendering with React & Redux was too hard. Now it's easy.

Status

Proof of concept. Needs testing. Kick the tires.

What's included?

Getting Started

You'll need to create two files:

client.js:

import React from 'react';

// Note: There are two versions of the client: bundled and source.
// If you want to build from source, try `react-easy-universal/client-src`.
import universal from 'react-easy-universal/client-bundled';

// returns a function that must be invoked to trigger render
const app = wireApp({ React }); // use all the defaults

// The app function will return your store so you can dispatch actions.
const store = app();

// Do stuff in your client app to trigger re-renders.
// e.g., subscribe to server updates, etc...
store.dispatch({
  type: 'SET_TITLE',
  title: 'Client render'
});

server.js:

import express from 'express';
import React from 'react';
import universal from 'react-easy-universal/server';

// Passing in the express app lets it know you want the server
// version, and it wires up the routes automatically
const app = wireApp({ React, app: express() });

app.use('/static', express.static(staticDir));

const port = process.env.APP_PORT || 3000;

app.listen(port, (err) => {
  if (err) {
    console.log(err);
    return;
  }

  console.log(`Listening at http://localhost:${ port }`);
});

Note: There is nothing exported from react-easy-universal by default. You must use one of the client or the server. They are two different builds in order to save on client download time.

Defining Your Routes

Use this module instead of depending directly on React Router, and we'll worry about keeping all the version dependencies compatible and in-sync for you.

import { Router, Route } from 'react-easy-universal/route-helpers';

import createHome from 'shared/components/home';
import createTestData from 'shared/components/test-data';

// It expects a factory function that it can inject dependencies into.
export default (React) => {

  return (
    <Router>
      <Route path="/" component={ createHome(React) } />
      <Route path="/test-data" component={ createTestData(React) } />
    </Router>
  );
};

Why is this needed? (AKA, the old n busted way)

Universal routing & rendering with React and Redux is pretty great. For serious app projects, it can save you a ton of time, but if you have ever tried configuring it yourself, you'll know, it's a lot harder than it should be. Just to give you an idea of how complicated it can be, here's the example from redux-simple-router, which is AFAIK, the easiest way to configure this stuff right now:

import React from 'react'
import ReactDOM from 'react-dom'
import { createStore, combineReducers, applyMiddleware } from 'redux'
import { Provider } from 'react-redux'
import { Router, Route, browserHistory } from 'react-router'
import { syncHistory, routeReducer } from 'redux-simple-router'
import reducers from '<project-path>/reducers'

const reducer = combineReducers(Object.assign({}, reducers, {
  routing: routeReducer
}))

// Sync dispatched route actions to the history
const reduxRouterMiddleware = syncHistory(browserHistory)
const createStoreWithMiddleware = applyMiddleware(reduxRouterMiddleware)(createStore)

const store = createStoreWithMiddleware(reducer)

// Required for replaying actions from devtools to work
reduxRouterMiddleware.listenForReplays(store)

ReactDOM.render(
  <Provider store={store}>
    <Router history={browserHistory}>
      <Route path="/" component={App}>
        <Route path="foo" component={Foo}/>
        <Route path="bar" component={Bar}/>
      </Route>
    </Router>
  </Provider>,
  document.getElementById('mount')
)

That's six dependencies that you have to manage in your own app, and good luck getting all the right versions that will play together nicely. And this is just the client side. The code above doesn't work on the server. To get that going, you'll have to create an Express route handler that manually calls match() from react-router, checks for errors & redirects, and maybe renders the document. It looks something like this:

import React from 'react';
import { match } from 'react-router';

import renderLayout from 'server/render-layout';
import render from 'server/render';
import settings from 'server/settings';

import configureStore from 'shared/configure-store';
import createRoutes from 'shared/routes';

const store = configureStore();
const routes = createRoutes(React);
const initialState = store.getState();

export default (req, res) => {
  match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
    if (error) {
      res.status(500).send(error.message);
    } else if (redirectLocation) {
      res.redirect(302, redirectLocation.pathname + redirectLocation.search);
    } else if (renderProps) {
      const rootMarkup = render(React)(renderProps, store);
      res.status(200).send(renderLayout({ settings, rootMarkup, initialState }));
    } else {
      res.status(404).send('Not found');
    }
  });
};

There are a few other files you need to wire up that I won't list, for brevity's sake.

It took me two days to get these examples working in one of my own projects. 2 days of fiddling with dependencies, copying the exact versions out of the example repositories and into my package.json. These projects are evolving quickly, and the documentation examples can't be relied on to work.

So, you could keep track of all these dependency versions yourself (and they're all being rapidly updated) -- or, you could use this library, plug in your routes & reducers, and get on with building an actual application instead of chasing all the moving parts around.

Advanced Configuration (note: unfinished)

Need to customize layouts, the root React Node, the root route, and so on? No problem. Just make your wire-app.js factory configurable:

import universal from 'react-easy-universal';

import routes from './path/to/your/routes';
import reducers from './path/to/your/reducers';

const wireApp = ({
  React, app,
  rootID, // default: 'root'
  rootRoute, // default: '/'
  renderLayout // Skeleton DOM render template for the server-side. Default: Barebones ES6 template
}) => universal({
  React, app,
  routes, reducers,
  rootId, rootRoute, renderLayout
});

export default wireApp;

Contributing

There are some handy scripts for contributors, if you'd like to pitch in:

Dev console

There's a dev console available that will show you any lint errors or test failures on file saves:

npm run watch

Debugging

To run the debugger, first, make sure it's installed:

npm install -g iron-node

Then:

npm run debug:test

changelog

v2.0.0

Feb 4, 2016

  • Bugfix: Fix search base logic with an empty query (#221)
  • Bugfix: Fail gracefully when Safari 5 security settings prevent access to window.sessionStorage (#223)

v2.0.0-rc3

Feb 3, 2016

  • Bugfix: Don't convert same-path PUSH to REPLACE when location.state changes (#179)
  • Bugfix: Re-enable browser history on Chrome iOS (#208)
  • Bugfix: Properly support location descriptors in history.createLocation (#200)

v2.0.0-rc2

Jan 9, 2016

  • Add back deprecation warnings

v2.0.0-rc1

Jan 2, 2016

  • Bugfix: Don't create empty entries in session storage (#177)

v1.17.0

Dec 19, 2015

  • Bugfix: Don't throw in memory history when out of history entries (#170)
  • Bugfix: Fix the deprecation warnings on createPath and createHref (#189)

v1.16.0

Dec 10, 2015

  • Bugfix: Silence all warnings that were introduced since 1.13 (see rackt/react-router#2682)
  • Deprecation: Deprecate the createLocation method in the top-level exports
  • Deprecation: Deprecate the state arg to history.createLocation

v1.15.0

Dec 7, 2015

  • Feature: Accept location descriptors in createPath and createHref (#173)
  • Deprecation: Deprecate the query arg to createPath and createHref in favor of using location descriptor objects (#173)

v1.14.0

Dec 6, 2015

  • Feature: Accept objects in history.push and history.replace (#141)
  • Deprecation: Deprecate history.pushState and history.replaceState in favor of passing objects to history.push and history.replace (#168)
  • Bugfix: Disable browser history on Chrome iOS (#146)
  • Bugfix: Do not convert same-path PUSH to REPLACE if the hash has changed (#167)
  • Add ES2015 module build (#152)
  • Use query-string module instead of qs to save on bytes (#121)

v1.13.1

Nov 13, 2015

  • Fail gracefully when Safari security settings prevent access to window.sessionStorage
  • Pushing the currently active path will result in a replace to not create additional browser history entries (#43)
  • Strip the protocol and domain from <base href> (#139)

v1.13.0

Oct 28, 2015

  • useBasename transparently handles trailing slashes (#108)
  • useBasename automatically uses the value of <base href> when no basename option is provided (#94)

v1.12.6

Oct 25, 2015

  • Add forceRefresh option to createBrowserHistory that forces full page refreshes even when the browser supports pushState (#95)

v1.12.5

Oct 11, 2015

  • Un-deprecate top-level createLocation method
  • Add ability to use { pathname, search, hash } object anywhere a path can be used
  • Fix useQueries handling of hashes (#93)

v1.12.4

Oct 9, 2015

  • Fix npm postinstall hook on Windows (#62)

v1.12.3

Oct 7, 2015

  • Fix listenBefore hooks not being called unless a listen hook was also registered (#71)
  • Add a warning when we cannot save state in Safari private mode (#42)

v1.12.2

Oct 6, 2015

v1.12.1

Oct 5, 2015

  • Give location objects a key by default
  • Deprecate history.setState

v1.12.0

Oct 4, 2015

  • Add history.createLocation instance method. This allows history enhancers such as useQueries to modify location objects when creating them directly
  • Deprecate createLocation method on top-level exports

v1.11.1

Sep 26, 2015

  • Fix location.basename when location matches exactly (#68)
  • Allow transitions to be interrupted by another

v1.11.0

Sep 24, 2015

  • Add useBasename history enhancer
  • Add history.listenBefore
  • Add history.listenBeforeUnload to useBeforeUnload history enhancer
  • Deprecate (un)registerTransitionHook
  • Deprecate (un)registerBeforeUnloadHook
  • Fix installing directly from git repo