perf: cache custom domain CORS origin lookups

Avoid hitting the database on every cross-origin request by caching
published custom domain checks for five minutes.
This commit is contained in:
Ian Troisi committed 2026-06-11 13:15:02 -04:00
1 parent 6a1ab622b3
commit 120708ed47
2 files changed
+81 -1

No files matched your search

@@ -2,7 +2,16 @@ import type { CorsOptions } from "cors";
import type { IStatusPagesRepository } from "@/domain/status-pages/status-page-repository.interface.js";
import { normalizeStatusPageDomain } from "@/utils/statusPageDomain.js";
const CUSTOM_DOMAIN_CORS_CACHE_TTL_MS = 5 * 60 * 1000;
type CustomDomainCorsCacheEntry = {
allowed: boolean;
expiresAt: number;
};
export const createStatusPageCorsOrigin = (clientHost: string, statusPagesRepository: IStatusPagesRepository): CorsOptions["origin"] => {
const cache = new Map<string, CustomDomainCorsCacheEntry>();
return (origin, callback) => {
if (!origin) {
callback(null, true);
@@ -27,10 +36,21 @@ export const createStatusPageCorsOrigin = (clientHost: string, statusPagesReposi
return;
}
const cached = cache.get(customDomain);
if (cached && cached.expiresAt > Date.now()) {
callback(null, cached.allowed ? origin : false);
return;
}
statusPagesRepository
.findByCustomDomain(customDomain)
.then((statusPage) => {
callback(null, statusPage.isPublished ? origin : false);
const allowed = statusPage.isPublished;
cache.set(customDomain, {
allowed,
expiresAt: Date.now() + CUSTOM_DOMAIN_CORS_CACHE_TTL_MS,
});
callback(null, allowed ? origin : false);
})
.catch(() => {
callback(null, false);