-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmiddleware.ts
More file actions
43 lines (37 loc) · 1.19 KB
/
middleware.ts
File metadata and controls
43 lines (37 loc) · 1.19 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { maintenanceMode } from "./utils/config";
export const middleware = (request: NextRequest) => {
// Maintenance mode
if (maintenanceMode) {
return new Response(
"This site is currently under maintenance. Please check back later.",
);
}
const response = NextResponse.next();
const existingUnboxerId = request.cookies.get("unboxerId");
let newUnboxerId: string = crypto.randomUUID();
// Check if the unboxerId is a valid UUID
// If it is, use it. Otherwise, use the newly generated UUID
if (existingUnboxerId) {
const isValidUUID =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
existingUnboxerId.value,
);
if (isValidUUID) newUnboxerId = existingUnboxerId.value;
}
// Refresh the unboxerId cookie
response.cookies.set(
"unboxerId",
// If the unboxerId is valid, use it. Otherwise, generate a new one
newUnboxerId,
{
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
httpOnly: true,
},
);
return response;
};
export const config = {
matcher: ["/", "/unboxed"],
};