@@ -2,13 +2,14 @@ import { NextRequest, NextResponse } from 'next/server';
22import { authCookies , accessCookieOptions , refreshCookieOptions } from './src/lib/authCookies' ;
33import { getBackendBaseUrl } from './src/lib/env' ;
44import { isJwtExpiringSoon } from './src/lib/jwt' ;
5+ import { createClient } from './utils/supabase/middleware' ;
56
67function isProtectedPath ( pathname : string ) : boolean {
78 return pathname === '/dashboard' || pathname . startsWith ( '/dashboard/' ) ;
89}
910
1011function isAuthPage ( pathname : string ) : boolean {
11- return pathname === '/login' || pathname === '/register' ;
12+ return pathname === '/login' || pathname === '/register' || pathname === '/supabase-test' ;
1213}
1314
1415function parseCookieValue ( setCookieHeader : string | null , cookieName : string ) : string | null {
@@ -84,12 +85,23 @@ export async function middleware(req: NextRequest) {
8485 const pathname = req . nextUrl . pathname ;
8586 const accessToken = req . cookies . get ( authCookies . accessToken ) ?. value ?? null ;
8687
88+ // 1. Handle Supabase session refreshing
89+ let res = NextResponse . next ( {
90+ request : {
91+ headers : req . headers ,
92+ } ,
93+ } ) ;
94+
95+ const supabase = createClient ( req , res ) ;
96+ // This refreshes the session if needed
97+ await supabase . auth . getUser ( ) ;
98+
8799 if ( isAuthPage ( pathname ) && accessToken ) {
88100 return NextResponse . redirect ( new URL ( '/dashboard' , req . url ) ) ;
89101 }
90102
91103 if ( ! isProtectedPath ( pathname ) ) {
92- return NextResponse . next ( ) ;
104+ return res ;
93105 }
94106
95107 if ( ! accessToken ) {
@@ -99,20 +111,19 @@ export async function middleware(req: NextRequest) {
99111 }
100112
101113 if ( ! isJwtExpiringSoon ( accessToken , 60_000 ) ) {
102- return NextResponse . next ( ) ;
114+ return res ;
103115 }
104116
105117 const refreshed = await tryRefreshTokens ( req ) ;
106118 if ( ! refreshed ) {
107- return NextResponse . next ( ) ;
119+ return res ;
108120 }
109121
110- const res = NextResponse . next ( ) ;
111122 res . cookies . set ( authCookies . accessToken , refreshed . accessToken , accessCookieOptions ) ;
112123 res . cookies . set ( authCookies . refreshToken , refreshed . refreshToken , refreshCookieOptions ) ;
113124 return res ;
114125}
115126
116127export const config = {
117- matcher : [ '/dashboard/:path*' , '/login' , '/register' ] ,
128+ matcher : [ '/dashboard/:path*' , '/login' , '/register' , '/supabase-test' ] ,
118129} ;
0 commit comments