<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hrushi Borhade on Medium]]></title>
        <description><![CDATA[Stories by Hrushi Borhade on Medium]]></description>
        <link>https://medium.com/@hrushiborhade123?source=rss-a6e9668eb4ea------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2AN9KyHMmzgJBbfJyxPYQQ.jpeg</url>
            <title>Stories by Hrushi Borhade on Medium</title>
            <link>https://medium.com/@hrushiborhade123?source=rss-a6e9668eb4ea------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 15:09:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hrushiborhade123/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Type-Safe Env Variables: Because Debugging Production at 3 AM is Not the Vibe✨]]></title>
            <link>https://medium.com/@hrushiborhade123/type-safe-env-variables-because-debugging-production-at-3-am-is-not-the-vibe-409564af7a4c?source=rss-a6e9668eb4ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/409564af7a4c</guid>
            <category><![CDATA[environment]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[production]]></category>
            <category><![CDATA[webdev]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Hrushi Borhade]]></dc:creator>
            <pubDate>Sun, 18 May 2025 16:17:05 GMT</pubDate>
            <atom:updated>2025-05-18T16:24:31.524Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gP2BYQQJOxpQ4ujD0k0iMQ.png" /></figure><p>The way I see it, there are two types of developers in this world: those traumatised by env variable disasters and those who haven’t seen the monster yet. Picture this: It’s 3AM, you’re in bed scrolling Instagram Reels, when your phone lights up with “@channel production is down”. Your stomach drops faster than your dating standards after six months on the apps. Today’s TED talk is all about <strong>type-safe environment variables</strong>, the unsung hero of stable deployments. let me introduce you to your new emotional support developer tool.</p><h3>The Struggle is Real: Environment Variable Problems in Production</h3><p>Let’s keep it a stack — we’ve all been there. It’s Friday at 4:55 PM, and you’re about to deploy that shiny new feature that’ll definitely get you that promotion. You push to main (yolo, right?), and suddenly your Slack is blowing up:</p><pre>@channel PRODUCTION IS DOWN!! WHO PUSHED LAST??</pre><p>And it turns out your app is serving 500s because you used process.env.DATABSE_URL (yes, with that typo) instead of DATABASE_URL. No cap.</p><h3>Basic Env Validation: The Mid Approach</h3><p>The most basic approach to validating environment variables is something like this:</p><pre>import { z } from &quot;zod&quot;;<br>// Simple validation and type-safety<br>const simpleEnv = z.object({<br>  DATABASE_URL: z.string().url().min(1),<br>  NEXT_PUBLIC_SUPABASE_URL: z.string().url().min(1),<br>  NEXT_PUBLIC_SUPABASE_ANON_KEY: z.string().min(1),<br>  OPENAI_API_KEY: z.string().min(1),<br>  ANTHROPIC_API_KEY: z.string().min(1),<br>  EXA_API_KEY: z.string().min(1),<br>});<br>simpleEnv.parse(process.env);<br>declare global {<br>  namespace NodeJS {<br>    interface ProcessEnv extends z.infer&lt;typeof simpleEnv&gt; {}<br>  }<br>}</pre><p>This gives you some type checking, which is better than raw dogging your environment variables. Your IDE will give you autocomplete, and TypeScript will yell at you if you try to access a non-existent variable.</p><p>But it’s giving “I tried” energy. Let me explain why this is just not it, chief.</p><h3>Why the Basic Approach is Cheugy</h3><p>The simple validation approach has several problems that’ll have you crying in the club:</p><ol><li><strong>No runtime validation at build time</strong> — Your app will compile just fine, then fail spectacularly when it runs.</li><li><strong>No default values</strong> — Want to set reasonable defaults? Sorry, not with this approach.</li><li><strong>No transforms</strong> — What if you need that port string as a number? The types will lie to you faster than that situationship saying they’re “just busy with work.”</li><li><strong>Environment separation issues</strong> — Next.js has different environments (server/client), and this approach doesn’t respect the boundaries.</li><li><strong>Framework-specific quirks</strong> — Next.js only includes env vars you explicitly reference, which breaks validation.</li></ol><p>Trying to use this approach in production is like showing up to a party wearing Crocs with socks — technically functional, but everyone’s judging you.</p><h3>The Main Character Energy: T3-OSS/Env</h3><p>Enter <a href="https://env.t3.gg/">@t3-oss/env-nextjs</a> – the moment environmental variables got their glow-up. It was built by the <a href="https://create.t3.gg/">create-t3-app</a> team who were tired of dealing with the same problems over and over.</p><p>Let’s get into it:</p><pre>pnpm add @t3-oss/env-nextjs zod</pre><p>Now, let’s create our schema in src/env.ts:</p><pre>import { createEnv } from &quot;@t3-oss/env-nextjs&quot;;<br>import { z } from &quot;zod&quot;;<br><br>export const env = createEnv({<br>  server: {<br>    DATABASE_URL: z.string().url(),<br>    OPENAI_API_KEY: z.string().min(1),<br>    ANTHROPIC_API_KEY: z.string().min(1),<br>  },<br>  client: {<br>    NEXT_PUBLIC_SUPABASE_URL: z.string().url(),<br>    NEXT_PUBLIC_SUPABASE_ANON_KEY: z.string().min(1),<br>  },<br>  runtimeEnv: {<br>    DATABASE_URL: process.env.DATABASE_URL,<br>    OPENAI_API_KEY: process.env.OPENAI_API_KEY,<br>    ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY,<br>    NEXT_PUBLIC_SUPABASE_URL: process.env.NEXT_PUBLIC_SUPABASE_URL,<br>    NEXT_PUBLIC_SUPABASE_ANON_KEY: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,<br>  },<br>});</pre><h3>Real Talk: Why This Slaps</h3><h3>1. No More “Server Variable in Client” Nightmares</h3><p>You know that moment when you accidentally use a server variable on the client, and now your API keys are exposed like your friend’s DMs on screen share? T3-Env says “not today”:</p><pre>// In a client component<br>import { env } from &quot;~/env&quot;;<br>console.log(env.OPENAI_API_KEY); // 🚨 ERROR: Attempted to access server-side environment variable on the client<br>console.log(env.NEXT_PUBLIC_SUPABASE_URL); // ✅ This works fine</pre><p>This isn’t just type checking — it’s runtime validation that actively prevents you from leaking secrets. It’s like having a personal bodyguard for your env variables.</p><h3>2. Validation at Build Time = Sleep at Night Time</h3><p>Ever gone to bed right after a deploy, just to wake up to chaos? By importing your env file in next.config.js, you validate everything at build time:</p><p>Now if someone forgets to add DATABASE_URL to the CI environment, the build fails immediately with a clear error message instead of failing mysteriously in production. Your sleep schedule will thank you.</p><h3>3. Real World Example: Multi-Environment Setup</h3><p>Let’s say you’re building the next big AI Agentic MCP Workflow(as one does), and you need different feature flags and configs for different environments:</p><pre>import { createEnv } from &quot;@t3-oss/env-nextjs&quot;;<br>import { z } from &quot;zod&quot;;<br>export const env = createEnv({<br>  server: {<br>    DATABASE_URL: z.string().url(),<br>    REDIS_URL: z.string().url().optional().default(&quot;redis://localhost:6379&quot;),<br>    LOG_LEVEL: z.enum([&quot;debug&quot;, &quot;info&quot;, &quot;warn&quot;, &quot;error&quot;]).default(&quot;info&quot;),<br>    FEATURE_NEW_ALGORITHM: z.boolean().default(false),<br>    RATE_LIMIT_MAX: z.coerce.number().int().positive().default(100),<br>    SECRET_KEY: z.string().min(32),<br>  },<br>  client: {<br>    NEXT_PUBLIC_API_URL: z.string().url(),<br>    NEXT_PUBLIC_GA_ID: z.string().optional(),<br>    NEXT_PUBLIC_ENVIRONMENT: z.enum([&quot;development&quot;, &quot;staging&quot;, &quot;production&quot;]),<br>    NEXT_PUBLIC_FEATURE_CONFETTI: z.boolean().default(true), // Everyone loves confetti<br>  },<br>  runtimeEnv: {<br>    // ... mapping all the variables<br>  },<br>  // Advanced: Transform env variables<br>  createFinalSchema: (schema, isServer) =&gt;<br>    z.object(schema).transform((env, ctx) =&gt; {<br>      // Add computed properties<br>      return {<br>        ...env,<br>        IS_PROD: env.NEXT_PUBLIC_ENVIRONMENT === &quot;production&quot;,<br>        IS_DEV: env.NEXT_PUBLIC_ENVIRONMENT === &quot;development&quot;,<br>        IS_TEST: process.env.NODE_ENV === &quot;test&quot;,<br>      };<br>    }),<br>});</pre><p>Now you’ve got:</p><ul><li>Type safety</li><li>Default values</li><li>Coercion (string to number, etc.)</li><li>Computed properties</li><li>Documentation via zod schema</li></ul><p>It’s giving productivity.</p><h3>4. Deployment Provider Presets</h3><p>Working with Vercel, Netlify, or Render? The library comes with presets for common platforms:</p><pre>import { createEnv } from &quot;@t3-oss/env-nextjs&quot;;<br>import { vercel } from &quot;@t3-oss/env-core/presets-zod&quot;;<br>import { z } from &quot;zod&quot;;<br>export const env = createEnv({<br>  extends: [vercel()], // Extends from Vercel preset<br>  server: {<br>    // Your custom vars<br>    DATABASE_URL: z.string().url(),<br>  },<br>  // ...rest of config<br>});<br>// Now you can use Vercel-specific env vars<br>console.log(env.VERCEL_URL); // Typed and validated!</pre><p>Available presets include:</p><ul><li>vercel</li><li>neonVercel</li><li>uploadthing</li><li>render</li><li>railway</li><li>fly.io</li><li>netlify</li><li>upstashRedis</li></ul><p>Literally we’re so back with these presets.</p><h3>5. Error Handling: Custom Messages That Don’t Make You Cringe</h3><p>You can customize error handling to fit your workflow:</p><pre>import { createEnv } from &quot;@t3-oss/env-nextjs&quot;;<br>import { z } from &quot;zod&quot;;<br>export const env = createEnv({<br>  // ...env config<br>  onValidationError: (errors) =&gt; {<br>    console.error(&quot;❌ Invalid environment variables:&quot;, errors);<br>    throw new Error(<br>      `Missing required environment variables. Check server logs for details.`<br>    );<br>  },<br>  onInvalidAccess: (variable) =&gt; {<br>    throw new Error(<br>      `❌ Attempted to access ${variable} on the client! This is giving security breach.`<br>    );<br>  },<br>});</pre><h3>Advanced: The Secret Techniques</h3><h3>Empty String Handling</h3><p>Ever had a CI/CD pipeline set empty strings instead of undefined? T3-Env has your back:</p><pre>import { createEnv } from &quot;@t3-oss/env-nextjs&quot;;<br>import { z } from &quot;zod&quot;;<br>export const env = createEnv({<br>  // ... config<br>  emptyStringAsUndefined: true, // Treat &quot;&quot; as undefined<br>  server: {<br>    PORT: z.coerce.number().default(3000), // Empty PORT= in .env will use the default<br>  },<br>});</pre><h3>Monorepo Sharing</h3><p>If you’re running a monorepo (very tech lead energy), you can create shared environment definitions:</p><pre>// packages/auth/env.ts<br>import { createEnv } from &quot;@t3-oss/env-core&quot;;<br>export const authEnv = createEnv({<br>  server: {<br>    AUTH_SECRET: z.string().min(32),<br>    SMTP_HOST: z.string(),<br>    // ... other auth variables<br>  },<br>  // ... rest of config<br>});</pre><pre>// apps/web/env.ts<br>import { createEnv } from &quot;@t3-oss/env-nextjs&quot;;<br>import { authEnv } from &quot;@repo/auth/env&quot;;<br>export const env = createEnv({<br>  extends: [authEnv], // Inherit all the auth env vars<br>  server: {<br>    DATABASE_URL: z.string().url(),<br>    // App specific variables<br>  },<br>  // ... rest of config<br>});</pre><p>This keeps your code DRY and your schemas reusable. We love to see it.</p><h3>Conditional Variable Requirements</h3><p>Sometimes, you need variables to depend on each other. For example, if you’re supporting multiple payment providers:</p><pre>import { createEnv } from &quot;@t3-oss/env-nextjs&quot;;<br>import { z } from &quot;zod&quot;;<br>export const env = createEnv({<br>  server: {<br>    PAYMENT_PROVIDER: z.enum([&quot;stripe&quot;, &quot;paypal&quot;]),<br>    STRIPE_SECRET_KEY: z.string().optional(),<br>    STRIPE_WEBHOOK_SECRET: z.string().optional(),<br>    PAYPAL_CLIENT_ID: z.string().optional(),<br>    PAYPAL_CLIENT_SECRET: z.string().optional(),<br>  },<br>  // ... rest of config<br>  createFinalSchema: (schema, isServer) =&gt;<br>    z.object(schema).transform((env, ctx) =&gt; {<br>      // Validate conditional requirements<br>      if (env.PAYMENT_PROVIDER === &quot;stripe&quot;) {<br>        if (!env.STRIPE_SECRET_KEY || !env.STRIPE_WEBHOOK_SECRET) {<br>          ctx.addIssue({<br>            code: z.ZodIssueCode.custom,<br>            message: &quot;Stripe configuration missing required keys&quot;,<br>          });<br>          return z.NEVER;<br>        }<br>      }<br>      <br>      if (env.PAYMENT_PROVIDER === &quot;paypal&quot;) {<br>        if (!env.PAYPAL_CLIENT_ID || !env.PAYPAL_CLIENT_SECRET) {<br>          ctx.addIssue({<br>            code: z.ZodIssueCode.custom,<br>            message: &quot;PayPal configuration missing required keys&quot;,<br>          });<br>          return z.NEVER;<br>        }<br>      }<br>      <br>      return env;<br>    }),<br>});</pre><h3>Conclusion: It’s Giving Peace of Mind</h3><p>Validating environment variables might not be the sexiest part of web development, but neither is getting called at 3 AM because production is on fire. T3-Env brings:</p><ol><li><strong>Type safety</strong> — No more typos or reference errors</li><li><strong>Runtime validation</strong> — Catches missing variables before they cause problems</li><li><strong>Environment separation</strong> — Keeps server secrets off the client</li><li><strong>Framework optimization</strong> — Works with Next.js’s quirks</li><li><strong>Developer experience</strong> — Better errors, transforms, and presets</li></ol><p>So do yourself, your team, and your future sleep schedule a favor — set up proper env validation. Your 3 AM self will thank you, and that’s on period.</p><pre>// src/env.ts - The blueprint for peaceful nights<br>import { createEnv } from &quot;@t3-oss/env-nextjs&quot;;<br>import { z } from &quot;zod&quot;;<br>export const env = createEnv({<br>  server: {<br>    DATABASE_URL: z.string().url(),<br>  },<br>  client: {<br>    NEXT_PUBLIC_API_URL: z.string().url(),<br>  },<br>  runtimeEnv: process.env,<br>});</pre><p>No cap, this is the way.</p><p><em>If you found this helpful, follow me for more unhinged tech takes and tutorials that might save your job. And remember, always validate your env vars before they validate your entire career choices.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=409564af7a4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>