Spencer FengSpencer Feng

Authentication in React Apps with JWT: Part 9

Welcome to the ninth tutorial in our ‘Authentication and Authorisation in React Apps with JSON Web Tokens’ series. Currently, the user is able to create an account, login to and logout from our application, however, there is one thing that we have missed which is that a logged-in user can still access the login and signup page. In this tutorial, we will complete following tasks:

  • Redirect logged-in users to the home page if they try to access the login page
  • Redirect logged-in users to the home page if they try to access the signup page

Redirect logged-in users to the home page if they try to access the login page

We will use the Redirect component from react-router-dom to redirect logged-in users to the home page when they try to access the login page. Let’s open ‘client/src/App.js’ file and import Redirect component from react-router-dom by updating the code below

import { Route, Switch } from 'react-router-dom';

to

import { Route, Switch, Redirect } from 'react-router-dom';

After importing Redirect component into ‘client/src/App.js’, let’s replace the code below

<Route path="/login" component={LoginPage} />

with

<Route path="/login" render={() => (
    ! IsEmpty(this.props.store.getState().cUser) ? (
        <Redirect to="/" />
    ) : (
        <LoginPage />
    )
)} />

What the change does is very obvious: if the cUser object in the state is empty, the application redirects the user to the home page, otherwise, the application loads the login page.

Redirect logged-in users to the home page if they try to access the signup page

This is very similar to what we did in the previous section. Let’s replace the code in ‘client/src/App.js’

<Route path="/signup" component={SignupPage} />

with

<Route path="/signup" render={() => (
    ! IsEmpty(this.props.store.getState().cUser) ? (
        <Redirect to="/" />
    ) : (
        <SignupPage />
    )
)} />

After making those 2 changes in ‘client/src/App.js’, now logged-in users will be redirected to home page when they try to access ‘login’ and ‘signup’ pages.

View the source code for this tutorial on GitHub.

Please sign up to our Newsletter if you want to get notified when new tutorials are available.

×