How to redirect to any url after login in redirect?

Viewed 3870

I want to redirect my user to any url that he types in after logging in for example; my user types in the browser, http://localhost:3000/login/tickets, If he has not logged in I would need the program to load the login page, and after login, the program redirects to this page, I can do it with a single page but I wanted it to be dynamic, something like this.

    isAuthenticated()
      ? (
        <Component {...props} />
        ) : <Redirect to=`/login?next=${this.props.location.search}` />
      )}

soon this redirect would load the login page with the tag next

5 Answers

My solution was to do essentially what you describe. I made a HOC to wrap my route's component in if it requires that the user be logged in:

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

/**
 * Higher-order component (HOC) to wrap restricted pages
 */
export default function LoggedInOnly(BaseComponent) {
    class Restricted extends Component {
        state = {};
        static getDerivedStateFromProps(nextProps) {
            const { history, location } = nextProps;
            if (!nextProps.isLoggedIn) {
                history.replace({ pathname: '/signin', search: `dest=${encodeURIComponent(location.pathname)}` });
            }
            return null;
        }
        render() {
            const { location, staticContext } = this.props;

            if (this.props.isLoggedIn) return <BaseComponent {...this.props} />;

            const destinationURL = `/signin?dest=${encodeURIComponent(location.pathname)}`;
            if (staticContext) staticContext.url = destinationURL;

            return <Redirect to={destinationURL} />;
        }
    }

    const mapStateToProps = state => ({
        isLoggedIn: !!state.globalUserState.loggedInUserEmail,
    });

    return withRouter(connect(mapStateToProps)(Restricted));
}

I also set the url on the static context in my case so I can handle redirects appropriately in server side rendering. If you're not doing the same you can ignore that part.

For using it, though, I redirect after my SSR render function, like so:

if (context.url) {
    console.log(`Redirecting to URL ${context.url}`);
    return res.redirect(context.url);
}

A route using this would look like:

<Route path="/preferences" component={LoggedInOnly(SettingsView)} />

On my login page I grab the url parameters to see if there's a destination. If there is, I redirect there on login success.

I do this using query-string and the search component of the location:

const { destination } = queryString.parse(props.location.search);

The above assumes you're using withRouter to get the location info in the props.

On authentication success in the client I simply redirect to destination if it exists:

window.location.href = this.props.destination;

You could also use history.push or similar to accomplish the above.

In my case, as you can see, I'm using redux to track the logged in user state.

you need to update state by taking a variable and apply check wether it has been changed or not, if yes then redirect to desired page ,if not revert back. Since you have not posted your whole code .You can refer to this video for wider and clear perspective : https://www.youtube.com/watch?v=zSt5G3s3OJI

You can accomplish what you need by doing some thing like this:

if(isAuthenticated)
  this.props.history.push('/login', {lastPage: this.props.location.match})

and after user gets logged in you cant redirect him to passed param lastPage!

Another way is to store lastPage in redux and access it after user get logged in.

I had the same problem, i made a HOC to solve it.

import React from "react";
import { connect } from "react-redux";
import Login from "../../Auth/Login";
import { withRouter } from "react-router-dom";
import qs from "querystring";

const signInPath = "/signin";
const signUpPath = "/signup";
const forgotPassPath = "/forgot";
const resetPassPath = "/resetpassword";
const returlUrlPath = "returnUrl";

const allowedPaths = pathname =>
  pathname === signInPath ||
  pathname === signUpPath ||
  pathname === forgotPassPath ||
  pathname === resetPassPath;

const homePath = "/";

export default Component => {
  class AuthComponent extends React.Component {
    componentDidMount() {
      this.checkAuthentication();
    }

    componentDidUpdate(nextProps) {
      if (
        nextProps.location.pathname !== this.props.location.pathname ||
        this.props.loggedIn !== nextProps.loggedIn
      ) {
        this.checkAuthentication();
      }
    }

    checkAuthentication() {
      const {
        loggedIn,
        history,
        location: { pathname, search }
      } = this.props;
      if (!loggedIn) {
        if (!allowedPaths(pathname)) {
          const returlUrl =
            pathname.length > 1
              ? `${returlUrlPath}=${pathname.replace("/", "")}`
              : undefined;
          history.replace({ pathname: signInPath, search: returlUrl });
        }
      } else if (search) {
        const parsedSearch = qs.parse(search.replace("?", ""));
        if (parsedSearch.returnUrl) {
          history.replace({ pathname: parsedSearch.returnUrl });
        } else {
          history.replace({ pathname: homePath });
        }
      } else if (
        history.location.pathname === signInPath ||
        history.location.pathname === signUpPath
      ) {
        history.replace({ pathname: homePath });
      }
    }

    shouldRedirectToLogin() {
      const {
        location: { pathname }
      } = this.props;
      return (
        !this.props.loggedIn &&
        pathname !== signUpPath &&
        pathname !== forgotPassPath &&
        pathname !== resetPassPath
      );
    }

    render() {
      return this.shouldRedirectToLogin() ? (
        <Login></Login>
      ) : (
        <Component {...this.props}></Component>
      );
    }
  }
  return withRouter(
    connect(({ user: { loggedIn } }) => {
      return {
        loggedIn
      };
    })(AuthComponent)
  );
};

Thanks for all, after a lot of research i get only:

const  params  = (this.props.children.props.computedMatch.url);
       return <Redirect to={`/login/?next=${params}`} />;
Related