4

I am trying to setup an Azure Function to run locally on my development environment. I wish to connect to a MongoDb database instance.

In my local.settings.json file I have added:

"ConnectionStrings": {
    "DB_CONNECT_STRING": "mongodb://localhost:27017/MyDatabase"
}

In my function I then have:

module.exports = function (context, myTimer) {
    console.log(process.env.DB_CONNECT_STRING);
    context.done();
};

process.env.DB_CONNECT_STRING is undefined.

I assume I need to add some kind of prefix to the environment variable, but I can't find this documented anywhere. How do I specify a connection string and reference it in the function code?

3
  • Can you try process.env.ConnectionStrings.DB_CONNECT_STRING or process.env.ConnectionStrings["DB_CONNECT_STRING"]? Commented Jul 12, 2017 at 10:40
  • Both result in "cannot read property of undefined". Commented Jul 12, 2017 at 10:49
  • 1
    What happens if you add it in Values instead of ConnectionStrings? Commented Jul 12, 2017 at 16:58

2 Answers 2

6

Matt Mason is right.

In Node.js, we should specify app settings in the Values collection. These settings can then be read as environment variables by using process.env.

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "DB_CONNECT_STRING": "mongodb://localhost:27017/MyDatabase"
  }
}

enter image description here

Then use process.env.DB_CONNECT_STRING to get the value.

Sign up to request clarification or add additional context in comments.

Comments

0

For the purists out there, I found it. I set a breakpoint and evaluated "process.env" and found my connection string in this format:

ConnectionStrings:<ConnectionName>

enter image description here

So if my local.settings.json looks like this:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "node",
  },
  "Host": {
    "CORS": "http://localhost:8080"
  },
  "ConnectionStrings": {
    "Prod": "MyConnString"
  }
}

Then I would access it like this:

 const sqlConnString = process.env['ConnectionStrings:Prod'];

You have to use bracket notation because of the colon.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.