2

I have created a react app in which I have a login page as the first page and we login it enters into the application. So when I run the app using "yarn start" the app runs at "localhost:8082" by default but I want that when I run "yarn start" command it shows the url like "localhost"8082/Login" because the first page is the login page.

And when I successfully logged in it again shows "localhost:8082" but I want after login it shows "localhost:8082/Home".

So is there any way to change the url like this that I mentioned.

Attaching some code for reference.

App.tsx code:-

import "./css/App.css";
import {
  AuthenticatedTemplate,
  UnauthenticatedTemplate,
} from "@azure/msal-react";
import { Login } from "./pages/Login";
import Routers from "./components/Routers";

function App() {
  return (
    <div>
      <AuthenticatedTemplate>
        <Routers />
      </AuthenticatedTemplate>

      {
        <UnauthenticatedTemplate>
          <Login />
        </UnauthenticatedTemplate>
      }
    </div>
  );
}

export default App;

Routers.tsx code:-

import { BrowserRouter, Routes, Route, Outlet} from "react-router-dom";
import Home from "../pages/Home";
import About from "../pages/About";
import Contact from "../pages/Contact";

function Routers() {
  return (
    <div className="Routers">
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/Home" element={<Home />} /> 
          <Route path="/About" element={<About />} />
          <Route path="/Contact" element={<Contact />} />
        </Routes>
        <Outlet />
      </BrowserRouter>
    </div>
  );
}

export default Routers;

So I want that the first page when I run "yarn start" command will be "localhost:8082/Login" and when I login the url must be "localhost:8082/Home".

I have tried it to achieve it through different ways but I was unable to do so. I don't want to add a homepage element in package.json as it is not working in my case.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Avanish
  • 51
  • 6

1 Answers1

0

Short of just starting the app and navigating to "/login" directly you could use a mounting useEffect hook in the root component of your app to manually redirect to "/login". I'd really suggest implementing protected routes and place the home "/" route under protection so unauthenticated users will be redirected to "/login" automatically.

Create protected authenticated and unauthenticated route components.

import { Navigate, Outlet, useLocation } from 'react-router-dom';
import {
  AuthenticatedTemplate,
  UnauthenticatedTemplate,
} from "@azure/msal-react";
import { useAuth } from '../path/to/AuthContext'; // <-- you'll need to implement this, however it fits with the Azure authentication

const PrivateRoutes = () => {
  const location = useLocation();
  const { isAuthenticated } = useAuth();

  if (isAuthenticated === undefined) {
    return null; // or loading indicator/spinner/etc
  }

  return isAuthenticated 
    ? (
      <AuthenticatedTemplate>
        <Outlet />
      </AuthenticatedTemplate>
    )
    : <Navigate to="/login" replace state={{ from: location }} />;
}

const AnonymousRoutes = () => {
  const { isAuthenticated } = useAuth();

  if (isAuthenticated === undefined) {
    return null; // or loading indicator/spinner/etc
  }

  return isAuthenticated 
    ? <Navigate to="/" replace />
    : (
      <UnauthenticatedTemplate>
        <Outlet />
      </UnauthenticatedTemplate>
    );
}

Routers.tsx

import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "../pages/Home";
import About from "../pages/About";
import Contact from "../pages/Contact";
import { Login } from "./pages/Login";
import { AnonymousRoutes, PrivateRoutes } from '../components/auth';

function Routers() {
  return (
    <div className="Routers">
      <BrowserRouter>
        <Routes>
          <Route element={<PrivateRoutes />}>
            <Route path="/" element={<Home />} />
            <Route path="/Home" element={<Home />} /> 
            <Route path="/About" element={<About />} />
            <Route path="/Contact" element={<Contact />} />
          </Route>
          <Route element={<AnonymousRoutes />}>
            <Route path="/login" element={<Login />} />
          </Route>
        </Routes>
        <Outlet />
      </BrowserRouter>
    </div>
  );
}

App.tsx

import Routers from "./components/Routers";

function App() {
  return (
    <div>
      <Routers />
    </div>
  );
}
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • Hi @Drew Reese, I am not getting how to config useAuth() as when I use your code it is redirecting me back to the login page even after successful login. Can you please help me with it? – Avanish Jan 03 '23 at 13:12
  • @Avanish I'm assuming somewhere near the root of your app you've *some* sort of auth provider component, and I'm assuming it provides a hook to use for this purpose or exposes the authentication status to the app. Here's a `@msal-react` documentation for some [hooks](https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-react/docs/hooks.md). – Drew Reese Jan 03 '23 at 16:32
  • Hi @Drew Reese, I tried with the approach which you have suggested but I am facing an issue. When I launch my react app using "yarn start" it redirects me to "localhost:8082/Login" as expected but after logging in with correct credentials it is not redirecting into the application(i.e "localhost:8082/Home") and remains on the login screen even after logging in. What can be the possible reason for this? – Avanish Jan 05 '23 at 14:04
  • @Avanish Typically the `Login` component, upon a successful log in, will take the `from: location` value that was passed in route state and redirect *back* to the route the user was originally attempting to access, or a safe default route. See my answer [here](/a/66289280/8690857) to see the general flow. – Drew Reese Jan 05 '23 at 17:19
  • Hi @Drew Reese, in this same react app I want to add database login along with Azure AD Authentication. So for the same, how can I manage the "isAuthenticated" thing which is declared in Auth.tsx and is suggested by you. If you can please help me out in this. I am not getting the approach for it anywhere. For you reference I have posted the detailed question here(https://stackoverflow.com/questions/75056546/how-to-use-database-login-and-azure-ad-authentication-both-in-a-react-app-at-sam). Please have a look and suggest some approach for it. – Avanish Jan 10 '23 at 14:29