loading...
Cover image for ⚡ Practical Guide to Serverless Microsoft Azure Functions with JavaScript

⚡ Practical Guide to Serverless Microsoft Azure Functions with JavaScript

mrahmadawais profile image Ahmad Awais ⚡️ Originally published at ahmadawais.com on ・10 min read

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, 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, Google Cloud Platform, and Amazon Web Services. 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 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, 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 😮).

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 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 account with a credit card in billing.
  2. ✅ Install Visual Studio Code (Psst. I'm making a course on VSCode).
  3. ✅ Install the Azure Functions extension on your VSCode.
  4. 💡 To enable local debugging, install the Azure Functions Core Tools.
  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 — along with my VSCode.pro course. For more info see which software and hardware I use.

VSCode 🦄 Shades of Purple theme

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

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.

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

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.

GIF for MongoDB Atlas, Microsoft Azure, & Serverless Functions

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 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

Step#5: Create package.json and Install mongoose

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. 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

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

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

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.

This file is pretty much self-explanatory.

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 as the first parameter, make sure you read about that. 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() dance.

Everything is pretty much explained with inline documentation.

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

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 →

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
  • 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 →

— 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 →

Posted on by:

mrahmadawais profile

Ahmad Awais ⚡️

@mrahmadawais

Edutianer VSCode.pro ❯ Google Dev Expert ❯ Award-winning Dev Advocate ❯ Node.js Community Committee Member ❯ WordPress Core Dev ❯ TEDx Speaker ❯ Hilarious tech comedian! ❯ Loves @MaedahBatool & 🍕

Discussion

markdown guide
 

Hi Ahmad, thanks to your instructions I was able to set up a simple Azure Function, which sends some JSON to MongoDB Atlas. The function uses Mongoose - just like in your example above.

It works perfectly fine, BUT I have massive cold start times of up to 70 seconds. Did you encounter similar issues? Tomorrow I try to zip the function and deploy it (as described here github.com/Azure/app-service-annou...). Hope this decreases cold start.

 

70 seconds is odd. Must be some issue. Keep digging. Anything beyond 5 sec is something wrong.

Also, glad you liked it. Just release my VSCode.pro course been thinking about a course on serverless after that.

Peace! ✌️

 

Hi Ahmad, the zipping helped! Cold start time is down to 3 seconds max now. When deploying from VS Code the add-in is automatically creating the package, so no issues with long cold starts. Should have used it right from the beginning.

Thanks for this tutorial again! It was very helpful!

Awesome! 💯

Been thinking on making a course on it.

 

Ahmad, one more comment regarding your function. I received the error message

Error: Choose either to return a promise or call 'done'. Do not use both in your script.

Since you are using an async function there is no need to return with "context.done()" since async functions return a promise, anyway.

Right from MS Developer Guide:

When using the JavaScript async function declaration or otherwise returning a JavaScript Promise (not available with Functions v1.x), you do not explicitly need to call the context.done callback to signal that your function has completed. Your function completes when the exported async function/Promise completes.

Edit: I just saw that this is only valid for V2 of Functions. I suppose you were working on V1. Then nevermind ;)