-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmiddleware.ts
44 lines (34 loc) · 1.13 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
import { NextRequest, NextResponse } from 'next/server'
import { kv } from "@vercel/kv"
export const config = {
matcher: '/:path*',
}
export async function middleware(req: NextRequest) {
const path = req.nextUrl.pathname.replace('/', '')
let endURL = await kv.get(path)
if (path) {
if (endURL) {
// if endURL missing http/https, add it
if (!endURL.match(/^[a-zA-Z]+:\/\//)) {
endURL = 'http://' + endURL
}
return NextResponse.redirect(new URL(endURL))
} else {
// Search for a secure key
let allKeys = []
for await (const key of kv.scanIterator()) {
allKeys.push(key)
}
let secureKey = allKeys.find((key) => key.startsWith(path))
if (secureKey) {
return NextResponse.redirect(new URL(req.nextUrl.toString().replace('/' + path, '') + '/unlock?key=' + path.split('$')[0]))
}
else if (path.includes('$')) {
return NextResponse.redirect(new URL(req.nextUrl.toString().replace('/' + path, '') + '/unlock?key=' + path.split('$')[0] ))
}
return NextResponse.next()
}
} else {
return NextResponse.next()
}
}