I'm using joi to structure data.
Now I'm unable to read environment variable set on startup.

I have a startup scrip.sh like:

PUBLIC_KEY="$(cat public_key.pem) docker-compose up --build"

Then I try to read that PUBLIC_KEY variable.

const envVariables = joi.object({
 PUBLIC_KEY: joi.string()
    .default('PUBLIC_KEY')
})

I thought this would automatically identify the variable but it does not.
Is it possible to get the variable set on start up with Joi?


Solution 1:

You can get environment variables using the process core module. From the documentation :

The process core module of Node.js provides the env property which hosts all the environment variables that were set at the moment the process was started.

For example,

const pubKey = process.env.PUBLIC_KEY

Solution 2:

  1. Joi does not provide variables, at least in such a way you want
  2. use it from the process if it's provided by CLI arguments or additionally use dotenv.config() to read synchronously from .env files
  3. if you need to read some previous value inside Joi schema logic you e.g. for some conditions you cat try this example
var schema = {
    a: Joi.string(),
    b: Joi.string(),
    c: Joi.string().when('a', { is: 'avalue', then: Joi.string().required() }).concat(Joi.string().when('b', { is: 'bvalue', then: Joi.string().required() }))
};