Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

cache x-frame-options in redis

Steven Teyc251040e38b8
diff --git a/lib/middleware/link.ts b/lib/middleware/link.ts
index 14da803025..1738941401 100644
--- a/lib/middleware/link.ts
+++ b/lib/middleware/link.ts
@@ -4,7 +4,12 @@ import {
NextResponse,
userAgent,
} from "next/server";
-import { detectBot, getFinalUrl, parse } from "#/lib/middleware/utils";
+import {
+ detectBot,
+ getFinalUrl,
+ hasXFrameOptions,
+ parse,
+} from "#/lib/middleware/utils";
import { ratelimit, redis } from "#/lib/upstash";
import { recordClick } from "#/lib/tinybird";
import { DUB_HEADERS, LOCALHOST_GEO_DATA, LOCALHOST_IP } from "../constants";
@@ -92,12 +97,7 @@ export default async function LinkMiddleware(
// rewrite to target URL if link cloaking is enabled
if (rewrite) {
// check if there's a `X-Frame-Options` header
- const res = await fetch(decodeURIComponent(target), {
- headers: {
- "User-Agent": "dub-bot/1.0",
- },
- });
- const xFrameOptions = res.headers.get("X-Frame-Options");
+ const xFrameOptions = await hasXFrameOptions(decodeURIComponent(target));
if (xFrameOptions) {
// if there is, use Next.js rewrite instead of iframe
return NextResponse.rewrite(decodeURIComponent(target), DUB_HEADERS);
diff --git a/lib/middleware/utils.ts b/lib/middleware/utils.ts
index 8169bd9ebe..89b6caf404 100644
--- a/lib/middleware/utils.ts
+++ b/lib/middleware/utils.ts
@@ -1,4 +1,5 @@
import { NextRequest } from "next/server";
+import { redis } from "#/lib/upstash";
export const parse = (req: NextRequest) => {
let domain = req.headers.get("host") as string;
@@ -60,3 +61,24 @@ export const detectBot = (req: NextRequest) => {
}
return false;
};
+
+// check if a URL has a `X-Frame-Options` header (and caches it in Redis)
+export const hasXFrameOptions = async (url: string) => {
+ const cachedResults = await redis.get(`x-frame-options:${url}`);
+ if (cachedResults) {
+ return cachedResults === "yes";
+ }
+
+ const res = await fetch(url, {
+ headers: {
+ "User-Agent": "dub-bot/1.0",
+ },
+ });
+ const xFrameOptions = res.headers.get("X-Frame-Options"); // returns null if there is no `X-Frame-Options` header
+ // cache for 1 month
+ await redis.set(`x-frame-options:${url}`, xFrameOptions ? "yes" : "no", {
+ ex: 60 * 60 * 24 * 30,
+ });
+
+ return xFrameOptions;
+};