React Router Create Protected Route

Protected / Private Routing is helpful in case of backend development with ReactJs. Or we can say only authenticated users can only access the particular route. We can make a protected/private route with React Router Dom package. I am using React Router 5.x.

Protected / Private Route

Basically, I am building a dashboard with React.js that requires the login and the dashboard route. Of cause I don’t want to give the access of the dashboard to the un-authenticated user. And this is where we need the protected routing.

We are using the React Redux and React Router Dom packages with React. React Redux is for managing states ( data-state and UI-state ) in single page application (SPA). Because we need the authentication state to check who’s going to access the particular route.

Simply we need to check the authenticated state and let the access the defined component if the request is authenticated, otherwise, redirect the user to the login route. Let’s jump to the codes to make a protected route.

import React from 'react'
import { Route, Redirect, withRouter } from 'react-router-dom'
import { connect } from 'react-redux'

const PrivateRouteHandler = ({ component, auth, ...rest }) => {

    let ComponentToRender = component;

    return (
        <Route
            {...rest}
            render={props =>
                auth.isAuthenticated ? (
                    <ComponentToRender {...props} />
                ) : (
                    <Redirect
                        to={{
                            pathname: "/login",
                            state: { from: props.location }
                        }}
                    />
                )
            }
        />
    );
}

const mapStateToProps  = (state) => ({ auth: state.auth });
export const PrivateRoute = withRouter(connect(mapStateToProps)(PrivateRouteHandler));

Everything is simple to grab if you are not new to javascript. But does the ...rest means? As you see we are accessing all the route properties in ({ component, auth, …rest }) and the ...rest means all the properties except component to new object assigned to variable rest.

This is the sample of data that we get through the defined store.

React Redux State Example

Next step is to use the created PrivateRoute.

<PrivateRoute exact path="/dashboard" component={Protected} />
<Route exact path="/login" component={Login} />

Helpful resources

Posted by Jogesh Sharma

Jogesh Sharma is a web developer and blogger who loves all the things design and the technology, He love all the things having to do with PHP, WordPress, Joomla, Magento, Durpal, Codeigniter, jQuery, HTML5 etc. He is the author of this blog.