Mastodon hachyterm.io

Yesterday I was wondering how I could protect routes in React.js.

I have a back-end application written in Node.js which uses middleware (Passport-Next and a requireLogin helper) to protect the server routes. But what about client-side routing?
The app uses React Router v4 for routing and React-Redux for state management.
The Redux store contains an auth key that tells me if the user is signed in.

So, how can I use the Redux state to determine if a user can visit a (client-side) route?

And because Stack Overflow is the friend of all newbie devs, I quickly found a great answer:

Simple Conditional Routing in Reactjs

This will explain how to create a ProtectedRoute component which can act as a kind of “middleware” for your front-end routing needs. I used Redux’s Connect and mapStateToProps to access the authentication status from my Redux store.

Which really shows that you don’t have to re-invent the wheel but just know how to do research. And then go from there.

Further Reading