Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy load components requiring authentication with react-redux

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?

like image 697
lgpasquale Avatar asked Feb 07 '17 18:02

lgpasquale


People also ask

Should I lazy load all components?

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.


Video Answer


1 Answers

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.

like image 171
idealweek.net Avatar answered Oct 02 '22 15:10

idealweek.net