Next.js Discord

Discord Forum

Redirects in middleware.ts

Unanswered
Asiatic Lion posted this in #help-forum
Open in Discord
Asiatic LionOP
Hi,
Is someone experienced with middleware.ts as I have an issue with modifying the response. What I am trying to do is basically check for a session and if that session is not there the user should always get redirected to /signin.

import { createMiddlewareClient } from '@supabase/auth-helpers-nextjs'
import { NextResponse } from 'next/server'

import type { NextRequest } from 'next/server'
import type { Database } from '@/types_db'

export async function middleware(req: NextRequest) {
  const res = NextResponse.next()
  const supabase = createMiddlewareClient<Database>({ req, res })
  const activeSession = await supabase.auth.getSession()

  if (!activeSession.data.session) return NextResponse.redirect('http://localhost:3000/signin')

  return res
}

I tried using next/navigation redirect to redirec the user to the /signin page but this doesnt work. Tried couple of other methods and nothing worked.
Edit: Main problem is that using the above approach leads to "Err: Too many redirects" as the middleware is constantly "attacked"

4 Replies

Kirtland's Warbler
You must add exception for signin page
Because its also checking for signin page
When you redirect to signin page, it will always redirect to signin in loop
@Kirtland's Warbler You must add exception for signin page
Asiatic LionOP
Thanks
I added some regExp to get a work around for that