@sharyn/env.check
v1.0.2
Published
Helpers to check the validity of your environment variables.
Downloads
7
Maintainers
Readme
🌹 @sharyn/env.check
Deprecated
Use envalid instead. Example:
const envalid = require('envalid')
const pick = require('lodash.pick')
const either = require('@sharyn/util.either')
const swit = require('@sharyn/util.swit')
const { email, bool, port, str } = envalid
const varDefs = {
STAGE: str({ choices: ['dev', 'local-prod', 'staging', 'prod'] }),
TRUE: bool(),
EMAIL: email({ desc: 'The email of the admin' }),
PORT: port(),
}
const env = envalid.cleanEnv(
process.env,
{
STAGE: varDefs.STAGE,
...swit(
process.env.STAGE,
['dev', 'local-prod', pick(varDefs, 'TRUE', 'PORT')],
['staging', 'prod', pick(varDefs, 'EMAIL', 'PORT')]
),
},
{ strict: true }
)
module.exports = env
@sharyn/env/check
provides 3 methods to check that your process.env
is loaded with the right variables.
Installation
npm i @sharyn/env.check
# or
yarn add @sharyn/env.check
You can alternatively install the @sharyn/browser
package, or the entire sharyn
library.
Usage
In the following example, the STAGE
corresponds to the various deployment stages, which I like to name dev
, local-prod
(with NODE_ENV
set to production
), staging
, and prod
.
Create a file to check your env, env-check.js
for instance:
import 'dotenv/config'
import { check, checkPresent, checkAbsent } from '@sharyn/env/check'
checkPresent('DATABASE_URL', 'REDIS_URL') // Checked for all stages
if (process.env.STAGE === 'dev') {
checkPresent('WEBPACK_DEV_SERVER_PORT')
checkAbsent('S3_BUCKET', 'ERROR_REPORTING')
}
if (process.env.STAGE === 'prod') {
checkPresent('S3_BUCKET', 'ERROR_REPORTING')
checkAbsent('WEBPACK_DEV_SERVER_PORT')
check('API_URL', url => url.startsWith('https://'), name => `${name} is not an HTTPS URL.`)
}
You should check your environment variables at runtime, at the very beginning or your application. Before the initialization of your Express server for instance.
import './env-check'
Imports
Depending on the package you are using, you can import
or require
getFormFields
in the following ways:
import { check, checkPresent, checkAbsent } from '@sharyn/env.check'
import { check, checkPresent, checkAbsent } from '@sharyn/env/check'
import { check, checkPresent, checkAbsent } from 'sharyn/env/check'