-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
55 lines (48 loc) · 1.48 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
51
52
53
54
55
import { NextRequest, NextResponse } from "next/server";
import { authMiddleware, redirectToHome, redirectToLogin } from "next-firebase-auth-edge";
import { clientConfig, serverConfig } from "./config";
const PUBLIC_PATHS = ['/register', '/login'];
export async function middleware(request: NextRequest) {
return authMiddleware(request, {
loginPath: "/api/login",
logoutPath: "/api/logout",
apiKey: clientConfig.apiKey,
cookieName: serverConfig.cookieName,
cookieSignatureKeys: serverConfig.cookieSignatureKeys,
cookieSerializeOptions: serverConfig.cookieSerializeOptions,
serviceAccount: serverConfig.serviceAccount,
handleValidToken: async () => {
if (PUBLIC_PATHS.includes(request.nextUrl.pathname)) {
return redirectToHome(request);
}
// Create a new NextResponse and clone the headers from the request
const response = NextResponse.next();
request.headers.forEach((value, key) => {
response.headers.set(key, value);
});
return response;
},
handleInvalidToken: async (reason) => {
console.info('Missing or malformed credentials', { reason });
return redirectToLogin(request, {
path: '/login',
publicPaths: PUBLIC_PATHS
});
},
handleError: async (error) => {
console.error('Unhandled authentication error', { error });
return redirectToLogin(request, {
path: '/login',
publicPaths: PUBLIC_PATHS
});
}
});
}
export const config = {
matcher: [
"/",
"/((?!_next|api|.*\\.).*)",
"/api/login",
"/api/logout",
],
};