ark.env

Quickstart

Let's get you started with a few simple steps

#Install

npm install ark.env arktype

#Configure your project

Enable strict mode for the best typesafety:

tsconfig.json
{
  "compilerOptions": {
    "strict": true
  }
}

ark.env is built on top of ArkType. Follow the ArkType setup instructions to configure your project.

#Define the schema

Add a schema to make your environment variables validated and typesafe:

config/env.ts
import ark, { host, port } from 'ark.env';
 
export const env = ark.env({
  // Built-in validators
  DATABASE_HOST: host,
  DATABASE_PORT: port,
  
  // Custom string literals
  NODE_ENV: "'development' | 'production' | 'test'",
  
  // Optional variables with defaults
  LOG_LEVEL: "'debug' | 'info' | 'warn' | 'error' = 'info'",
  
  // Optional environment variable
  "API_KEY?": 'string'
});

#Define environment variables

Create a .env file in your project root with some environment variables:

.env
DATABASE_HOST=localhost
DATABASE_PORT=5432
NODE_ENV=development
API_KEY=your-secret-key

Tip

Avoid committing your .env file to version control:

echo ".env" >> .gitignore

#Use in your code

Import and use your validated and typed environment variables. For example, you might have a file like database.ts:

database.ts
import { env } from './config/env';
 
// TypeScript knows the ✨exact✨ types!
const dbConfig = {
  host: env.DATABASE_HOST,  // string (valid host)
  port: env.DATABASE_PORT,  // number (valid port)
};

#Next steps

On this page