Remember the link and redirect back to it after a successful login using ReactJS

Subscribe to my newsletter and never miss my upcoming articles

Hello peeps, I am plxity, a JavaScript developer. Currently, I am working as an SDE Intern @Innovaccer. Today in this article I am going to explaining how to remember a link and redirect the user back to it after successful login using ReactJS and React-Router.

This article assumes that you have prior knowledge of ReactJS and an idea about React Router.

So let's begin...

Suppose you have a user who is not logged in on your platform and tries to access a protected route for example,

/post/123/comments

Usually, you will redirect him to a login page for accessing the protected route. But what if you want to redirect the user to the same route after successful login.

Suppose you have a main component 'App' which is responsible for rendering all the components. In that component use componentWillMount lifecycle method.

 componentWillMount() {
    const isLoggedIn = getData()
    const { pathname } = window.location

      if (!isLoggedIn) {
        if (pathname !== '/') {
          history.push(`/redirect${pathname}`, { redirectURL: pathname })
        }
      } else if (pathname === '/') {
        history.push('/post/')
      }
  }

To learn more about history in react-router refer to this Link

In this piece of code, getData() function is used to check if a valid token is present in localStorage or not.

and const {pathname} = window.location will give me the route which the user was trying to access.

Now we check if the user is logged in or not. If the user is logged-in we will simply go the else part and will be redirected to the main page of our application.

But if a user is not logged in, we will redirect him to a route /redirect${pathname} where pathname is the route which the user was trying to access before. We will redirect user using history.push(`/redirect${pathname}`, { redirectURL: pathname }).

Now comes the main part. React Router provide us feature to pass props in history.push(), so we will pass the pathname which user was trying to access as a prop.

Now go to the file where you have defined all the routes of your application. In that create a route,

<Route exact path="/redirect/*" component={SignIn} />

So whenever we will have a route like this it will redirect us to the SignIn component and in this component we can access parameters of history which we passed earlier.

this.props.location.state.redirectURL can be used to the access the props passed in history.

So now we will have a sign-in form in the component which will ask users for the credentials and there will be a function which helps in firing an action which sends a request to the server to check if the credentials provided by the user are right or not.

Along with your credentials pass pathname as a parameter.

  handleSignin = (e) => {
      var redirectURL = this.props.location.state.redirectURL
      const { loginDetail } = this.state
      const { makeLogin } = this.props
      LoginUser(loginDetail.email, loginDetail.password, redirectURL)
    }
    return false
  }

Now in the action creator if the request was successful and token for the user was generated we are ready to redirect the user.

Please refer to this sample action creator.

export const LoginUser = (username, password, redirectURL) => async (dispatch) => {
  try {
    const data = await Api.createLogin({ username, password })  // Sending credentials to the API
    setData(data.auth_token, null)  
    dispatch({ type: 'MAKE_LOGIN', data })
    if (redirectURL) {
      window.location = redirectURL
    } else {
      window.location = '/'
    }
  } catch (error) {
    dispatch({ type: 'ERROR', data: error.response.data })
  }
}

Now at this point, we will check if we have the redirectURL, if yes we will redirect the user to the to that location using window.location = redirectURL and if not we will follow the normal flow.

Hope you guys understood how to redirect the user. In case of any doubts please feel free to reach out to me.

For more tech stuff follow me on Twitter , GitHub

No Comments Yet