zod parse env vars

This commit is contained in:
2026-06-03 10:35:12 +02:00
parent 9bb2cf331f
commit 95973937f5
3 changed files with 67 additions and 4 deletions
+63
View File
@@ -0,0 +1,63 @@
import { z } from "zod";
const clientSchema = z.object({
VITE_API_BASE_URL: z.string("Invalid API Base URL format"),
});
const serverSchema = z.object({
DISCORD_CONTACT_WEBHOOK: z.string("Invalid Discord Contact Webhook URL"),
DISCORD_ERROR_LOG_WEBHOOK: z.string("Invalid Discord Error Log Webhook URL"),
LICHESS_CLIENT_ID: z.string("Invalid Lichess Client ID"),
});
const fullSchema = z.object({
...clientSchema.shape,
...serverSchema.shape,
});
const isServer = typeof window === "undefined";
const rawEnv = isServer ? process.env : import.meta.env;
const getEnv = () => {
if (isServer) {
const _env = fullSchema.safeParse(rawEnv);
if (!_env.success) {
console.error("❌ Invalid Server Environment Variables:");
throw new Error("Invalid environment variables");
}
return _env.data;
} else {
const _env = clientSchema.safeParse(rawEnv);
if (!_env.success) {
console.error("❌ Invalid Client Environment Variables:");
throw new Error("Invalid environment variables");
}
return _env.data as z.infer<typeof fullSchema>;
}
};
export const env = getEnv();
//
// const isServer = typeof window === "undefined";
// const rawEnv = isServer ? process.env : import.meta.env;
//
// let parsedEnv: z.infer<typeof fullSchema>;
//
// if (isServer) {
// const _env = fullSchema.safeParse(rawEnv);
// if (!_env.success) {
// console.error("❌ Invalid Server Environment Variables:");
// throw new Error("Invalid environment variables");
// }
// parsedEnv = _env.data;
// } else {
// const _env = clientSchema.safeParse(rawEnv);
// if (!_env.success) {
// console.error("❌ Invalid Client Environment Variables:");
// throw new Error("Invalid environment variables");
// }
// parsedEnv = _env.data as z.infer<typeof fullSchema>;
// }
//
// export const env = parsedEnv;
+2 -1
View File
@@ -6,6 +6,7 @@ import {
useState,
} from "react";
import { toast } from "react-toastify";
import { env } from "#/env.ts";
import type { IHeader, IPosition } from "#/interfaces.ts";
import { gameReducer, initialGameState } from "#/reducers/gameReducer.ts";
import { downloadPDF } from "#/utils/pdfUtils.ts";
@@ -48,7 +49,7 @@ export const useChessGame = () => {
const { diagrams, diagramClock } = gameState;
const pgnString = buildPgnString(gameState);
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;
const apiBaseUrl = env.VITE_API_BASE_URL;
const response = await fetch(`${apiBaseUrl}/pdf`, {
method: "POST",