'how to redirect from a utility function in remix run

I am using Remix-run and i want to redirect to my login page from a auth utility function. but it doesnt work. here is a similar function to my authentication utility method

import { redirect } from 'remix';

 async function authenticate(request){
  try{
    const user = await rpc.getUser(request);
    return user
  } catch(e){
   console.log(e) // logs error when rpc fails
   if(e.response.status === 401){
    return redirect('/login')
   }
   return redirect('/500')
  }
 }

//component.jsx

import {useLoaderData } from 'remix';

export async function loader({ request }) {
  const user = await auth.authenticate(request);
  return { user };
}

export default function Admin(){
 const { user } = useLoaderData();
  return <h1>{user.name}</h1>
}

if the auth rpc fails i get the error in the logs. but redirect never happens. If i move redirect part to my loader function it works as expected. its not only working inside the utility function



Solution 1:[1]

After digging in the docs and remix jokes app demo. i found that you need to throw a redirect from any other function other than loaders/actions to do redirects. you can also throw Http response if wanted.

import { redirect } from 'remix';

 async function authenticate(request){
  try{
    const user = await rpc.getUser(request);
    return user
  } catch(e){
   if(e.response.status === 401){
    throw redirect('/login')
   }
   throw redirect('/500')
  }
 }

Solution 2:[2]

This sadly didn't work for me.

I am trying to redirect programmatically depending on a state update. For this purpose I created this fn:

const redirectToNested = (to) => {
  throw redirect('/to');
};

which lives outside my react component, the loader or action. I am still getting a crash with error "Error: Cannot initialize 'routeModules'. This normally occurs when you have server code in your client modules."

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hannad rehman
Solution 2 Hanna