Skip to content

Commit 406c174

Browse files
committed
refactor: bot detection from user agent
1 parent 76b571d commit 406c174

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

src/functions/utils.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { isbot } from "isbot";
12
import { customAlphabet } from "nanoid";
23

34
export function isValidUrl(url: string): boolean {
@@ -35,3 +36,10 @@ export function getIPLocation(ip: any): Promise<{ city: string; regionName: stri
3536
return null;
3637
});
3738
}
39+
40+
export function isPotentialBot(userAgent: string | undefined): boolean {
41+
if (!userAgent || userAgent.startsWith("Bun/")) {
42+
return false;
43+
}
44+
return isbot(userAgent);
45+
}

src/index.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,12 @@ import { cors } from "@elysiajs/cors";
66
import { helmet } from "elysia-helmet";
77
import { ip } from "elysia-ip";
88
import { UAParser } from "ua-parser-js";
9-
import { getIPLocation } from "./functions/utils";
9+
import { getIPLocation, isPotentialBot } from "./functions/utils";
1010
import { insertRedirect } from "./functions/redirects";
1111
import { redirectsRoutes } from "./routes/redirects";
1212
import bearer from "@elysiajs/bearer";
1313
import { demoRoutes } from "./routes/demo";
1414
import { NOT_FOUND_PAGE, PERSONAL_WEBSITE } from "./utils/constants";
15-
import { isbot } from "isbot";
1615

1716
const app = new Elysia()
1817
.use(cors())
@@ -74,11 +73,12 @@ const app = new Elysia()
7473
// Save analytics data after redirection, for performance reasons
7574
async afterResponse({ params, ip, headers }) {
7675
const link = await getLink(params.code);
77-
if (!link || isbot(headers["user-agent"])) {
76+
const userAgent = headers["user-agent"];
77+
if (!link || isPotentialBot(userAgent)) {
7878
return;
7979
}
8080

81-
const parserResult = new UAParser(headers["user-agent"]).getResult();
81+
const parserResult = new UAParser(userAgent).getResult();
8282
const lang = headers["accept-language"]?.split(",")[0];
8383
const loc = await getIPLocation(ip);
8484
await insertRedirect({

0 commit comments

Comments
 (0)