-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
37 lines (31 loc) · 1.07 KB
/
Copy pathmiddleware.ts
File metadata and controls
37 lines (31 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// middleware.ts
import NextAuth from "next-auth";
import { authConfig } from "@/auth.config";
import { NextResponse } from "next/server";
const { auth } = NextAuth(authConfig);
export default auth((req) => {
const { pathname } = req.nextUrl;
const isLoggedIn = !!req.auth;
// Public routes
if (pathname === "/" || pathname.startsWith("/login") || pathname.startsWith("/signup") || pathname.startsWith("/api/auth") || pathname.startsWith("/api/signup")) {
if (isLoggedIn && pathname.startsWith("/login")) {
return NextResponse.redirect(new URL("/dashboard", req.url));
}
return NextResponse.next();
}
// All other routes require login
if (!isLoggedIn) {
const loginUrl = new URL("/login", req.url);
const safe = pathname.startsWith("/") && !pathname.startsWith("//")
? pathname
: "/dashboard";
loginUrl.searchParams.set("callbackUrl", safe);
return NextResponse.redirect(loginUrl);
}
return NextResponse.next();
});
export const config = {
matcher: [
"/((?!_next/static|_next/image|favicon.ico|.*\\.png$).*)",
],
};