Skip to content

Instantly share code, notes, and snippets.

@graffhyrum
Last active August 31, 2025 20:27
Show Gist options
  • Select an option

  • Save graffhyrum/1e136ffdb5abdc8f54cbb8bcbfb32d42 to your computer and use it in GitHub Desktop.

Select an option

Save graffhyrum/1e136ffdb5abdc8f54cbb8bcbfb32d42 to your computer and use it in GitHub Desktop.
Validate and Parse process environment variables with Arktype.
import {validateAndParseEnv} from './schema';
const goodMockProcEnv = {
HOST: 'localhost',
PORT: '8080',
KEY: '1234567890',
SECRET: '1234567890',
EXTRAKEY: 'foo', // extra keys are ignored
};
const goodVersion = validateAndParseEnv(goodMockProcEnv);
handleResult(goodVersion);
/*
value is ok: {
"HOST": "localhost",
"PORT": 8080,
"KEY": "1234567890",
"SECRET": "1234567890",
"EXTRAKEY": "foo"
}
*/
const badMockedProcEnv = {
HOST: 'localhost',
PORT: '8080qqq', // should fail parsing
KEY: '1234567890',
SECRET: '', // should fail validation
EXTRAKEY: 'foo',
};
const badVersion = validateAndParseEnv(badMockedProcEnv);
handleResult(badVersion);
/*
Note that both errors are caught.
value is error: [
{
"data": "",
"path": [
"SECRET"
],
"code": "minLength",
"description": "at least length 2",
"meta": {},
"rule": 2,
"expected": "at least length 2",
"actual": "",
"problem": "must be at least length 2",
"message": "SECRET must be at least length 2"
},
{
"data": null,
"path": [
"PORT"
],
"code": "domain",
"description": "a number",
"meta": {},
"domain": "number",
"expected": "a number",
"actual": "NaN",
"problem": "must be a number (was NaN)",
"message": "PORT must be a number (was NaN)"
}
]
*/
function handleResult(result: ReturnType<typeof validateAndParseEnv>) {
result.match(
(value) => {
console.log(`value is ok: ${JSON.stringify(value, null, 2)}`);
},
(errors) => {
console.log(`value is error: ${JSON.stringify(errors, null, 2)}`);
},
);
}
import {ArkErrors, type} from 'arktype';
import {err, ok, Result} from 'neverthrow';
const procEnvSchema = type({
'HOST': 'string > 1',
'PORT': type('string')
.pipe(s => Number(s))
.to('0 < number < 65535'),
'KEY': 'string > 1',
'SECRET': 'string > 1',
});
// If you need type inference later.
export type ProcEnv = typeof procEnvSchema.infer;
export function validateAndParseEnv(env: NodeJS.ProcessEnv):Result<ProcEnv, ArkErrors> {
const procEnvResult = procEnvSchema(env);
if (procEnvResult instanceof ArkErrors) {
return err(procEnvResult)
}
return ok(procEnvResult);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment