Skip to content

Instantly share code, notes, and snippets.

@jtlindsey
Created March 22, 2017 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtlindsey/798a0de525d72acab02c2ad5ae3a8ea2 to your computer and use it in GitHub Desktop.
Save jtlindsey/798a0de525d72acab02c2ad5ae3a8ea2 to your computer and use it in GitHub Desktop.
Thinking about reactjs serverside
router.get('*', function(request, response) {
let initialState = { title: 'Universal React' };
let store = Redux.createStore(reducer, initialState);
ReactRouter.match({
routes: require('./routes'),
location: request.url
}, function(error, redirectLocation, renderProps) {
if (!USER_LOGGED_IN) {
let html = ReactDOMServer.renderToString(
<LoginView />
);
response.send(html);
} else if (renderProps && USER_LOGGED_IN) {
let html = ReactDOMServer.renderToString(
<Provider store={store}>
<ReactRouter.RouterContext {...renderProps} />
</Provider>
);
response.send(html);
} else {
response.status(404).send('Not Found');
}
});
});
@remarkablemark
Copy link

To add to what you already have, you could update the Redux store with { isAuthenticated: true } as the initial state so then ReactRouter can decide for itself which route to render.

Then you won't need to call ReactDOMServer.renderToString() twice because the logic is all in one place.

Plus, you could create a <Redirect> or <EnsureLoggedIn> component that redirects an unauthenticated user to /login if trying to access a protected route.

@jtlindsey
Copy link
Author

That makes since. Thanks for the feedback Mark!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment