Protected Routes in React JS 🎯

beginner
6 min

Protected Routes in React JS 🎯

Welcome to our in-depth guide on Protected Routes in React JS! This tutorial is designed for beginners and intermediate learners, explaining the concept from the ground up.

Understanding Protected Routes 📝

Protected Routes is a pattern in React JS that helps secure your application's routes by limiting access to specific pages based on authentication. This technique ensures that users can only access authorized routes after logging in.

Why Protected Routes?

  1. Prevent unauthorized access to sensitive pages.
  2. Improve user experience by directing unauthenticated users to a login page.
  3. Simplify the maintenance of route permissions.

Setting Up Protected Routes 💡

To implement Protected Routes in your React JS application, we'll use the react-router-dom package.

Installation

First, install react-router-dom in your project:

bash
npm install react-router-dom

Creating Authenticated Route Component

Create a new component named AuthRoute to wrap our protected routes:

jsx
import React from 'react'; import { Route, Redirect } from 'react-router-dom'; const AuthRoute = ({ component: Component, isAuthenticated, ...rest }) => ( <Route {...rest} render={(props) => isAuthenticated ? ( <Component {...props} /> ) : ( <Redirect to={{ pathname: '/login', state: { from: props.location } }} /> ) } /> ); export default AuthRoute;

In the above code, the AuthRoute component checks if the user is authenticated. If the user is authenticated, it renders the provided component. If not, it redirects the user to the login page.

Wrapping Protected Routes

Now, let's wrap our protected routes with the AuthRoute component:

jsx
import React from 'react'; import { BrowserRouter as Router, Route } from 'react-router-dom'; import Dashboard from './Dashboard'; import Login from './Login'; import AuthRoute from './AuthRoute'; const App = () => ( <Router> <AuthRoute isAuthenticated={true} path='/dashboard' component={Dashboard} /> <Route path='/login' component={Login} /> </Router> ); export default App;

In this example, only authenticated users can access the /dashboard route, while the /login route is accessible to everyone.

Advanced Protected Routes Examples 💡

Conditional Rendering

Sometimes, you may want to render different components based on the user's authentication status. Here's an example:

jsx
import React from 'react'; import { Route, Redirect } from 'react-router-dom'; import Dashboard from './Dashboard'; import UserProfile from './UserProfile'; import Login from './Login'; import AuthRoute from './AuthRoute'; const App = () => ( <Router> <AuthRoute isAuthenticated={true} path='/dashboard' component={Dashboard} /> <AuthRoute isAuthenticated={true} path='/user-profile' component={UserProfile} /> <Route path='/login' component={Login} /> </Router> ); export default App;

In this example, authenticated users can access both the /dashboard and /user-profile routes.

Route-level Authentication

If you want to perform authentication at the route level, you can use withAuth higher-order component (HOC):

jsx
import React from 'react'; import { Route, Redirect } from 'react-router-dom'; import { withAuth } from './withAuth'; import Dashboard from './Dashboard'; import Login from './Login'; const AuthRequired = withAuth(({ component: Component, ...rest }) => ( <Route {...rest} render={(props) => isAuthenticated ? ( <Component {...props} /> ) : ( <Redirect to={{ pathname: '/login', state: { from: props.location } }} /> ) } /> )); const App = () => ( <Router> <AuthRequired path='/dashboard' component={Dashboard} /> <Route path='/login' component={Login} /> </Router> ); export default App;

In this example, we've created the AuthRequired HOC, which takes care of authentication for specific routes.

Quiz 🎯

Quick Quiz
Question 1 of 1

What is the primary purpose of using Protected Routes in a React JS application?

With this tutorial, you now have a solid understanding of Protected Routes in React JS! Stay tuned for more tutorials on CodeYourCraft! 🎉🌟