npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

zodotenv

v1.2.0

Published

Validate and parse your environment variables like a responsible adult

Downloads

319

Readme

Validate and parse your environment variables like a responsible adult

Installation

Use your favourite package manager to install zodotenv:

npm i zodotenv

pnpm add zodotenv

bun add zodotenv

deno add npm:zodotenv

Usage

Define your configuration

import { z } from 'zod';
import { zodotenv } from 'zodotenv';

const config = zodotenv({
  name: ['NAME', z.string().default('my-app')],
  port: ['PORT', z.coerce.number().default(3000)],
  http2: ['HTTP2', z.string().transform((s) => s === 'true')],
  database: {
    host: ['DB_HOST', z.string()],
    driver: ['DB_DRIVER', z.enum(['mysql', 'pgsql', 'sqlite'])],
    tables: ['DB_TABLES', z.preprocess((s) => s.split(','), z.array(z.string()))],
  },
  credentials: {
    username: ['USERNAME', z.string()],
    password: ['PASSWORD', z.string(), { secret: true }],
  },
});

[!CAUTION] If the environment variable doesn’t match the Zod schema, zodotenv will throw an error. Simple as that.

Grab your values with config(...)

It returns the parsed and validated values including the inferred TypeScript types.

You can even dive into nested values using an object-path-style string, with autocompletion and TypeScript validation to help you out.

config('port'); // number
config('database.driver'); // 'mysql' | 'pgsql' | 'sqlite'
config('database.tables'); // string[]

config('something.which.does.not.exist');
// ^^^ TypeScript will call you out on this one

Serialise your configuration

You can serialise your entire configuration object to JSON. This is useful for logging or debugging purposes.

console.log(JSON.stringify(config, null, 2));

// or

console.log(config.toJSON());

[!TIP] Any configuration entries marked with { secret: true } will have their values masked when serialising to JSON, ensuring that sensitive information is not exposed.

Example

const config = zodotenv({
  port: ['PORT', z.coerce.number().default(3000)],
  database: {
    host: ['DB_HOST', z.string()],
    password: ['DB_PASSWORD', z.string(), { secret: true }],
  },
});

console.log(JSON.stringify(config, null, 2));
// Output:
//  {
//    "port": 3000,
//    "database.host": "localhost:5432",
//    "database.password": "*********"
//  }

Tips

Check out Zod schemas if you haven't already!

Since all environment variables are strings, you might need to use .coerce / .transform() / .preprocess() to convert them to the type you need:

// Boolean, e.g. `HTTP2=true`
z.string().transform((s) => s === 'true')

// Number, e.g. `PORT=3000`
z.coerce.number()

// Comma-separated list to string array, e.g. `DB_TABLES=users,posts` -> ["users", "posts"]
z.preprocess((v) => String(v).split(','), z.array(z.string()))

// JSON string to object, e.g. `CONFIG={"key":"value"}` -> {key: "value"}
z.string().transform((s) => JSON.parse(s)).pipe(
  z.object({ key: z.string() })
)