From 095bf7ceb3d826c2ebbb12039033dd8e6d838d45 Mon Sep 17 00:00:00 2001 From: Jared Pereira Date: Wed, 25 Mar 2026 13:27:12 -0700 Subject: [PATCH] update middleware route cache --- middleware.ts | 50 ++++++++++++++++++++++++++++++-------------------- 1 file changed, 30 insertions(+), 20 deletions(-) diff --git a/middleware.ts b/middleware.ts index 5181b052..27b6e977 100644 --- a/middleware.ts +++ b/middleware.ts @@ -1,5 +1,6 @@ import { AtUri } from "@atproto/syntax"; import { createClient } from "@supabase/supabase-js"; +import { getCache } from "@vercel/functions"; import { NextRequest, NextResponse } from "next/server"; import { Database } from "supabase/database.types"; @@ -19,21 +20,22 @@ export const config = { let supabase = createClient( process.env.NEXT_PUBLIC_SUPABASE_API_URL as string, process.env.SUPABASE_SERVICE_ROLE_KEY as string, - { - global: { - fetch: async (...args) => { - const response = await fetch(args[0], { - ...args[1], - next: { - revalidate: 60, - }, - }); - return response; - }, - }, - }, ); +const cache = getCache(); + +async function getDomainRoutes(hostname: string) { + let { data } = await supabase + .from("custom_domains") + .select( + "*, custom_domain_routes(*), publication_domains(*, publications(*))", + ) + .eq("domain", hostname) + .single(); + return data; +} +type DomainRoutes = Awaited>; + const auth_callback_route = "/auth_callback"; const receive_auth_callback_route = "/receive_auth_callback"; export default async function middleware(req: NextRequest) { @@ -44,13 +46,21 @@ export default async function middleware(req: NextRequest) { if (hostname === "leaflet.pub") return; if (req.nextUrl.pathname === "/not-found") return; - let { data: routes } = await supabase - .from("custom_domains") - .select( - "*, custom_domain_routes(*), publication_domains(*, publications(*))", - ) - .eq("domain", hostname) - .single(); + let routes: DomainRoutes = null; + try { + routes = (await cache.get(`domain:${hostname}`)) as DomainRoutes; + } catch {} + if (!routes) { + routes = await getDomainRoutes(hostname); + if (routes) { + try { + await cache.set(`domain:${hostname}`, routes, { + ttl: 60, + tags: [`domain:${hostname}`], + }); + } catch {} + } + } let pub = routes?.publication_domains[0]?.publications; if (pub) { -- 2.51.2