npm

Need private packages and team management tools?Check out npm Orgs. »

@taktikal/env

1.1.1 • Public • Published

@taktikal/env

Utility for dynamic runtime environment variables in compiled Server Side Rendered apps.

Getting started

Configuration

Create enums for PrivateEnv and a PublicEnv.

// types.ts
export enum PrivateEnv {
  API_URL = "API_URL",
}
 
export enum PublicEnv {
  SENTRY_DSN = "SENTRY_DSN",
}

Register the environment on the server side. This example is for Next.js

// _document.tsx
import { registerEnv } from "@taktikal/env";
import { PublicEnv, PrivateEnv } from "~/types";
 
const envScript = registerEnv({ public: PublicEnv, private: PrivateEnv }, {
  API_URL: "This is private",
  SENTRY_ENV: "This is public",
  PRIV: "priv",
});
 
// ...
 
<script dangerouslySetInnerHTML={{ __html: envScript }} />,

The string returned from registerEnv will be in the form __ENV__={ ...publicEnv }. The serialized __ENV__ object is html safe.

Then we create getters for both publicEnv and privateEnv with createEnvGetters.

// utils/env.ts
import { createEnvGetters } from "@taktikal/env";
import { PublicEnv, PrivateEnv } from "~/types";
 
export const { getPrivateEnv, getPublicEnv } = createEnvGetters({
  public: PublicEnv,
  private: PrivateEnv,
});

Usage

getPrivateEnv has access to both the public and private env.

// Server side
import { getPrivateEnv } from "~/utils/env";
 
const apiUrl    = getPrivateEnv("API_URL");    // Getting from private env
const sentryDsn = getPrivateEnv("SENTRY_DSN"); // Getting from public env
 
getPrivateEnv("INVALID_KEY"); // Error: Key 'INVALID_KEY' does not exist in private or public env.

getPublicEnv only has access to the public env.

// Client side
import { getPublicEnv } from "~/utils/env";
 
const sentryDsn = getPublicEnv("SENTRY_DSN"); // Getting from public env
 
getPublicEnv("API_URL"); // Error: Key 'API_URL' does not exist in public env.

Keywords

none

install

npm i @taktikal/env

Downloadsweekly downloads

39

version

1.1.1

license

ISC

homepage

gitlab.com

repository

Gitgitlab

last publish

collaborators

  • avatar
  • avatar
Report a vulnerability