-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmiddleware.ts
60 lines (49 loc) · 1.8 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
56
57
58
59
60
import { CUSTOM_DOMAINS, HOSTS } from 'consts/middleware'
import { NextRequest, NextResponse } from 'next/server'
import { getBaseURL } from 'lib/utils'
async function middleware(request: NextRequest) {
// clone the request url
const url = request.nextUrl.clone()
// get pathname of request [/cool]
const { pathname } = request.nextUrl
// get host name [aleem.com]
const hostname = request.headers.get('host')
if (!hostname) return NextResponse.redirect('https://kytelink.com')
// get our base url [https://kytelink.com]
const BASE_URL = getBaseURL(hostname)
// if the domain is a customdomain, and it's root path, redirect to kytelink.com
if (CUSTOM_DOMAINS.includes(hostname) && pathname === '/') {
return NextResponse.redirect('https://kytelink.com')
}
// if the domain is a host, treat it as normal
if (
HOSTS.includes(hostname) ||
CUSTOM_DOMAINS.includes(hostname) ||
hostname?.includes('vercel.app') ||
hostname?.includes('ngrok')
) {
return NextResponse.next()
}
// some safety checks
const doNotRedirect = ['images/', 'favicon.png', 'fonts/', 'api/', '_next/']
if (doNotRedirect.some((directory) => pathname.startsWith(`/${directory}`))) {
console.log('not redirecting' + pathname)
return NextResponse.next()
}
// go fetch the which user this domain belongs to
try {
const fetchUser = await fetch(`${BASE_URL}/api/fetchdomain?domain=${hostname}`)
const user = await fetchUser.json()
if (!user.success || !user.username) {
console.log('no user found')
console.log(user)
return NextResponse.redirect('https://kytelink.com')
}
url.pathname = `/${user.username}`
return NextResponse.rewrite(url)
} catch (e) {
console.log(e)
throw new Error('Error fetching domain')
}
}
export default middleware