-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.node.ts
67 lines (54 loc) · 1.84 KB
/
middleware.node.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
56
57
58
59
60
61
62
63
64
65
66
67
import { redirect } from "next/navigation";
import { NextRequest, NextResponse } from "next/server";
import { sleep } from "./lib/utils/common";
import { validateCookieSessionKey } from "./lib/utils/server";
import { cookies } from "next/headers";
function extractSlugs(urlPath: string): string[] {
return urlPath.split("/").filter((slug) => slug.length > 0);
}
const slug = process.env.NODE_ENV === "development" ? "dev" : "prod";
const siteUrl = "https://localhost:3000";
export default async function middleware(request: NextRequest) {
const response = NextResponse.next();
if (request.nextUrl.pathname.includes("/_next")) {
return response;
}
if (request.nextUrl.pathname.includes(".png")) {
return response;
}
if (request.nextUrl.pathname.includes(".ico")) {
return response;
}
if (request.nextUrl.pathname.startsWith("/test")) {
return response;
}
console.log("middleware", request.url);
const cookieStore = cookies();
const key = cookieStore.get("SESSION_KEY");
if (!validateCookieSessionKey(key)) {
const url = new URL(request.url);
console.log("user not logged in", `${url}`);
// return NextResponse.redirect(`${siteUrl}/test`);
}
// superceded by route segment cache constants
// response.headers.set(
// "Cache-Control",
// "public, max-age=10, stale-while-revalidate=1"
// );
// an example of setting headers on all routes
// response.headers.set(
// "Custom-header",
// "custom header return for all routes" +
// extractSlugs(request.nextUrl.pathname)[1]
// );
// example of conditional headers
if (request.nextUrl.pathname.startsWith("/cache/suspense")) {
response.headers.set(
"Suspense-header",
"returned only for the cache/suspense route" +
extractSlugs(request.nextUrl.pathname)[1]
);
return response;
}
return response;
}