React Environment Variables

Looking for the best way to get process.env variables for a create react app implmented.

Thanks in advance.

Can you explain how it works, for people not familiar?

Sure, this is probably the best reference: https://create-react-app.dev/docs/adding-custom-environment-variables/

So far I just have a simple binding like so:

@val @scope("prorecess") external env: Js.Dict.t<string> = "env"
switch env->Js.Dict.get("REACT_APP_STRIPE_CLIENT_ID") {
| Some(clientId) => Js.log2("Get Stripe URL", clientId)
| None => Js.log("No Stripe Client Id Found")
}

Curious to see any more elegant solutions out there.

1 Like

I suggest using @scope: https://github.com/shakacode/rust-rescript-demo/blob/master/client/src/lib/Env.res

Js.Dict might cause problems since some bundlers rely on process.env.[X] form in JS code.

EDIT: If some vars are optional, then

@val @scope(("process", "env")) @return(nullable) external x: option<string> = "X"

P.S. Didn’t check the code, typing from my phone.

5 Likes

Another option is:

type env = {
  @as("PUBLIC_FOO")
  foo: string,
  @as("PUBLIC_BAR_OPTIONAL")
  bar: option<string>,
}
@val @scope("process") external env: env = "env"

@return(nullable) is not needed for missing options as they are undefined which naturally works as None

4 Likes

Unless some naughty third party sets a property to null!