Skip to content

Missing environment variable validation for Upstash Redis credentials #65

@jaffarkeikei

Description

@jaffarkeikei

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

  1. Silent failures: If env vars are missing, undefined! becomes undefined
  2. Late error detection: Redis client is created, but errors appear only when used
  3. Cryptic errors: Instead of "Missing UPSTASH_REDIS_REST_URL", users get Redis connection errors
  4. 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions