You can use power of dynamically loaded chunks. For example imagine this mockup of routing:
switch(routeName) {
case 'home':
const homePage = require('homePage');
homePage();
break;
case 'contact':
const contactPage = require('contactPage');
contactPage();
break;
case 'dashboard': // <-- this should be protected
const dashboardPage = require('dashboardPage');
dashboardPage();
break;
case 'informationForLoggedUser': // <-- this should be protected
const informationForLoggedUserPage = require('informationForLoggedUserPage');
informationForLoggedUserPage();
break;
};
In above example all your routes will be downloaded in single bundle.js file. To change that you can use power of require.ensure. Wrap your protected routes in require.ensure with 3rd parameter naming this chunk as protected (this name can be different - it's just example).
switch(routeName) {
case 'home':
const homePage = require('homePage');
homePage();
break;
case 'contact':
const contactPage = require('contactPage');
contactPage();
break;
case 'dashboard': // <-- this will be protected
require.ensure([], () => {
const dashboardPage = require('dashboardPage');
dashboardPage();
}, 'protected');
break;
case 'informationForLoggedUser': // <-- this will be protected
require.ensure([], () => {
const informationForLoggedUserPage = require('informationForLoggedUserPage');
informationForLoggedUserPage();
}, 'protected');
break;
};
In your webpack.config.js if you will have this configuration:
entry: path.resolve('src', 'main.js'),
output: {
path: path.resolve('build'),
filename: '[name].js', // <-- this is important
publicPath: '/'
},
The webpack will produce this files:
main.js
1.protected.js
Now you must provide on your own protection on the backed - to not send *.protected.js file for not authenticated users.