Skip to content

Full Toolkit for Next-Level Domain Analysis

Reject bot requests completely 🛡️

Felix Wotschofsky933d6d30c083
diff --git a/env.ts b/env.ts
index 582710e..afd1a75 100644
--- a/env.ts
+++ b/env.ts
@@ -2,6 +2,14 @@ import { createEnv } from '@t3-oss/env-nextjs';
import { vercel } from '@t3-oss/env-nextjs/presets';
import { z } from 'zod';
+const safeJSONParse = (input: string) => {
+ try {
+ return JSON.parse(input);
+ } catch {
+ return input;
+ }
+};
+
export const env = createEnv({
extends: [vercel],
server: {
@@ -12,6 +20,11 @@ export const env = createEnv({
UPSTASH_REDIS_REST_URL: z.string().url(),
UPSTASH_REDIS_REST_TOKEN: z.string().min(1),
+ ALLOWED_BOTS: z
+ .string()
+ .transform(safeJSONParse)
+ .pipe(z.array(z.string()))
+ .optional(),
GOOGLE_SERVICE_KEY_B64: z.string().optional(),
BIGQUERY_DATASET: z.string().optional(),
diff --git a/middleware.ts b/middleware.ts
index a9e62b9..a9733a2 100644
--- a/middleware.ts
+++ b/middleware.ts
@@ -1,8 +1,22 @@
import { type NextRequest, NextResponse } from 'next/server';
-import { applyRateLimit } from '@/lib/api';
+import { env } from '@/env';
+import { applyRateLimit, isUserBot } from '@/lib/api';
export const middleware = async (request: NextRequest) => {
+ if (env.ALLOWED_BOTS) {
+ const { isBot, userAgent } = isUserBot(request.headers);
+ if (isBot) {
+ const isAllowedBot =
+ !!userAgent &&
+ env.ALLOWED_BOTS.some((name) => userAgent.toLowerCase().includes(name));
+
+ if (!isAllowedBot) {
+ return new Response('Forbidden', { status: 403 });
+ }
+ }
+ }
+
const visitorIp = request.headers.get('x-forwarded-for') ?? '';
const identifier = ['lookup-page', visitorIp].join(':');
const isAllowed = await applyRateLimit(identifier, 10, '60s');