1

I have Node JS Azure function that when I run locally needs the NODE_TLS_REJECT_UNAUTHORIZED=0 environment variable needs setting for my code to work. This is because I am connecting to an emulated Cosmos DB running locally on my machine which require Node to allow for self signed certificates.

I only want this environment variable setting when I run locally as in production I will be using a real (i.e. non emulated) Cosmos DB instance. Rather than putting and #if debug in my code (or the equivalent for a Node Azure Function) I'd like my VS Code project to set the env var when it is launched.

I've trying following this answers advice but when VS Code launches the program the environment variable is not set as I get a runtime error in my code about self signed certificates not being authorised. My launch.json looks like this:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Attach to Node Functions",
      "type": "node",
      "request": "attach",
      "port": 9229,
      "preLaunchTask": "func: ",
    },
  ],
  "environment": [{
    "name": "NODE_TLS_REJECT_UNAUTHORIZED",
    "value": "0"
    }],
  }

If I set the env var directly in code using process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0 everything is fine. I don't know how I can get VS Code to set this, or if it is even possible.

lukestringer90
  • 492
  • 7
  • 16

1 Answers1

2

Please update

"environment": [{ "name": "NODE_TLS_REJECT_UNAUTHORIZED", "value": "0" }],

To Be

"env": { "name": "NODE_TLS_REJECT_UNAUTHORIZED", "value": "0" },

Also please check the alternatives.

You can Update package.json scripts to add all environment variables on start like "runLocal": "NODE_TLS_REJECT_UNAUTHORIZED=0 ... your start code " or You can use third party lib called dotenv

this is how it works

01- Create .env file

02- Write all your environment variables key=val NODE_TLS_REJECT_UNAUTHORIZED=0

03- Update package.json scripts to add "runLocal": "NODE_ENV=dev ... your start code "

04- Check if node NODE_ENV is equal dev then load the dotenv

05- Import module in case of node env is local and call config function require('dotenv').config()

Yasser Mas
  • 1,652
  • 1
  • 10
  • 14
  • 1
    Thanks, I've figured it out using dotenv. I found this article also useful: https://medium.com/the-node-js-collection/making-your-node-js-work-everywhere-with-environment-variables-2da8cdf6e786 – lukestringer90 Aug 25 '19 at 11:54