application.env
Small utility to load environment configurations that works for both, node and the browser, including a react context helper for react apps.
Usage
In most cases, all you need to do is invoke load function:
import { load } from 'application.env';
load().then((env) => console.log('Env ready', env));
The above will load application.env
file and append it to global object (proccess.env
for Node and window.env
for Browser).
For Node you also get sync option:
import { loadSync } from 'application.env/node'; const env = loadSync(); console.log(env === proccess.env); // true
All load variants takes an optional options argument. Here's how its fields look with their default values:
function load(
options: LoadOptions = {
path: 'application.env', // Path to a file
failSilently: false, // Returns/appends an empty object on error instead of throwing it.
validator: ObjectValidator<Env> // Environment validator (read bellow)
}): Promise<ApplicationEnv.Env> {}
Validation
All load
functions also provide a way to validate loaded env before appending it to the global objects via the second
validator
optional argument. It's basically an object describing the shape of your env object with exposed properties to handle missing values.
interface Env {
propOne: string;
nonStringProperty: number;
optionalProperty: string;
criticalProperty: string;
}
const validator: ObjectValidator<Env> = {
propOne: {
errorMessage: "No default provided, throwing an error",
},
nonStringProperty: {
default: 420,
converter: (value) => Number(value)
},
optionalProperty: {
default: "DEFAULT VALUE",
},
criticalProperty: {
critical: true,
errorMessage: "The application cannot function without this property. Terminating...",
},
};
load({validator})
TypeScript
The module comes with it's own type declarations on both, public API and global scope extensions. It's also possible to declare your own named properties on loaded Env object via TS augmentation on ApplicationEnv
namespace:
declare global {
namespace ApplicationEnv {
interface Env {
MY_PROP_ONE?: string;
ANOTHER_REQUIRED_PROP: string;
ANOTHER_OPTIONAL_PROP: string;
NODE_ENV?: string;
}
}
}
React
This module exposes a React context provider and hook to consume the context in a child component
import ApplicationEnvProvider, { useApplicationEnv } from 'application.env/react';
const App: FC = (): JSX.Element => {
return (
<ApplicationEnvProvider path="/application.env">
<Child>
</ApplicationEnvProvider>
);
};
const Child: FC = () : JSX.Element => {
const envVars = useApplicationEnv();
return (<h1>{envVars.MY_PROP_ONE}</h1>)
}
export default App;
Behind the scenes
- Node: the file is loaded from your file system.
- Browser: the file is fetched from the same server that's serving HTML & JS files.
- React: the file is fetched from the same server that's serving HTML & JS files.