Home > Net >  Is it possible to redirect React app users from 127.0.0.1:3000 to localhost:3000?
Is it possible to redirect React app users from 127.0.0.1:3000 to localhost:3000?

Time:05-28

I am working on a React application with other developers who regularly navigate to http://127.0.0.1:3000/ to view/use the app. When accessing the app via http://127.0.0.1:3000/ it is partially functional, which is causing confusion. Is it possible to redirect users from http://127.0.0.1:3000/ to http://localhost:3000/? It seems like the <Route /> component from react-router-dom only deals with (as the name implies) the app route (and not the domain/port).

CodePudding user response:

This should work. Place it in your app component and it will monitor the web address and check whether it includes 127.0.0.1:3000. If so, it will redirect to your localhost.

if (window.location.href.includes("127.0.0.1:3000"){
  window.location.replace("http://localhost:3000/")
}

Even better, if you wanted to maintain the page the user is currently on, just replace 127.0.0.1:3000 for localhost:3000:

const currentDomain = window.location.href
 
if (currentDomain.includes("127.0.0.1:3000"){
  newDomain = currentDomain.replace("127.0.0.1:3000", "localhost:3000")
  window.location.replace(newDomain)
}
  • Related