-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathmiddleware.ts
39 lines (33 loc) · 1.18 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
import {islinkExpanderBot} from './utils/link_preview_util';
function isAsset(url) {
return /\.(png|jpe?g|gif|css|js|svg|ico|map|json)$/i.test(url.pathname);
}
function isPlayUrl(url) {
const split = url.pathname.split('/');
return split.length >= 3 && split[2] === 'play';
}
function isGameUrl(url) {
const split = url.pathname.split('/');
return split.length >= 3 && split[2] === 'game';
}
export default function middleware(req: Request) {
const url = new URL(req.url);
if (
isAsset(url) ||
(!isPlayUrl(url) && !isGameUrl(url)) ||
!islinkExpanderBot(req.headers.get('user-agent') as string)
) {
return new Response(null, {
headers: {'x-middleware-next': '1'},
});
}
console.log('crawler detected', req.headers.get('user-agent'));
console.log(`returning link preview from https://api.foracross.com/api/link_preview?url=${url}`);
// crawled by link expander bot, so redirect to link preview endpoint for this game URL
return new Response(null, {
status: 307,
headers: {
Location: `https://api.foracross.com/api/link_preview?url=${url}`, // vercel middleware can't really be tested in dev so just hardcoding to prod endpoint
},
});
}