-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
50 lines (45 loc) · 1.4 KB
/
middleware.ts
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
47
48
49
50
import NextAuth from "next-auth";
import authConfig from "./auth.config";
import {
API_AUTH_PREFIX,
AUTH_ROUTES,
DEFAULT_LOGIN_REDIRECTED,
PUBLIC_ROUTES,
} from "@/routes";
import { NextResponse } from "next/server";
const { auth } = NextAuth(authConfig);
export default auth((req) => {
// req.auth
const { nextUrl } = req;
const isLogedIn = !!req.auth;
const isPublicRoute = PUBLIC_ROUTES.includes(nextUrl.pathname!);
const isAuthRoute = AUTH_ROUTES.includes(nextUrl.pathname);
const isApiAuthRoute = nextUrl.pathname.startsWith(API_AUTH_PREFIX);
// if it is api route
if (isApiAuthRoute) {
if (nextUrl.search.includes("error"))
return NextResponse.redirect(new URL(`/login${nextUrl.search}`, nextUrl));
return;
}
// check if it is auth routes
// console.log({ isLogedIn, isProtectedRoute });
if (isAuthRoute) {
if (isLogedIn) {
return NextResponse.redirect(new URL(DEFAULT_LOGIN_REDIRECTED, nextUrl));
}
return;
}
// if it is protected route
if (!isPublicRoute && !isLogedIn) {
let callbackurl = nextUrl.pathname;
if (nextUrl.search) callbackurl += nextUrl.search;
const encodedCallbackUrl = encodeURIComponent(callbackurl);
return NextResponse.redirect(
new URL(`/login?callbackurl=${encodedCallbackUrl}`, nextUrl)
);
}
return;
});
export const config = {
matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/", "/(api|trpc)(.*)"],
};