skip to Main Content

Im trying to implement protected routes using react loader in react-router-dom.
I have a loader attribute in my Route tag which calls a dummy requireAuth() function that checks if the route is authenticated. This function is present in a util class. It redirects to /login path if authentication is false.

here is the code:

import { redirect } from "react-router-dom"

export async function requireAuth() {
const isLoggedIn = false
    if (!isLoggedIn) {
        throw redirect("/login")
    }
}

here is how I have configured my routes:

import React from 'react';
import ReactDOM from 'react-dom/client';
import {
  RouterProvider,
  createHashRouter,
  createRoutesFromElements,
  Route,
} from "react-router-dom";
import Dashboard from './pages/hosts/Dashboard';
import Login from './pages/Login';
import { requireAuth } from './utils';
const hashRouter = createHashRouter(createRoutesFromElements(
  <Route path='/' element={<Layout />}>
    <Route index element={<Home />} />
    <Route path='login' element={<Login />} />
    <Route path='about' element={<About />} />
    <Route path='vans' 
    element={<Vans />} 
    loader={vansLoader} 
    errorElement={<Error/>}
    />
    <Route 
    path='vans/:id' 
    element={<VanDetail />}
    loader={vanDetailLoader}
    />
    <Route 
    path='host' element={<HostLayout />} >
      <Route
        index
        element={<Dashboard />}
        loader={async () => await requireAuth()}
      />
      <Route 
      path='income' 
      element={<Income />}  
      loader={ 
        async ()=>{
        return null
      }}/>
      <Route 
      path='reviews' 
      element={<Reviews />}  
      loader={ 
        async ()=>{
        return null
      }}/>
      <Route 
      path='vans'
       element={<HostVans />}  
      loader={hostVansLoader}/>
      <Route 
      path='vans/:id' 
      element={<HostVansDetail/>} 
      loader={ hostVanDetailLoader}
      >
        <Route 
        index 
        element={<HostVanInfo />}  
        loader={ 
          async ()=>{
          return null
        }}/>
        <Route 
        path='pricing' 
        element={<HostVanPricing />} 
        loader={ 
          async ()=>{
          return null
        }} />
        <Route 
        path='photos' 
        element={<HostVanPhotos />}  
        loader={ 
          async ()=>{
          return null
        }}/>
  </Route>
</Route>
<Route path='*' element={<PageNotFound />} />
  </Route>
    ));

function App() {
  return (
    <RouterProvider router={hashRouter} />
  )
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />
);

When I load /host path, it should redirect me to the /login route. But I get the error
enter image description here

enter image description here

I am new to react and I’m learning. Please advise.

2

Answers


  1. Chosen as BEST ANSWER
    export async function requireAuth() {
        const isLoggedIn = false
        if (!isLoggedIn) {
           const response = redirect("/login")
           response.body = true;
           throw response;
        }
        return null;
    }
    

    I changed my util function to this, it worked.


  2. You need to return redirect("/login") instead of throwing it as an error in your loader function. Also I would suggest returning null after the if block to allow the default page load behaviour if isLoggedIn will be true in your production code

    export async function requireAuth() {
    const isLoggedIn = false
        if (!isLoggedIn) {
            return redirect("/login")
        }
        return null
    }
    

    Reference

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search