A little background
If you have been coding for a while, you know the importance of environment variables and the role it plays, and also the pain of figuring out a bug which was caused just because a damn env variable wasn’t set in your project, lol!
Earlier this year, I worked at an product based startup as a Full stack developer intern. As the project grew, the number of env variables also grew. And, everybody was working on separate features on separate branches, so we had no idea if someone introduced some new env variable in their branch which later got merged into the main branch. This created problems when I tried to deploy my branches, I had know idea that a new env var has been added to the the project.
Then, later I got introduced to T3 stack and it had a brilliant solution for adding type safety to env variables. I didn’t even know such a solution even existed. It’s always feels good to learn something new when you least expect it. T3 stack uses zod and @t3-oss/env-nextjs package to add type safety to your applications which I liked very much. After that, I made a commitment to always type-safe my env variables no matter what.
If you’re starting a new project, or already working in a team, I’d highly recommend you to please add type safety to your envs. Adding just this will save you your efforts for figuring out problems in your codebase.
Here’ how you can add it to your project. It’s fairly simple.
What is zod?
Zod is a lightweight, fast, schema declaration and validation library. A schema can be anything from a simple string, number to complex object type.
Basic usage
import {z} from 'zod'; const myBoolean = z.boolean(); myBoolean.parse('true'); // throws error myBoolean.parse(true) // valid
Creating a nested object schema
import { z } from 'zod'; const userSchema = z.object({ name: z.string(), age: z.number(), address: z.object({ house_no: z.string(), locality: z.string(), city: z.string(), state: z.string(), }) });
You can create a simple object schema or create nested objects schema.
What is t3-oss/env-nextjs?
It is simply a package which will help us add type safety to env variables
Let’s create type-safe env variables
Create a env.js file at the root of your project.
import {createEnv} from "@t3-oss/env-nextjs"; import {z} from "zod"; export const env = createEnv({ /* * Serverside Environment variables, not available on the client. * Will throw if you access these variables on the client. */ server: { DB_URI: z.string().url(), }, /* * Environment variables available on the client (and server). * * You'll get type errors if these are not prefixed with NEXT_PUBLIC_. */ client: { NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: z.string().min(1), }, /* * Due to how Next.js bundles environment variables on Edge and Client, * we need to manually destructure them to make sure all are included in bundle. * * You'll get type errors if not all variables from `server` & `client` are included here. */ runtimeEnv: { DB_URI: process.env.DATABASE_URL, NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY, }, });
Usage
import {env} from '@/env'; const CLERK_PUBLISHABLE_KEY = env.NEXT_PUBLISHABLE_KEY;
If you hover your cursor above NEXT_PUBLISHABLE_KEY, you can see that that value is typed as string, that means our env variables are typed now.
We’ve added type safe env variables, but this will not run on every build time. we have to import our newly created file into our next.config.js file. You can use unjs/jiti package for that.
First, install the jiti pacakge from npm.
import { fileURLToPath } from "node:url"; import createJiti from "jiti"; const jiti = createJiti(fileURLToPath(import.meta.url)); jiti("./app/env");
When working with import.meta.url, it provides the URL of the file you are currently working in. However, it includes a file:/// prefix, which you might not want. To remove that prefix, you can use the fileURLToPath function from the node:url module.
For example:
import {fileURLToPath} from 'node:url'; // Convert the file URL to a path const filename = fileURLToPath(import.meta.url);
Now, if you do not have the required env variables, you will see an error like this -
How to add type-safety to env variables in Node.js Projects?
import dotenv from "dotenv"; import { z } from "zod"; dotenv.config(); const schema = z.object({ MONGO_URI: z.string(), PORT: z.coerce.number(), JWT_SECRET: z.string(), NODE_ENV: z .enum(["development", "production", "test"]) .default("development"), }); const parsed = schema.safeParse(process.env); if (!parsed.success) { console.error( "❌ Invalid environment variables:", JSON.stringify(parsed.error.format(), null, 4) ); process.exit(1); } export default parsed.data;
In Node.js projects we're going to be simply creating a zod schema and parsing it against our process.env in order to check whether all the env variables are set or not.
Usage
import express from "express"; import env from "./env"; const app = express(); const PORT = env.PORT || 5000; // PORT is type safe here.... app.listen(PORT, () => { console.log("Connected to server on PORT ${PORT}"); connectDB(); });
That’s how you add type safety to your env variables. I hope you learnt something new in this tutorial.
Happy Coding!! ?
以上是Why you should always add type safety to your environment variables?的详细内容。更多信息请关注PHP中文网其他相关文章!

JavaScript字符串替换方法详解及常见问题解答 本文将探讨两种在JavaScript中替换字符串字符的方法:在JavaScript代码内部替换和在网页HTML内部替换。 在JavaScript代码内部替换字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 该方法仅替换第一个匹配项。要替换所有匹配项,需使用正则表达式并添加全局标志g: str = str.replace(/fi

本教程向您展示了如何将自定义的Google搜索API集成到您的博客或网站中,提供了比标准WordPress主题搜索功能更精致的搜索体验。 令人惊讶的是简单!您将能够将搜索限制为Y

因此,在这里,您准备好了解所有称为Ajax的东西。但是,到底是什么? AJAX一词是指用于创建动态,交互式Web内容的一系列宽松的技术。 Ajax一词,最初由Jesse J创造

本文系列在2017年中期进行了最新信息和新示例。 在此JSON示例中,我们将研究如何使用JSON格式将简单值存储在文件中。 使用键值对符号,我们可以存储任何类型的

增强您的代码演示:开发人员的10个语法荧光笔 在您的网站或博客上共享代码片段是开发人员的常见实践。 选择合适的语法荧光笔可以显着提高可读性和视觉吸引力。 t

本文介绍了关于JavaScript和JQuery模型视图控制器(MVC)框架的10多个教程的精选选择,非常适合在新的一年中提高您的网络开发技能。 这些教程涵盖了来自Foundatio的一系列主题

利用轻松的网页布局:8个基本插件 jQuery大大简化了网页布局。 本文重点介绍了简化该过程的八个功能强大的JQuery插件,对于手动网站创建特别有用

核心要点 JavaScript 中的 this 通常指代“拥有”该方法的对象,但具体取决于函数的调用方式。 没有当前对象时,this 指代全局对象。在 Web 浏览器中,它由 window 表示。 调用函数时,this 保持全局对象;但调用对象构造函数或其任何方法时,this 指代对象的实例。 可以使用 call()、apply() 和 bind() 等方法更改 this 的上下文。这些方法使用给定的 this 值和参数调用函数。 JavaScript 是一门优秀的编程语言。几年前,这句话可


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

SublimeText3 Linux新版
SublimeText3 Linux最新版