redirect with supabase.auth.getUser() inside middleware.ts / with Next.js

22 Views Asked by At

I want to know if I can handle redirects in middleware.

The Superbase guide handles redirects inside page.tsx. https://supabase.com/docs/guides/auth/server-side/nextjs

When there are multiple pages, it will be a little bit messy. So I want to handle the redirects inside middleware (or somewhere else).

But, I couldn't find the resources inside official documents or tutorials. So It will be very helpful if you could tell me.

I am thinking to write inside middleware like this.

export async function middleware(request: NextRequest) {
  
  const { data } = await supabase.auth.getUser()

  // redirect to / page if the user is not logged in
  if (!data?.user && request.nextUrl.pathname.startsWith('/account')) {
    redirect('/')
  }

  return await updateSession(request)
}
0

There are 0 best solutions below