-
Notifications
You must be signed in to change notification settings - Fork 409
Open
Description
Description
Found in packages/kv/src/index.ts: Required environment variables for Upstash Redis are accessed using non-null assertions without validation, leading to cryptic runtime errors if they're missing.
Current Code
import { Redis } from "@upstash/redis";
export const client = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL!, // ⚠️ No validation
token: process.env.UPSTASH_REDIS_REST_TOKEN!, // ⚠️ No validation
});Problem
- Silent failures: If env vars are missing,
undefined!becomesundefined - Late error detection: Redis client is created, but errors appear only when used
- Cryptic errors: Instead of "Missing UPSTASH_REDIS_REST_URL", users get Redis connection errors
- Poor DX: Hard to diagnose for new developers setting up the project
Example Error
Without env vars, users might see:
Error: fetch failed
at https://undefined/...
Instead of a clear message like:
Error: Required environment variable UPSTASH_REDIS_REST_URL is not set
Recommended Fix
Add validation before creating the Redis client:
import "server-only";
import { Redis } from "@upstash/redis";
const UPSTASH_URL = process.env.UPSTASH_REDIS_REST_URL;
const UPSTASH_TOKEN = process.env.UPSTASH_REDIS_REST_TOKEN;
if (!UPSTASH_URL) {
throw new Error(
"Missing required environment variable: UPSTASH_REDIS_REST_URL. " +
"Please set it in your .env file. See .env.example for reference."
);
}
if (!UPSTASH_TOKEN) {
throw new Error(
"Missing required environment variable: UPSTASH_REDIS_REST_TOKEN. " +
"Please set it in your .env file. See .env.example for reference."
);
}
export const client = new Redis({
url: UPSTASH_URL,
token: UPSTASH_TOKEN,
});Alternative: Use Zod for env validation
Even better, add to your env validation schema (if you have one):
import { z } from "zod";
const envSchema = z.object({
UPSTASH_REDIS_REST_URL: z.string().url(),
UPSTASH_REDIS_REST_TOKEN: z.string().min(1),
// ... other vars
});
const env = envSchema.parse(process.env);
export const client = new Redis({
url: env.UPSTASH_REDIS_REST_URL,
token: env.UPSTASH_REDIS_REST_TOKEN,
});Impact
- Severity: Medium
- Affects developers during initial setup
- Makes debugging harder than it needs to be
- Violates fail-fast principle
Location
packages/kv/src/index.ts, lines 5-8
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels