@taktikal/env
Utility for dynamic runtime environment variables in compiled Server Side Rendered apps.
Last updated 2 months ago by bjark .
ISC · Repository · Original npm · Tarball · package.json
$ cnpm install @taktikal/env 
SYNC missed versions from official npm registry.

@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.

Current Tags

  • 1.1.1                                ...           latest (2 months ago)

4 Versions

  • 1.1.1                                ...           2 months ago
  • 1.1.0                                ...           2 months ago
  • 1.0.1                                ...           8 months ago
  • 1.0.0                                ...           9 months ago
Maintainers (2)
Downloads
Today 0
This Week 1
This Month 2
Last Day 1
Last Week 1
Last Month 0
Dependencies (3)
Dev Dependencies (12)
Dependents (0)
None

Copyright 2014 - 2016 © taobao.org |