React - Redirect to Login Page if Unauthenticated
Tutorial built with React 17.0.2 and React Router 5.3.0
This is a super quick post to show how to redirect users to the login page in a React app that uses React Router. The redirect applies to users that attempt to access a secure/restricted page when they are not logged in.
The below components are part of a React JWT authentication tutorial I posted recently that includes a live demo, so to see the code running check out React + Recoil - JWT Authentication Tutorial & Example.
React Private Route Component
The PrivateRoute
component wraps the React Router Route
component and implements authorization logic in the render
function. The React component returned by the render function is rendered by the route component.
If the user is logged in the Component
prop is rendered, otherwise if the user is not logged in the React Router Redirect
component is rendered which redirects the user to the /login
page. The requested path (props.location
) is passed with the redirect in the state.from
property so the login page can redirect the user back their desired page after successful login.
The current logged in (auth
) state of the user is retrieved from Recoil global state with a call to useRecoilValue(authAtom)
.
import { Route, Redirect } from 'react-router-dom';
import { useRecoilValue } from 'recoil';
import { authAtom } from '_state';
export { PrivateRoute };
function PrivateRoute({ component: Component, ...rest }) {
const auth = useRecoilValue(authAtom);
return (
<Route {...rest} render={props => {
if (!auth) {
// not logged in so redirect to login page with the return url
return <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
}
// authorized so return component
return <Component {...props} />
}} />
);
}
React App Component with Private Route
The App
component is the root component of the example app, it contains the outer html, main nav and routes for the application.
The /login
route is public, and the home route (/
) is secured by the private route wrapper component that checks if the user is logged in before rendering.
import { Router, Route, Switch, Redirect } from 'react-router-dom';
import { Nav, PrivateRoute } from '_components';
import { history } from '_helpers';
import { Home } from 'home';
import { Login } from 'login';
export { App };
function App() {
return (
<div className="app-container bg-light">
<Router history={history}>
<Nav />
<div className="container pt-4 pb-4">
<Switch>
<PrivateRoute exact path="/" component={Home} />
<Route path="/login" component={Login} />
<Redirect from="*" to="/" />
</Switch>
</div>
</Router>
</div>
);
}
Need Some React Help?
Search fiverr to find help quickly from experienced React freelance developers.
Follow me for updates
I share all new blog posts on Twitter and Facebook.
When I'm not coding
My wife and I are attempting to ride motorcycles around Australia and vlog about it on YouTube.