-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
73 lines (57 loc) · 2.09 KB
/
Copy pathmiddleware.ts
File metadata and controls
73 lines (57 loc) · 2.09 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { Redis } from "@upstash/redis";
import { NextFetchEvent, NextRequest, NextResponse } from "next/server";
import { auth0 } from "./lib/auth0";
const redis = Redis.fromEnv();
async function handleShortlink(request: NextRequest, authRes: NextResponse) {
try {
const slug = request.nextUrl.pathname.slice(1);
// get destination URL data, if the slug is a valid shortlink
const result: string | null = await redis.hget(slug, "destinationUrl");
if (!result) throw new Error("Key not found or destinationUrl not set");
// increment visit counter
await redis.hincrby(slug, "visits", 1);
return NextResponse.redirect(new URL(result), {
status: 302,
});
} catch (error) {
console.error("Error fetching shortlink:", error?.message);
return authRes;
}
}
// Main middleware function
export async function middleware(request: NextRequest, event: NextFetchEvent) {
let authRes = await auth0.middleware(request);
// Ensure own middleware does not handle the `/auth` routes, auto-mounted and handled by the Auth0 SDK
if (request.nextUrl.pathname.startsWith("/auth")) {
return authRes;
}
// Allow access to public routes without requiring a session
if (request.nextUrl.pathname === "/") {
return authRes;
}
const { origin } = new URL(request.url);
const { pathname } = request.nextUrl;
// Handle protected routes
if (pathname.startsWith("/links")) {
const session = await auth0.getSession(request);
// If the user does not have a session, redirect to login
if (!session) {
return NextResponse.redirect(`${origin}/auth/login`);
}
// If a valid session exists, continue with the response from Auth0 middleware
return authRes;
}
// Skip shortlink handling for system paths
if (pathname.startsWith("/api/")) {
return authRes;
}
// Handle shortlink redirects for all other paths
return handleShortlink(request, authRes);
}
// Configure paths that trigger the middleware
export const config = {
matcher: [
// Match paths except static files
"/((?!_next/static|_next/image|favicon.ico).*)",
],
};