How to create guarded routes for your React-App
Whenever you develop a React-Application there will be the need to restrict unauthenticated users to access certain parts of your application.
React Router is my library of choice when it comes to routing for React, but there is no built-in way to protect a <Route> from unrestricted access. In this post I will show you how to easily build your own guarded routes.
Setting up an example application
First run npx create-react-app route-guard
on your command line to bootstrap a new React-Application.
Second run npm start
inside the newly created route-guards
folder to check if everything is working properly.
As a result you should see the create-react-app default page in your browser:
Setting up some <Routes> to guard
Now we install React Router by running npm install react-router-dom
, in order to set up some basic routes which we guard later.
Additionally set up three new React components to which we can route:
Import the BrowserRouter into your App.js
component and set up a <Router> with two routes.
Your App.js
should look like this:
In a next step we display three links inside the App.js
component to easily navigate from one page to another.
Import Link from react-router-dom and add the following lines to the top of the <Router> of your app component:
Hereby the basic setup is completed, now we can look into authentication and how to guard a <Route>.
Adding fake authentication
Before we can add route guarding we need to add a fake authentication.
Underneath the Navigation we add a Login and a Logout button with an onClick
handler that points to the corresponding functions that we define right at the top of the component.
We use the useState
hook to save the current user login state inside the state of the component.
The App.js
component should now look like this:
Guard Route to the protected component
Now we want to guard the protected page from unrestricted user access.
We need to write a GuardedRoute
which wraps a normal React-Router <Route>:
Now we can use the new component inside theApp.js
component.
<GuardedRoute path='/protected' component={Protected} auth {isAutheticated} />
Let me explain the code above:
First of all we create a new component wrapping a React-Router <Route>. Then we rename the component
prop to Component
because in JSX lowercase tag names are considered html tags so component names should always start uppercase. Inside the render of the <Router> component we check if the user is authenticated. If true, display the protected component. If false we redirect to Home.js
.
Now we are finished with the implementation. Restart your application and test the different <Routes>. It should not be possible to reach the protected component if your are not logged in. If you try to reach the protected page the application redirects to the home page.
You can find the final code in my GitHub repo:
Credits
The article was influenced by the following works on a similar topic: