I'm trying to create a website using react+redux. I've already setup jwt authentication on the server. What I'd like to do is to lazy load some of my components/containers and reducers so that they can be downloaded only by authenticated users. I already know how to hide components from unauthenticated users (client side), but I would prefer to prevent them from downloading the relative javascript code.
I am using webpack, and I've already looked into react-router and require-ensure
(https://stackoverflow.com/a/33044701/2920112), but this approach doesn't seem to handle authentication at all.
I've also considered using fetch
in some way (probably bundling the private code separately with webpack), but I wouldn't know what to do with the bundle once I fetch it.
Am I approaching the problem in the wrong way? The only alternative I see is to provide two HTML files, one loading a webpack bundle with only the public content, and one downloading also the private code. This however seems really suboptimal. What is the correct approach?
No, for every component it no needed. It make sense to use for each layout or page. A good place to start is with routes. Most people on the web are used to page transitions taking some amount of time to load.
We solved this by using react-router:
<Route
key="secured_component"
path="/secured"
onEnter={handleEnterSecuredComponent}
getComponent=({nextState, cb) => {
require.ensure([], () => {
cb(null, require('YourComponent').default);
});
}}
/>
...
const handleEnterSecuredComponent = (nextState, replace) => {
const {login: {success}} = store.getState();
if (!success) {
replace('/login');
}
};
So your login page should set in redux {login: {success: true}} if user is authenticated. If an authenticated user tries to access /secured, he will be redirected to /login.
the require.ensure does not play any role of authentication. It just an entry point for webpack to split the chunk of js files for lazy loading.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With