forked from bluuweb/example-next-auth-v5
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
46 lines (36 loc) · 1.39 KB
/
middleware.ts
File metadata and controls
46 lines (36 loc) · 1.39 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
38
39
40
41
42
43
44
45
46
import NextAuth from "next-auth";
import { NextResponse } from "next/server";
import authConfig from "./auth.config";
const { auth } = NextAuth(authConfig);
const publicRoutes = ["/", "/prices"];
const authRoutes = ["/login", "/register"];
const apiAuthPrefix = "/api/auth";
export default auth((req) => {
const { nextUrl } = req;
const isLoggedIn = !!req.auth;
console.log({ isLoggedIn, path: nextUrl.pathname });
// Permitir todas las rutas de API de autenticación
if (nextUrl.pathname.startsWith(apiAuthPrefix)) {
return NextResponse.next();
}
// Permitir acceso a rutas públicas sin importar el estado de autenticación
if (publicRoutes.includes(nextUrl.pathname)) {
return NextResponse.next();
}
// Redirigir a /dashboard si el usuario está logueado y trata de acceder a rutas de autenticación
if (isLoggedIn && authRoutes.includes(nextUrl.pathname)) {
return NextResponse.redirect(new URL("/dashboard", nextUrl));
}
// Redirigir a /login si el usuario no está logueado y trata de acceder a una ruta protegida
if (
!isLoggedIn &&
!authRoutes.includes(nextUrl.pathname) &&
!publicRoutes.includes(nextUrl.pathname)
) {
return NextResponse.redirect(new URL("/login", nextUrl));
}
return NextResponse.next();
});
export const config = {
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};