@@ -2,29 +2,28 @@ import { cookies } from "next/headers";
2
2
import { NextResponse } from "next/server" ;
3
3
import { NextRequest } from "next/server" ;
4
4
5
- function isNoSession ( request : NextRequest ) : boolean {
6
- return (
7
- request . nextUrl . pathname . startsWith ( "/auth" ) && cookies ( ) . has ( "session" )
8
- ) ;
9
- }
5
+ const protectedRoutes = [ "/questions/*" , "/user/*" ] ;
6
+ const publicRoutes = [ "/" , "/auth/login/" , "/auth/register" ] ;
10
7
11
- function isSession ( request : NextRequest ) : boolean {
12
- return (
13
- ! request . nextUrl . pathname . startsWith ( "/auth" ) && ! cookies ( ) . has ( "session" )
14
- ) ;
15
- }
8
+ const isValidSession = ( ) => {
9
+ return cookies ( ) . has ( "session" ) ;
10
+ } ;
16
11
17
12
export function middleware ( request : NextRequest ) {
18
- // UNCOMMENT AND ADD TO ENV IF JUST TESTING FRONTEND STUFF
19
- if ( process . env . NEXT_BYPASS_LOGIN === "yesplease" ) {
13
+ const path = request . nextUrl . pathname ;
14
+ const isProtectedRoute = protectedRoutes . includes ( path ) ;
15
+ const isPublicRoute = publicRoutes . includes ( path ) ;
16
+
17
+ if ( isPublicRoute ) {
20
18
return NextResponse . next ( ) ;
21
19
}
22
20
23
- if ( isNoSession ( request ) ) {
24
- return NextResponse . redirect ( new URL ( "/questions" , request . url ) ) ;
21
+ // UNCOMMENT AND ADD TO ENV IF JUST TESTING FRONTEND STUFF
22
+ if ( process . env . NEXT_BYPASS_LOGIN === "yesplease" ) {
23
+ return NextResponse . next ( ) ;
25
24
}
26
25
27
- if ( isSession ( request ) ) {
26
+ if ( ! isValidSession ( ) && isProtectedRoute ) {
28
27
return NextResponse . redirect ( new URL ( "/auth/login" , request . url ) ) ;
29
28
}
30
29
}
@@ -39,6 +38,6 @@ export const config = {
39
38
* - _next/image (image optimization files)
40
39
* - favicon.ico, sitemap.xml, robots.txt (metadata files)
41
40
*/
42
- "/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)" ,
41
+ "/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt|.*\\.png$ ).*)" ,
43
42
] ,
44
43
} ;
0 commit comments