Press enter or click to view image in full size
Authentication and authorization are both common problems when writing an application. Authentication answers the question, “who are you?”, while authorization answers the question, “are you allowed to see that?”
Somebody recently asked how to accomplish role-based authorization using React and React Router, and linked to a post describing one way to go about it. Essentially, the post suggests simply passing a list of roles that are allowed to see a given route, and checking whether the currently logged in user is one of those roles within your route handler.
That would work, but I see a few problems with it.
- Single responsibility principle violations.
- Unnecessarily passing data through React Router.
- No reusable code.
So how can we apply authorization in a way that gives each component a single job to do, is self contained, and is reusable?
One way we could improve upon the above blog’s code, would be to encapsulate the authorization logic in its own component—with a function child to prevent components from mounting if the user isn’t authorized—and render that from your route handler.