Created
March 22, 2017 14:58
-
-
Save jtlindsey/798a0de525d72acab02c2ad5ae3a8ea2 to your computer and use it in GitHub Desktop.
Thinking about reactjs serverside
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
} | |
}); | |
}); |
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
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.