React
Redirect to External Url

https://www.stackhawk.com/blog/react-open-redirect-guide-examples-and-prevention/

Basic RedirectsRedirects - React ExamplesMore Redirecting

https://bobbyhadz.com/blog/react-redirect-to-external-url#:~:text=Use%20the%20window.,location.

Redirect to an External URL in React

Borislav Hadzhiev

Last updated: Apr 19, 2022

Redirect to an External URL in React #

Use the window.location.replace() method to redirect to an external url in React, e.g. window.location.replace('https://google.com'). If a certain condition is met, you can programmatically replace the current resource with the provided URL by calling the replace() method.

App.js

import {BrowserRouter as Router, Link, Route, Routes} from 'react-router-dom';

export default function App() {
  return (
    <Router>
      <div>
        <Link to="/about">About</Link>

        <br />
        <br />

        {/* 👇️ If you need to simply link to external URL */}
        <a href="https://google.com" target="_blank" rel="noreferrer">
          Google.com
        </a>
      </div>

      <Routes>
        <Route path="/about" element={<About />} />
      </Routes>
    </Router>
  );
}

function About() {
  // 👇️ redirect to external URL
  window.location.replace('https://google.com');

  return null;
}

react redirect external url

The code snippet redirects to an external URL when the user navigates to the /about route.

This could be any other condition and can also be used in an if statement.

You can use the location.replace() method to replace the current resources with the provided URL.

 

When using the replace() method, the current page will not be saved in session history.

In other words, the user won't be able to use the back button to navigate to it.

We want to avoid this behavior because if the user navigates back to the /about route, they would get redirected to google.com again and they wouldn't be able to use the back button functionality.

If you want to enable the user to go back to the page that redirected them, use window.location.href instead of window.location.replace.

App.js

import {BrowserRouter as Router, Link, Route, Routes} from 'react-router-dom';

export default function App() {
  return (
    <Router>
      <div>
        <Link to="/about">About</Link>

        <br />
        <br />

        {/* 👇️ If you need to simply link to external URL */}
        <a href="https://google.com" target="_blank" rel="noreferrer">
          Google.com
        </a>
      </div>

      <br />

      <Routes>
        <Route path="/about" element={<About />} />
      </Routes>
    </Router>
  );
}

function About() {
  // 👇️ using window.location.href 👇️
  window.location.href = 'https://google.com';
  return null;
}

Using window.location.href instead of window.location.replace is different because it allows the user to go back to the route that redirected them.

In this particular case if the user clicks back, they would get redirected to google again.

Note that if you need to simply link to an external URL, you can use an <a> tag.

App.js

export default function App() {
  return (
    <a href="https://google.com" target="_blank" rel="noreferrer">
      Google.com
    </a>
  );
}

The react router Link component is intended to only be used for internal navigation.

When the target attribute on the a element is set to _blank, the external link is opened in a new tab. You can remove the attribute if you want to open the external URL in the same tab.

https://atomizedobjects.com/blog/react/how-to-redirect-in-reactjs/

How to redirect in ReactJs

Just before we get stuck into the details of how to redirect in ReactJs, here is a quick cheat sheet to redirecting in React Js / JavaScript (We will go into detail about each later on):

JS – redirect:

window.location.replace("https://google.com/");

JS – user event navigation:

window.location.href = "https://google.com/";

Learn more about the JS implementation here.

 

React.Js hooks – react-router-dom v6:

const navigate = useNavigation();
navigate("/redirect-example", { replace: true });

React.Js hooks – react-router-dom v5:

const history = useHistory();
history.push("/redirect-example");

React.Js JSX – react-router-dom v5:

import { Redirect } from 'react-router-dom'
…
<Redirect to='/redirect-example' />

How to redirect in ReactJs cheat sheet - js, react-router-dom v5 & v6

In React there are many libraries that you can use to handle client side routing & navigation and redirection will be a part of those libraries, however the principle of the redirects will be very similar for each.

The principle of a client side redirect will be to push or replace a new route/url to the history of the window in order to change the page.

In vanilla JavaScript you would redirect using window.location.replace, or window.location.href depending on the scenario.

You would use the window.location.replace to perform a redirect which replaces the item in history to prevent loops, and you would use the window.location.href to add onto the history based on a user action.

When it comes to libraries used in ReactJs it will be a similar flow, you will just need to find the specific component/method to use for the given library, such as history.push.

We will shortly look at the differences between external vs internal urls as well as absolute and relative routes.

But first let’s dive into how to specifically redirect using some popular React libraries such as react-router.

How to redirect in ReactJs with react-router/react-router-dom v6

Firstly we will take a look into how we can redirect in react using the v6 version of react-router and react-router-dom.

It is fairly straightforward and makes use of a hook called useNavigate which we can just pass our url into with some optional parameters and then it will programmatically navigate/redirect to the new route/url.

Here is an example of the useNavigate hook in use:

import React from "react";
import { useNavigate } from "react-router-dom";

export default function HookRedirectExample() {
  const navigate = useNavigate();
  return (
    <button
      type="button"
      onClick={() => navigate("/redirect-example/", { replace: true })}
    >
      Redirect
    </button>
  );
}

As you can see in the above example it is fairly straightforward to use, all we need to do is initialize the hook in the component and then call navigate with our url.

I have included the parameter replace: true which will replace the history entry rather than add to it which is ideal for automatic redirection where you don’t want the user to be able to return to that page directly.

How to redirect in ReactJs with hooks & react-router/react-router-dom v5

Next we will look at the v5 version of the react-router library which is still widely used and we will start by using react hooks, more specifically the useHistory hook. Making use of the react hook implementation of the history context with useHistory makes it much cleaner and easier to use than in comparison to the JSX option.

All we need to do is import the useHistory hook from react-router-dom and then initialise it in a component like so:

import React from "react";
import { useHistory } from "react-router-dom";

export default function HookRedirectExample() {
  const history = useHistory();
  return null;
}

Once we have a basic setup complete for our component, we then just need to push a new url to the history using history.push("URL_HERE") whenever a user performs a certain action, in our example we will use a button click.

import React from "react";
import { useHistory } from "react-router-dom";

export default function HookRedirectExample() {
  const history = useHistory();
  return (
    <button type="button" onClick={() => history.push("/redirect-example/")}>
      Redirect
    </button>
  );
}

Now when the user clicks on the button we will push a new relative URL into the history which will cause the user to be redirected to the desired page.

How to redirect in ReactJs with JSX & react-router/react-router-dom v5

Next we will look at how to essentially do the above with a mixture of conditional rendering and the Redirect component from react-router-dom.

The principle of the redirect using theRedirect component is similar to the react hook version although we need to render the Redirect component instead of calling a function.

This makes it a little less intuitive in comparison to the hook version where you can just call a function as well as slightly different use cases, but it is still a valid way of doing it.

Let’s take our previous example but this time introduce some props to show the real benefit of using the Redirect component to redirect in ReactJS.

 

import React from "react";
import { Redirect } from "react-router-dom";

export default function HomePage({ authenticated, name }) {
  if (!authenticated) {
    return <Redirect to="/login" />;
  }
  return <h1>Welcome {name}</h1>;
}

As you can see in the above example, we are checking to see if the user is authenticated, if not we are rendering the redirect component, and if they are logged in, we are rendering the home page component which displays a welcome message.

If the user is not authenticated the Redirect component will be rendered which will then trigger the page to redirect to the login page.

 

In summary of the Redirect component it is a nice way to redirect based off of side effects rather than actions.

It is possible to create the same functionality with the hook method as well with the use of useEffect and the dependency array like so:

import React, { useEffect } from "react";
import { useHistory } from "react-router-dom";

export default function HomePage({ authenticated, name }) {
  const history = useHistory();

  useEffect(() => {
    if (!authenticated) {
      history.push("/login");
    }
  }, [authenticated]);
  return <h1>Welcome {name}</h1>;
}

How to redirect in ReactJs with react-router-dom

How to redirect in ReactJs with JavaScript

The last redirection method in React is using vanilla JavaScript. React is a JavaScript based library, which means we can run plain JavaScript as well if we need to.

If you are already making use of a routing library, then it would not be recommended to use vanilla JavaScript to navigate or perform redirections because it could interfere with the routing library.

Instead the redirection from vanilla JavaScript is best used with React when you only need very basic navigation where an anchor element can’t do it.

The reason why you might opt for a vanilla JavaScript approach for redirection in React is simple because you might not need to add a whole new library to your application if you have a simple use case, and therefore might make some performance savings by reducing the overall application size.

Here is a quick example of how you can use JavaScript to navigate from a React application:

import React from "react";
import { sendAnalyticsEvent } from "./example-anaylytics.js";

const handleRedirect = () => {
  sendAnalyticsEvent("redirect");
  window.location.href = "http://google.com/";
};

export default function JsRedirectExample() {
  return (
    <button type="button" onClick={handleRedirect}>
      Redirect
    </button>
  );
}

 

Or for an automatic redirect:

import React from "react";
import { sendAnalyticsEvent } from "./example-anaylytics.js";

export default function JsRedirectExample() {
  sendAnalyticsEvent("redirect");
  window.location.replace("http://google.com/");
  return null;
}

Internal urls vs external urls for redirecting in react

The difference between internal and external urls/routes is simple enough where internal urls will navigate within the current website, and external urls/routes will navigate the user to a different website.

The reason why it is important to understand the difference is because handling the different types of url can be very different.

For simplicity let’s assume that we are always talking about urls/routes that will replace the current page (not open in a new tab).

If you are navigating to an external route from your page, you might not need to worry about running it through your library because in most cases the state of the application will be lost after you navigate away from the page in which case using either the React based library or a vanilla JS implementation won’t matter (This may vary between library, so make sure you read the docs!).

If you have an internal route/url though that is managed and handled by a react library you will always want to make use of the libraries implementation or redirection/navigating (even with JSX elements) so that the library can track, manage and render each page whilst maintaining the history.

Absolute urls vs relative urls for redirecting in react

Once again, absolute vs relative urls have a simple difference and it works in the same way as it does when referencing files in a directory.

A relative path is based on where you currently are, but an absolute path does not matter where you currently are and will always take you to the same place.

Generally speaking when it comes to client side applications, a relative path will be relative from the root of the URL/website.

 

For example, if you are on https://atomizedobjects.com/blog/react/how-to-redirect-in-reactjs/ and you navigate to a relative path of /blog/react it will take you to https://atomizedobjects.com/blog/react/.

However if you wanted to do the same thing but as an absolute path you would just need to add the root as well so you would enter https://atomizedobjects.com/blog/react/ instead of /blog/react.

 

 

You can redirect a web page to another page in a number of ways including server-side redirects, HTML meta refresh redirects and JavaScript redirects. In this tutorial, we will demonstrate how you can easily redirect a page using JavaScript by giving examples for various scenarios. Before we move on to our examples though, let’s briefly mention about the importance of using such redirects responsibly and only when you really have to.

Interruptive or unexpected web page redirects are considered to be very annoying from the user perspective, since they negatively affect the overall user experience. For example, if you redirect the users to another website as soon as they land on your site, that will obviously cause frustration for them. Also, if you take the users to an irrelevant page after a timer, after they click on a button or image, or after they complete a certain action on your site, that will most probably result in the user wanting to leave your site at once and never come back.

Another reason you should avoid redirects where possible is that the search engines do not favor websites that use redirects, especially if they are deceptive. Your site may even get removed from their index if you have redirects on your website that try to trick the search engine bots or that result in a bad user experience. Having said that, there are also some cases where a redirect can be quite useful based on the context of your web page or a specific feature of your web application and we will leave the decision whether to use a redirect or not, to you.

Keeping the above points in mind, we can now continue with discussing about how JavaScript redirects work.

JavaScript Redirect Methods

You can redirect a web page via JavaScript using a number of methods. We will quickly list them and conclude with the recommended one.

In JavaScript, window.location or simply location object is used to get information about the location of the current web page (document) and also to modify it. The following is a list of possible ways that can be used as a JavaScript redirect:

// Sets the new location of the current window.
window.location = "https://www.example.com";

// Sets the new href (URL) for the current window.
window.location.href = "https://www.example.com";

// Assigns a new URL to the current window.
window.location.assign("https://www.example.com");

// Replaces the location of the current window with the new one.
window.location.replace("https://www.example.com");

// Sets the location of the current window itself.
self.location = "https://www.example.com";

// Sets the location of the topmost window of the current window.
top.location = "https://www.example.com";

Though the above lines of JS code accomplish a similar job in terms of redirection, they have slight differences in their usage. For example, if you use top.location redirect within an iframe, it will force the main window to be redirected. Another point to keep in mind is that location.replace() replaces the current document by moving it from the history, hence making it unavailable via the Back button of the browser.

It is better to know your alternatives but if you want a cross-browser compliant JavaScript redirect script, our recommendation will be to use the following in your projects:

window.location.href = "https://www.example.com";

Simply insert your target URL that you want to redirect to in the above code. You can also check this page to read more about how window.location works. Now, let’s continue with our examples.

JavaScript Redirect: Redirect the Page on Page Load

In order to redirect the user to another website immediately after your website is opened, you can use the following code at the top of your page, within the element. Or, if you are using a separate .js file, put the following code into that file and remember to link to it from the head of your page.

<script>
  window.location.href = "https://www.example.com";
</script>

Simply replace the example URL with the one you want to redirect to. Note that, with this type of redirection, the visitors will not see your web page at all and be redirected to the target URL instantly.

JavaScript Redirect: Redirect the Page After a Certain Period

In order to redirect the user to another website after a certain time passes, you can use the following code:

<script>
setTimeout(function() {
  window.location.href = "https://www.example.com";
}, 3000);
</script>

The above function will redirect the page 3 seconds after it fully loads. You can change 3000 (3 x 1000 in milliseconds) as you wish.

JavaScript Redirect: Redirect the Page After an Event or User Action

Sometimes, you may want to send the user to another page after a certain event or action takes place, such as a button click, an option selection, a layout change, a form submission, a file upload, an image drag, a countdown timer expiration or things like that. In such cases, you can either use a condition check or assign an event to an element for performing the redirect. You can use the following two examples to give you a basic idea:

<script>
// Check if the condition is true and then redirect.
if ( ... ) {
  window.location.href = "https://www.example.com";
}
</script>

The above code will do the redirection if the condition is true.

<script>
// onclick event is assigned to the #button element.
document.getElementById("button").onclick = function() {
  window.location.href = "https://www.example.com";
};
</script>

The above code will do the redirection when the user clicks the #button element.

This is how JavaScript redirect basically works. We hope that the above examples will help you while handling your web page redirects.

 

Scroll to Top