Creating Protected routes in React JS

Tarak
Tarak
Mar 27 · 4 min read

In this story we would write create a basic react app with routing and create a protected route where only authorized users will be able to access it.

First of all create an app using create-react-app and install react-router-dom

create-react-app protected-routes
npm install react-router-dom

There are 3 important steps to use react-router.

  1. We have to wrap our application inside {BrowserRouter} from react-router-dom
  2. Define our routes using {Route} component
  3. Link routes using {Link} component

Addition to these, to create a protected-route we will do the following:

4. Create a fake authentication service

5. Create a protected Route component and check for user validation using the fake authentication service

Now, let us wrap our application inside BrowserRouter according to setp 1. Open index.js file and import the BorwserRouter component form react-router-dom and wrap the <App/> component inside it

import {BrowserRouter} from ‘react-router-dom’;
ReactDOM.render(
<BrowserRouter><App />
</BrowserRouter>, document.getElementById(‘root’));

Create two separate components for Public and Private routes which will be used for our routing purpose. Our code for Public.js and Private.js can be as follows:

import React from 'react';const Public =() => {return <h1> This is a Public route</h1>}export default Public;

Similarly Private.js file can be created

Now, let’s add a new file called Router.js and add the routes

import React, {Component} from 'react';import { Switch, Route, Redirect } from 'react-router-dom';import Public from './components/Public';import Protected from './components/Protected';const Router = (props) => (<Switch><Route exact path='/public' component={Public}/><Route path="/protected" component={Protected} /></Switch>)export default Router;

Let us add a file called Header.js that has three links for Home, Public and Protected and two buttons to login and logout

import React from 'react';import { Link } from 'react-router-dom';class Header extends React.Component{constructor(props){super(props);this.login=this.login.bind(this);this.logout=this.logout.bind(this);}login(){}logout(){}render(){return(<div><Link to='/'>Home</Link><br/><Link to='Public'>Public</Link><br/><Link to='protected'>Protected</Link><br/><button onClick={this.login}>Login</button><br/><button onClick={this.logout}>Logout</button></div>);}}export default Header;

Next step is to update the App.js file to include our header and router

import React, { Component } from 'react';import './App.css';import  Header from './components/Header';import Router from './Router';class App extends Component {render() {return (<div className="App"><Header/><Router/></div>);}}export default App;

At this step we have created a basic app with Routes set up. Our page looks as follows:

Now that we have finished the basic app with routes, let us add a fake authentication service and update the Header.js and Routes.js files to be able to use protected routes

Create a file called Auth.js and add the following code

const Auth = {isAuthenticated: false,authenticate() {this.isAuthenticated = true;},signout() {this.isAuthenticated = false;},getAuth() {return this.isAuthenticated;}};export default Auth;

Now, we need to update the Router.js file. We will be creating a component called PrivateRoute which would accept the component to which application has to route if the user has authenticated. Otherwise user will be redirected to home page. And finally update the Route that we used to the newly created protected route.

The final code of Router.js will be as follows. Notice the creation of Private Route and usage of the App component that was created.

import React, {Component} from 'react';import { Switch, Route, Redirect } from 'react-router-dom';import Public from './components/Public';import Protected from './components/Protected';import Auth from './Auth';const Router = (props) => (<Switch><Route exact path='/public' component={Public}/><PrivateRoute path="/protected" component={Protected} /></Switch>)const PrivateRoute = ({ component: Component, ...rest }) => (<Route{...rest}render={props =>Auth.getAuth() ? (<Component {...props} />) : (<Redirectto={{pathname: "/"}}/>)}/>);export default Router;

Last, we need to update the Header.js file so that we will be able to update the login/logout state based on the button click.

import React from 'react';import { Link } from 'react-router-dom';import Auth from '../Auth';class Header extends React.Component{constructor(props){super(props);this.login=this.login.bind(this);this.logout=this.logout.bind(this);}login(){Auth.authenticate();}logout(){Auth.signout();}render(){return(<div><Link to='/'>Home</Link><br/><Link to='Public'>Public</Link><br/><Link to='protected'>Protected</Link><br/><button onClick={this.login}>Login</button><br/><button onClick={this.logout}>Logout</button></div>);}}export default Header;

Once the app is run, if the user clicks on Login button and try to navigate the the protected route, routing would happen. If the user is Logged out or not signed in, clicking on protected route would redirect the user to home page.

Here is a working example of the above code:

Source code of the above example can be downloaded form the following github page

Happy Learning :)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade