fix: survive empty-string env vars from compose

Docker Compose passes undeclared variables as empty strings
(CRON_SECRET="" etc.), which crashed env validation while loading the
instrumentation hook. A throwing register() made Next.js answer every
route with 500 while the process stayed alive.

- parse optional CRON_SECRET / AUTO_RULE_SYNC_INTERVAL_SECONDS via
  plain preprocess helpers that map blank strings to unset (zod v4
  does not accept preprocess-produced undefined through .optional())
- guard instrumentation register() so scheduler failures can never
  break request handling
This commit is contained in:
Leon Tonhäuser committed 2026-08-25 01:16:13 +02:00
1 parent dd60fd6ee6
commit c6b69eb88d
3 files changed
+102 -7

No files matched your search

+23 -5
View File
@@ -21,15 +21,33 @@ const serverEnvSchema = z.object({
.default("https://leon-tonhaeuser.de/datenschutz"),
LEGAL_TERMS_URL: z.url().default("https://leon-tonhaeuser.de/agb"),
/** Bearer token for the /api/cron/album-sync endpoint; unset disables it. */
CRON_SECRET: emptyToUndefined(z.string().min(16)).optional(),
CRON_SECRET: optionalSecret(),
/** How often the album auto-rule sync runs, in seconds (min 30). */
AUTO_RULE_SYNC_INTERVAL_SECONDS: emptyToUndefined(z.coerce.number().int().min(30)).optional(),
AUTO_RULE_SYNC_INTERVAL_SECONDS: optionalIntervalSeconds(),
});
// Docker Compose passes undeclared vars as empty strings; treat those as
// unset so optional settings stay optional.
function emptyToUndefined<T extends z.ZodType>(schema: T) {
return z.preprocess((value) => (value === "" ? undefined : value), schema);
// unset so optional settings stay optional. Implemented with plain
// preprocess functions because wrapping z.preprocess(...).optional() does
// NOT accept the produced undefined in zod v4 (the inner schema still runs).
function emptyStringToUndefined(value: unknown): unknown {
return typeof value === "string" && value.trim() === "" ? undefined : value;
}
function optionalSecret() {
return z.preprocess(
emptyStringToUndefined,
z.string().min(16, "CRON_SECRET must be at least 16 characters").optional(),
);
}
function optionalIntervalSeconds() {
return z.preprocess((value) => {
const normalized = emptyStringToUndefined(value);
if (normalized === undefined) return undefined;
if (/^\d+$/.test(String(normalized))) return Number(normalized);
return normalized;
}, z.number().int().min(30, "AUTO_RULE_SYNC_INTERVAL_SECONDS must be >= 30").optional());
}
export type ServerEnv = z.infer<typeof serverEnvSchema>;