-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
69 lines (57 loc) · 1.62 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
import { type NextRequest, NextResponse } from 'next/server';
import countries from '@/constants/countries.json';
import { kvKeys } from './constants/kv';
import { redis } from './libs/upstash';
import { checkIPIsBlocked } from './actions/ip';
import { ENV } from './constants/env';
import { updateSession } from './libs/supabase/middleware';
const publicRoutes = [
'/',
'/api(.*)',
'/blog(.*)',
'/confirm(.*)',
'/projects',
'/guestbook',
'/newsletters(.*)',
'/about',
'/rss',
'/feed',
'/ama',
];
export const config = {
// matcher: ['/((?!_next|studio|.*\\..*).*)'],
matcher: [
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
],
};
const middleware = async (req: NextRequest) => {
const { geo, nextUrl } = req;
const isApi = nextUrl.pathname.startsWith('/api/');
const isBlocked = await checkIPIsBlocked(req);
if (isBlocked) {
if (isApi) {
return NextResponse.json(
{ error: 'You have been blocked.' },
{ status: 403 },
);
}
nextUrl.pathname = '/blocked';
return NextResponse.rewrite(nextUrl);
}
if (nextUrl.pathname === '/blocked' && ENV.isProd) {
nextUrl.pathname = '/';
return NextResponse.redirect(nextUrl);
}
if (geo && !isApi && ENV.isProd) {
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 });
}
}
// await updateSession(req);
return NextResponse.next();
};
export default middleware;