⚡ Practical Guide to Serverless Microsoft Azure Functions with JavaScript
Tags: javascript, azure
Published: 2018-10-15 12:46:30

---
title: ⚡ Practical Guide to Serverless Microsoft Azure Functions with JavaScript
published: true
tags: JavaScript,Azure,
cover_image: https://on.ahmda.ws/a16f67/c
canonical_url: https://ahmadawais.com/microsoft-azure-functions-javascript/
---

> Check out my latest courses for developers

> - [NodeCLI.com](https://NodeCLI.com) — Build Node.js CLI Automation DevTools. 10 hours, 100 videos, 22 projects, beginner-friendly.

> - [VSCode.pro](https://VSCode.pro) — Become a VSCode Power User and learn 200+ tips/tricks workflows like multi-cursors, debugging, & macros. Learn almost every workflow I have.

---

As a Full Stack JavaScript developer, I am super excited about this relatively new FaaS or Functions as a Service offering that has also caught on a name of `Serverless` — since you don't have to manage, update, patch, or worry about servers. 


While [building this custom WordPress dashboard](https://ahmadawais.com/wordpress-mongodb-atlas-microsoft-azure-serverless-functions/), I wanted to make sure that each module of this dashboard lived in form of a serverless app with multiple serverless functions. This decision was based on keeping this dashboard's cost as economical as possible.

### 👀  Three Options

There are three major cloud services providers present. That are [Microsoft Azure](https://azure.microsoft.com/en-us/), [Google Cloud Platform](https://cloud.google.com/), and [Amazon Web Services](https://aws.amazon.com/). Each of which has serverless functions available which are called Azure functions, GCP Cloud Functions, and AWS Lambdas.

### 📘 Choosing Azure

Azure has one of the biggest cloud architecture and global presence. 50 Azure regions, more than any cloud provider and after testing each of these three, I found that Azure functions had the best response time in UAE (as my client's business is based out of UAE). 

Also, the fact that we're using Azure ML Studio, AI Cognitive Services, and Virtual Machines to host parts of this project, it made complete sense to use Azure functions for the serverless architecture.

## Getting Started with Azure Functions

Let's get started with Azure functions. I am going to take you through the process of creating a simple serverless Azure function, which will be triggered via HTTP requests, and inside it, we'll process the sales information sent to us from Paddle.com.

### ⚙ What are we building?!

1.  I am building a serverless Azure function which is based on JavaScript and specifically Node.js code.
2.  This Azure function will get triggered by a simple `GET` HTTP request from our 3rd party payment solution, i.e., Paddle.com
3.  As soon as there's a sale on Paddle.com, it will [trigger a webhook](https://paddle.com/docs/reference-using-webhooks) that contains info related to our sale, quantity, item, earnings, and some member-related data that WordPress sent to Paddle.
4.  Using WordPress REST API, I have added some custom data related to the user who purchased the product, like user's ID in WordPress DB, which WordPress site had this sale, and such user's meta info.
5.  When Azure function receives this `GET` request, it processes the info, takes out what I need to keep in the MongoDB Atlas Cluster and forms a JavaScript object ready to be saved in the DB.
6.  The azure function then connects to MongoDB Atlas instance via an npm package called [mongoose](http://mongoosejs.com/), where after connecting the database, I create a DB Model/Schema, and then this data is saved to the MongoDB Atlas Cluster.
7.  After which Azure function kind of sits there waiting for next sale to happen, where my client only pays for the execution time and amount of executions for Azure functions. ([1 million of which are free every month](https://azure.microsoft.com/en-us/pricing/details/functions/) 😮).

Now, this is only a high-level summary of what's happening, there's a lot of steps that I skipped here like authentication which is beyond the scope of this article. You should always setup authentication and verification to keep things civil and avoid any overage. 

So, let's go ahead and build this thing.

### Step#1: Set up Microsoft Azure & VSCode

I expect you to have the [Azure](https://azure.microsoft.com/) account set up on your end. You'll need to subscribe with a credit card since we need storage for hosting the Node.js files which will be used with Azure Functions and you have to pay for storage (you'll probably get a free $200 credit for the first month and even after that the cost is quite pretty low). So, go ahead and set up the following:

1.  ✅ Setup a [Microsoft Azure](https://azure.microsoft.com/) account with a credit card in billing.
2.  ✅ Install [Visual Studio Code](https://code.visualstudio.com/) (Psst. I'm making a [course on VSCode](https://ahmadawais.com/visual-studio-code-power-user/)).
3.  ✅ Install the [Azure Functions extension](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azurefunctions) on your VSCode.
4.  💡 To enable local debugging, install the [Azure Functions Core Tools](https://github.com/Azure/azure-functions-core-tools#installing).
5.  🗂 Create a new directory and open it up in VSCode.

_In case you're wondering which theme and font I am using, it's 🦄[Shades of Purple](https://marketplace.visualstudio.com/items?itemName=ahmadawais.shades-of-purple) — along with my [VSCode.pro course](https://VSCode.pro/). For more info see which [software and hardware I use](https://ahmadawais.com/uses/)._


[![VSCode 🦄 Shades of Purple theme](https://ahmadawais.com/wp-content/uploads/2018/05/7-VSCode-Shades-of-Puple.jpg)](https://marketplace.visualstudio.com/items?itemName=ahmadawais.shades-of-purple)

### Step#2: Create a New Function App Project

Now let's create a new function app project. This is really easy with VSCode. All you have to do is go-to the Azure Extension explorer present in the activity bar. From there access `FUNCTIONS` tab and click on the first `Create New Project` icon. 

This will create a demo project, with basic files required to get started and will initialize a Git repo for you. I'll keep up with small gif based demos to make things easier for you. 

 ![GIF for MongoDB Atlas, Microsoft Azure, & Serverless Functions](https://ddwva799xzrph.cloudfront.net/items/1l0g2p0Z3q1F0T120d0F/Screen%20Recording%202018-05-21%20at%2011.41%20PM.gif) 

### Step#3: Create an HTTP-triggered Azure Function

Now that we have created a function app project, let's create an HTTP-triggered serverless Azure function. For that, go-to the Azure Extension explorer present in the activity bar. From there access `FUNCTIONS` tab and click on the second icon `Create Function`. 

For the sake of this demo, I am choosing to keep the authentication part simple so going to select anonymous access. The name of our Azure function is `HttpTriggerJS` so you can find a new directory created with that name inside your project. This should contain two files i.e. `functions.json` and `index.js` .

⚡ A _function_ is a primary concept in Azure Functions. You write code for a function in a language of your choice and save the code and configuration files in the same folder. 


🛠 The configuration is named `function.json`, which contains JSON configuration data. It defines the function bindings and other configuration settings. The runtime uses this file to determine the events to monitor and how to pass data into and return data from function execution. [Read more on this file in the official documentation here](https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference#function-code). 

Following is an example `function.json` file that gets created. 

{%gist https://gist.github.com/ahmadawais/9e0b7a61e4b50c671a132547c5c148ae %}

And then, there's an `index.js` file which contains a basic code that you can use to test your Azure function. It receives a parameter `name` and prints it back to you or shows you an error asking for this parameter. 

{%gist https://gist.github.com/ahmadawais/d9791f74cfe114548a58227ed8db2dd1 %}
 
![GIF for MongoDB Atlas, Microsoft Azure, & Serverless Functions](https://ddwva799xzrph.cloudfront.net/items/462i2l1I0q2g3W2h380r/Screen%20Recording%202018-05-21%20at%2011.47%20PM.gif) 

### Step#4: Deploy & Test Your Azure Function

Now that we have created an Azure function which can be triggered by `GET` HTTP request, let's go ahead and deploy it with VSCode and test it with [Postman](https://www.getpostman.com/) API Explorer. 

To deploy the function go-to the Azure Extension explorer present in the activity bar. From there access `FUNCTIONS` tab and click on the third icon `Deploy to Function App`. 

This will ask you a bunch of questions about what is the name of your app, use anything unique. I used `demo-wp-mdb-azure`— VSCode then use this to create a resource group, to group together your function-app related resources, it's storage (used to save the files), and the created Azure function — finally responding us back with a public URL. 


I then went ahead to access this URL and it asked for the `name` param as per the code then when I sent the `name` param with the Postman app, it responded with `Hello Ahmad Awais`. 👍 

VSCode also asked me to update the function extension app version to beta, and I chose yes — coz that will help me use Node.js v8 for async/await. 

![GIF for MongoDB Atlas, Microsoft Azure, & Serverless Functions](https://ddwva799xzrph.cloudfront.net/items/0Z292i0m2b010z3D1f2E/Screen%20Recording%202018-05-22%20at%2012.20%20AM.gif) 

### Step#5: Create `package.json` and Install [`mongoose`](http://mongoosejs.com/)

Now that our Azure function is up and running. Let's create a `package.json` file in the root of our project and install [`mongoose`](http://mongoosejs.com/). We'll need this to connect and save data to our MongoDB Atlas Cluster.

Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in typecasting, validation, query building, business logic hooks and more, out of the box. It's pretty awesome. 💯 

![GIF for MongoDB Atlas, Microsoft Azure, & Serverless Functions](https://ddwva799xzrph.cloudfront.net/items/3y2S050O3m172T2e061U/Screen%20Recording%202018-05-22%20at%2012.36%20AM.gif) 

### Step#6: Add App Setting for MongoDB Connection

Now we are almost ready to start writing code for our application. But before doing that, we'll need a connection string to be able to connect to our MongoDB Atlas Cluster (just like we did with MongoDB Compass). This connection string is private and you shouldn't commit it to the git repo. 

💯 This connections string belongs to the `local.settings.json` file in the project root. Let's first download the settings, then add `MongodbAtlas` setting with our connection string (get this string from the MongoDB Atlas dashboard) and upload the app settings. 

To do this, go-to the Azure Extension explorer present in the activity bar. From there access `FUNCTIONS` tab and select your subscription, then your Azure function app, i.e., `demo-wp-mdb-azure` and then right click `Application Settings` to select `Download remote settings…` to download and `Upload local settings…` to upload the settings after adding the `MongodbAtlas` connection string to the settings. 

![GIF for MongoDB Atlas, Microsoft Azure, & Serverless Functions](https://ddwva799xzrph.cloudfront.net/items/0D2X2I100v1Y0i0R0K2g/Screen%20Recording%202018-05-22%20at%2001.19%20AM.gif) 

### Step#7: Update Node Version of Azure Function

In the code, I intend to use `async`/`await` which are not available on `v6.5.0` of Node.js that comes with the default version 1 of Azure functions. In the step #4, VSCode asked me to update to the runtime version of Azure function to beta and I did that. This enables support for latest Node.js versions on Azure functions.

So, let's just update `WEBSITE_NODE_DEFAULT_VERSION` app setting in our local settings and update that to the remote settings. 

![GIF for MongoDB Atlas, Microsoft Azure, & Serverless Functions](https://ddwva799xzrph.cloudfront.net/items/1b1b3e3h1N3u0k0W3b2C/Screen%20Recording%202018-05-22%20at%2001.44%20AM.gif) 

### Step#8: Create MongoDB Model/Schema

Before we save any data to our MongoDB Atlas Cluster, let's create a `modelSale.js` file that will contain the model's schema for what we intend to save in the database. It's an extremely simple schema implementation, I suggest you read up on what you can do here with `[mongoose](http://mongoosejs.com/docs/guide.html)` and [MongoDB](https://docs.mongodb.com/manual/data-modeling/). 

_This file is pretty much self-explanatory._ 

{%gist https://gist.github.com/ahmadawais/c4c33b2a0e519ef79efa50e9aeb7f40f %}


### Step#9: Code the ⚡Azure Function with Node.js

Now let's code our Azure function. I'm adding all the main code lives inside the `index.js` file for the purpose of this demo. Also going to use the [context object](https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-node#context-object) as the first parameter, make sure you [read about that](https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-node#context-object). Everything else is explained in the code snippet below. 


So, this is just a demo code for this article. It does the following:

- ✅ Gets the data from Paddle.com
- ⚡ Connects to the MongoDB Atlas via connection string that we added in our Application Settings.
- 📘 Uses the defined DB schema inside the `test` database where it creates a `sales` collection including documents for our sales.
- ⚙ Validates the data and creates a `finalData` object that gets saved in the MongoDB Atlas Cluster. Yay!!!
- 🥅 Finally, responds to the Paddle webhook with `200` status code if all goes well, and does the [`context.done()`](https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-node#context-object) dance.

_Everything is pretty much explained with inline documentation._ 

{%gist https://gist.github.com/ahmadawais/50bf1af0fb30ca80aca1800e46d8af27 %}

### Step#10: Re-Deploy The Azure Function

Now let's re-deploy the Azure function. For that, go-to the Azure Extension explorer present in the activity bar. From there access `FUNCTIONS` tab and click on the third `Deploy to Function App` icon. 

 ![GIF for MongoDB Atlas, Microsoft Azure, & Serverless Functions](https://ddwva799xzrph.cloudfront.net/items/0k1I0r0o2Z023Y1m3z1T/Screen%20Recording%202018-05-22%20at%2002.20%20AM.gif)

### Step#11: Test Azure Function via Paddle's Webhook

Looks like we're pretty much done. All that's left is to test our Azure function by triggering a dummy webhook via Paddle.com. Let's do that. Also, when things do work, let's explore how our data looks in the MongoDB Compass.  

Checkout this [8Mb Gif that won't load here →](https://ddwva799xzrph.cloudfront.net/items/2u0B100V1m321O3o3V3I/10.gif)


_Wow, Humph!!! That was a lot. Glad it worked. 🎉_

## 🤔 So, What Just Happened?!

Prepare yourself for a mouthful. 

- 1️⃣ I created a small part of the `Sales` module in the custom WordPress Dashboard app that I am building
- 2️⃣ I used MongoDB Atlas and Compass, then created Microsoft ⚡Azure Function via Function App with [VSCode](https://VSCode.pro/) 
- 3️⃣ I deployed the app with env secret as application string with the MongoDB connection string
- 4️⃣ I then updated the Node.js version for Azure functions 
- 5️⃣ And then I triggered the function via a dummy webhook from Paddle.com (like it will get triggered when an actual sale will happen) to send data (from Paddle + WordPress) to our Azure function and from there to MongoDB Atlas. 
- ✅ _And it worked, haha!_ 

> That's about it. To read more about this topic, take this gigantic post for a read" [Building a custom WordPress dashboard with Azure Functions & MongoDB →](https://ahmadawais.com/wordpress-mongodb-atlas-microsoft-azure-serverless-functions/)

_— So, yes, try out Microsoft Azure functions (serverless stuff is pretty cool) and share your thoughts below, over to you! Peace! ✌️_

Follow me on Twitter for where I share #OneDevMinute tips [@MrAhmadAwais →](https://twitter.com/MrAhmadAwais/)