reactjstypescriptnext.jssupabasenext.js13

Redirecting to Origin URL with Next.js Route Not Working


I'm currently working on a Next.js application where I have a layout component inside the app directory. Within that component, I have a navbar client component. I'm attempting to implement a logout feature, where clicking a button on the navbar should redirect the user to the origin page using a server-side route. However, it isn't working as expected.

When I click the logout button, the server logs confirm that the route is being called, and I'm getting a "Status: 200 OK" response, but the redirect isn't happening.

Here's the code snippet for the route:

import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs';
import { cookies } from 'next/headers';
import { NextResponse } from 'next/server';

export const dynamic = 'force-dynamic';

export async function POST(request: Request) {
  const requestUrl = new URL(request.url);
  const supabase = createRouteHandlerClient({ cookies });

  await supabase.auth.signOut();
  console.log("Salir sesion ruta llamada");

  // Log the origin to the console
  console.log("Origin URL:", requestUrl.origin);

  return NextResponse.redirect(`${requestUrl.origin}/`, {
    // a 301 status is required to redirect from a POST to a GET route
    status: 301,
  });
}

I have already verified the origin URL, ensured the correct HTTP method, and checked for other common issues, but I'm still encountering this problem.

Has anyone encountered a similar issue, or does anyone have suggestions on what might be going wrong? Any help would be greatly appreciated! Thank you!


Solution

  • You have confused between redirects on browser vs server.

    When you add a redirect to an API like,

    return NextResponse.redirect(`api/b`, {
      status: 301,
    });
    

    What that means is, if try to fetch a response from api/a, it shall redirect and get the response from api/b (assuming follow-redirects option is set).

    What you actually want is a redirect on the browser side.


    You can accomplish this in Next.js using (assuming you are using app router):

    import { redirect } from 'next/navigation'
     
    export default async function Profile({ shouldRedirect }) {
      if (shouldRedirect) {
        redirect('/')
      }
     
      // ...
    }
    

    Refer to https://nextjs.org/docs/app/api-reference/functions/redirect for more details.