javascriptreactjswebpackauthorizationrbac

Different React Webpack JS Bundles for User Roles


I'm working on an application at the moment which has RBAC and as a result different users will be presented with more elements depending on their role.

I'm securing the App with a JWT that must be retrieved on login and subsequently passed on every API call and stored in the localStorage.

What my issue is, if somebody alters state and sets my state vars as logged in and a certain user, they will be able to see what an admin can do, they might not be able to utilise the backend commands but they can get a view of what is possible and the endpoints associated with that.

I'm wondering if it's possible to use Webpack to seperate bundles so that we can first validate the user is of the right type then present them an SPA with only the possible options for their user? Kind of like server side rendering the page with all the other roles removed and all the functionality remaining for their role.


Solution

  • In order to create several sets of bundles based on the same source code, you can export array of configs from you webpack.config.js (docs).

    In each config you are free to define some necessary flags using DefinePlugin:

    module.exports = [
      {
        //...
        // admin config
        //...
        plugins: [
          new webpack.DefinePlugin({
            ROLE: 'admin'
          })
        ]
      },
      {
        //...
        // user config
        //...
        plugins: [
          new webpack.DefinePlugin({
            ROLE: 'user'
          })
        ]
      }
    ]
    

    Then in your source code you can use process.env.ROLE to enable/disable some features:

    if (process.env.ROLE === 'admin') { /* show red alert button */}
    

    In the end dead code elimination will remove those sections for you. As a result you will have multiple bundles with different features included.