-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
70 lines (59 loc) · 1.65 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
61
62
63
64
65
66
67
68
69
70
import { authMiddleware } from '@clerk/nextjs'
import { get } from '@vercel/edge-config'
import { type NextRequest, NextResponse } from 'next/server'
import { kvKeys } from '~/config/kv'
import { env } from '~/env.mjs'
import countries from '~/lib/countries.json'
import { getIP } from '~/lib/ip'
import { redis } from '~/lib/redis'
export const config = {
matcher: ['/((?!_next|studio|.*\\..*).*)'],
}
async function beforeAuthMiddleware(req: NextRequest) {
const { geo, nextUrl } = req
const isApi = nextUrl.pathname.startsWith('/api/')
if (process.env.EDGE_CONFIG) {
const blockedIPs = await get<string[]>('blocked_ips')
const ip = getIP(req)
if (blockedIPs?.includes(ip)) {
if (isApi) {
return NextResponse.json(
{ error: 'You have been blocked.' },
{ status: 403 }
)
}
nextUrl.pathname = '/blocked'
return NextResponse.rewrite(nextUrl)
}
if (nextUrl.pathname === '/blocked') {
nextUrl.pathname = '/'
return NextResponse.redirect(nextUrl)
}
}
if (geo && !isApi && env.VERCEL_ENV === 'production') {
const country = geo.country
const city = geo.city
const countryInfo = countries.find((x) => x.cca2 === country)
if (countryInfo) {
const flag = countryInfo.flag
await redis.set(kvKeys.currentVisitor, { country, city, flag })
}
}
return NextResponse.next()
}
export default authMiddleware({
beforeAuth: beforeAuthMiddleware,
publicRoutes: [
'/',
'/studio(.*)',
'/api(.*)',
'/blog(.*)',
'/confirm(.*)',
'/projects',
'/guestbook',
'/newsletters(.*)',
'/about',
'/rss',
'/feed',
],
})