Search code examples
phpreactjslaravelhttp-redirectmiddleware

Redirecting From Middleware In Laravel Is Not Working As Expected


I am working on an react-laravel project and i am trying to protect the dashboard routes with a middleware, here is the code from the middleware

public function handle($request, Closure $next)
{
    $apiToken = $request->bearerToken();
    $isAuthenticated = User::where('api_token', $apiToken)
                            ->where('is_admin', true)
                            ->first();

    if(!$isAuthenticated) {
        return redirect('/');
    }

    return $next($request);
}

Now the problem is in case of the user is not authenticated the middleware does not redirect to the desired route, instead it returns the html page as text in the response as follows.Response in case of of not authenticated user

  <!DOCTYPE html>
  <html lang="en">
    <head>
        <meta charset="utf-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>
        <meta name="theme-color" content="#000000"/>
        <meta name="description" content="Web site created using create-react-app"/>
        <link rel="stylesheet" href="http://localhost/css/app.css">
        <title>Some Title Here</title>
    </head>
    <body>
        <noscript>You need to enable JavaScript to run this app.</noscript>
        <div id="root"></div>
        <script src="http://localhost/js/app.js"></script>
    </body>
  </html>

I've tried to use

return redirect()->route('/');

but sadly it doesn't work either.

I've also tried to throw 401 exception by using

abort(401)

And catch it in the exception handler and redirect from there (as i did so with the 404 and 500 exceptions and i was redirected successfully) but this does not work and i've got the same response message with the page sent as text in the response, so the problem is probably with redirecting from the middleware, can someone help me find the problem, please?


Solution

  • So as a front-end engineer i've chosen to make a short-cut solution and redirect the user using react and axios so in the middlewere i've just throw an httperror with status 401 (unauthorized) then caught it by axios as follows: My Middleware

        if(!$isAuthenticated) {
          return abort(401);
       }
    

    react

    const instance = axios.create({
        baseURL: API_PREFIX
    });
    
    instance.interceptors.response.use(
        response => {
            return response;
        },
        function(error) {
            if (error.response.status === 401) {
                window.location.replace("/");
            }
            return Promise.reject(error.response);
        }
    );
    

    Links that helped me: github