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.

FEAT: iOS Deferred Deep Linking

Steven Tey05a66ab69ac2
diff --git a/apps/web/app/(ee)/api/track/open/route.ts b/apps/web/app/(ee)/api/track/open/route.ts
index c67b279ece..2c454064a0 100644
--- a/apps/web/app/(ee)/api/track/open/route.ts
+++ b/apps/web/app/(ee)/api/track/open/route.ts
@@ -2,6 +2,8 @@ import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import { linkCache } from "@/lib/api/links/cache";
import { recordClickCache } from "@/lib/api/links/record-click-cache";
import { parseRequestBody } from "@/lib/api/utils";
+import { getIdentityHash } from "@/lib/middleware/utils";
+import { IdentityHashClicksData } from "@/lib/middleware/utils/cache-identity-hash-clicks";
import { getLinkViaEdge } from "@/lib/planetscale";
import { recordClick } from "@/lib/tinybird";
import { RedisLinkProps } from "@/lib/types";
@@ -19,24 +21,71 @@ const CORS_HEADERS = {
"Access-Control-Allow-Headers": "Content-Type, Authorization",
};
+const trackOpenRequestSchema = z
+ .object({
+ deepLink: parseUrlSchema.optional(),
+ dubDomain: z.string().optional(),
+ })
+ .superRefine((data, ctx) => {
+ if (!data.deepLink && !data.dubDomain) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message:
+ "You need to provide either `deepLink` or `dubDomain` for deferred deep linking.",
+ });
+ }
+ });
+
const trackOpenResponseSchema = z.object({
- clickId: z.string(),
- link: z.object({
- id: z.string(),
- domain: z.string(),
- key: z.string(),
- url: z.string(),
- }),
+ clickId: z.string().nullable(),
+ link: z
+ .object({
+ id: z.string(),
+ domain: z.string(),
+ key: z.string(),
+ url: z.string(),
+ })
+ .nullable(),
});
// POST /api/track/open – Track an open event for deep link
export const POST = withAxiom(async (req: AxiomRequest) => {
try {
- const { deepLink: deepLinkUrl } = z
- .object({
- deepLink: parseUrlSchema,
- })
- .parse(await parseRequestBody(req));
+ const { deepLink: deepLinkUrl, dubDomain } = trackOpenRequestSchema.parse(
+ await parseRequestBody(req),
+ );
+
+ if (!deepLinkUrl) {
+ const identityHash = await getIdentityHash(req);
+
+ // Get all iOS click cache keys for this identity hash
+ const [_, cacheKeys] = await redis.scan(0, {
+ match: `iosClickCache:${identityHash}*`,
+ count: 50,
+ });
+
+ const firstCacheKeyForDomain = cacheKeys.find((key) =>
+ key.startsWith(`iosClickCache:${identityHash}:${dubDomain}`),
+ );
+
+ if (firstCacheKeyForDomain) {
+ const cachedData = await redis.get<IdentityHashClicksData>(
+ firstCacheKeyForDomain,
+ );
+
+ if (cachedData) {
+ return NextResponse.json(trackOpenResponseSchema.parse(cachedData));
+ }
+ }
+
+ return NextResponse.json(
+ trackOpenResponseSchema.parse({
+ clickId: null,
+ link: null,
+ }),
+ { headers: CORS_HEADERS },
+ );
+ }
const deepLink = new URL(deepLinkUrl);
diff --git a/apps/web/lib/middleware/link.ts b/apps/web/lib/middleware/link.ts
index 8ac9c50d60..16d0842286 100644
--- a/apps/web/lib/middleware/link.ts
+++ b/apps/web/lib/middleware/link.ts
@@ -31,6 +31,7 @@ import { recordClickCache } from "../api/links/record-click-cache";
import { getLinkViaEdge } from "../planetscale";
import { getDomainViaEdge } from "../planetscale/get-domain-via-edge";
import { getPartnerAndDiscount } from "../planetscale/get-partner-discount";
+import { cacheIdentityHashClicks } from "./utils/cache-identity-hash-clicks";
import { crawlBitly } from "./utils/crawl-bitly";
import { isSingularTrackingUrl } from "./utils/is-singular-tracking-url";
import { resolveABTestURL } from "./utils/resolve-ab-test-url";
@@ -395,17 +396,31 @@ export default async function LinkMiddleware(
// redirect to iOS link if it is specified and the user is on an iOS device
} else if (ios && ua.os?.name === "iOS") {
ev.waitUntil(
- recordClick({
- req,
- clickId,
- linkId,
- domain,
- key,
- url: ios,
- webhookIds,
- workspaceId,
- shouldCacheClickId,
- }),
+ Promise.all([
+ recordClick({
+ req,
+ clickId,
+ linkId,
+ domain,
+ key,
+ url: ios,
+ webhookIds,
+ workspaceId,
+ shouldCacheClickId,
+ }),
+ // cache click if it's an iOS app store URL
+ ios.startsWith("https://apps.apple.com/") &&
+ cacheIdentityHashClicks({
+ req,
+ clickId,
+ link: {
+ id: linkId,
+ domain,
+ key,
+ url, // pass the main destination URL to the cache (for deferred deep linking)
+ },
+ }),
+ ]),
);
return createResponseWithCookies(
diff --git a/apps/web/lib/middleware/utils/cache-identity-hash-clicks.ts b/apps/web/lib/middleware/utils/cache-identity-hash-clicks.ts
new file mode 100644
index 0000000000..725fce414e
--- /dev/null
+++ b/apps/web/lib/middleware/utils/cache-identity-hash-clicks.ts
@@ -0,0 +1,29 @@
+import { redis } from "@/lib/upstash";
+import { getIdentityHash } from "./get-identity-hash";
+
+export type IdentityHashClicksData = {
+ clickId: string;
+ link: { id: string; domain: string; key: string; url: string };
+};
+
+export async function cacheIdentityHashClicks({
+ req,
+ clickId,
+ link,
+}: {
+ req: Request;
+ clickId: string;
+ link: { id: string; domain: string; key: string; url: string };
+}) {
+ const identityHash = await getIdentityHash(req);
+ return await redis.set<IdentityHashClicksData>(
+ `iosClickCache:${identityHash}:${link.domain}:${link.key}`,
+ {
+ clickId,
+ link,
+ },
+ {
+ ex: 60 * 60,
+ },
+ );
+}
diff --git a/apps/web/lib/tinybird/record-click.ts b/apps/web/lib/tinybird/record-click.ts
index ab9ae73e77..db1c34c990 100644
--- a/apps/web/lib/tinybird/record-click.ts
+++ b/apps/web/lib/tinybird/record-click.ts
@@ -118,13 +118,13 @@ export async function recordClick({
const referer = referrer || req.headers.get("referer");
- const identity_hash = await getIdentityHash(req);
+ const identityHash = await getIdentityHash(req);
const finalUrl = url ? getFinalUrlForRecordClick({ req, url }) : "";
const clickData = {
timestamp: timestamp || new Date(Date.now()).toISOString(),
- identity_hash,
+ identity_hash: identityHash,
click_id: clickId,
link_id: linkId,
url: finalUrl,