Skip to content

Commit 7ec7d7e

Browse files
refactor: 🛠️ Enhance authentication middleware to improve user redirection logic and prevent redirect loops
1 parent 3d3952a commit 7ec7d7e

File tree

1 file changed

+4
-32
lines changed

1 file changed

+4
-32
lines changed

utils/supabase/middleware.ts

+4-32
Original file line numberDiff line numberDiff line change
@@ -27,61 +27,33 @@ export async function updateSession(request: NextRequest) {
2727
}
2828
)
2929

30-
// Do not run code between createServerClient and
31-
// supabase.auth.getUser(). A simple mistake could make it very hard to debug
32-
// issues with users being randomly logged out.
33-
3430
// IMPORTANT: DO NOT REMOVE auth.getUser()
35-
3631
const {
3732
data: { user },
3833
} = await supabase.auth.getUser()
39-
// if (
40-
// !user &&
41-
// !request.nextUrl.pathname.startsWith('/login') &&
42-
// !request.nextUrl.pathname.startsWith('/auth')
43-
// ) {
44-
// // no user, potentially respond by redirecting the user to the login page
45-
// const url = request.nextUrl.clone()
46-
// url.pathname = '/login'
47-
// return NextResponse.redirect(url)
48-
// }
4934

35+
// Protected routes check - redirect to signin if not authenticated
5036
if (
5137
!user && (request.nextUrl.pathname.startsWith('/dashboard'))
5238
) {
53-
// no user, potentially respond by redirecting the user to the login page
5439
const url = request.nextUrl.clone()
5540
url.pathname = '/auth/signin'
5641
return NextResponse.redirect(url)
5742
}
5843

59-
60-
44+
// Redirect authenticated users away from auth pages
6145
if (
6246
user &&
6347
(request.nextUrl.pathname === '/' ||
6448
request.nextUrl.pathname.startsWith('/auth/signin') ||
6549
request.nextUrl.pathname.startsWith('/auth/signup'))
6650
) {
67-
// user exists and route is / or /auth/signin or /auth/signup, redirect to /dashboard
51+
// Add a cache-busting parameter to avoid redirect loops
6852
const url = request.nextUrl.clone()
6953
url.pathname = '/dashboard'
54+
url.searchParams.set('_ts', Date.now().toString())
7055
return NextResponse.redirect(url)
7156
}
7257

73-
// IMPORTANT: You *must* return the supabaseResponse object as it is.
74-
// If you're creating a new response object with NextResponse.next() make sure to:
75-
// 1. Pass the request in it, like so:
76-
// const myNewResponse = NextResponse.next({ request })
77-
// 2. Copy over the cookies, like so:
78-
// myNewResponse.cookies.setAll(supabaseResponse.cookies.getAll())
79-
// 3. Change the myNewResponse object to fit your needs, but avoid changing
80-
// the cookies!
81-
// 4. Finally:
82-
// return myNewResponse
83-
// If this is not done, you may be causing the browser and server to go out
84-
// of sync and terminate the user's session prematurely!
85-
8658
return supabaseResponse
8759
}

0 commit comments

Comments
 (0)