Ahmad Awais

NAVIGATE


SHARE


⚡ Practical Guide to Serverless Microsoft Azure Functions with JavaScript

Ahmad AwaisAhmad Awais

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 the 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 the 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 these 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 set up 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.

7 Vscode Shades Of Puple

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.

{
	"disabled": false,
	"bindings": [
		{
			"authLevel": "anonymous",
			"type": "httpTrigger",
			"direction": "in",
			"name": "req"
		},
		{
			"type": "http",
			"direction": "out",
			"name": "res"
		}
	]
}

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.

// FILE: index.js
module.exports = function(context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');
    if (req.query.name || (req.body && req.body.name)) {
        context.res = {
            // status: 200, /* Defaults to 200 */
            body: "Hello " + (req.query.name || req.body.name)
        };
    } else {
        context.res = {
            status: 400,
            body: "Please pass a name on the query string or in the request body"
        };
    }
    context.done();
};

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

This file is pretty much self-explanatory.

// FILE: modeSchema.js
/**
 * Model: Sale
 */
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
// Sale Schema.
const saleSchema = new mongoose.Schema({
    sale_gross: Number,
    earnings: Number,
    currency: String,
    memberSince: Date,
    customerEmail: String,
    event_time: {
        type: Date,
        default: Date.now
    },
});
// Export the model.
module.exports = mongoose.model('Sale', saleSchema);

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.

A high-level overview of the code for this article. It does the following:

Everything is pretty much explained with inline documentation.

// FILE: index.js
/**
 * Azure Function: Sale.
 *
 * Gets data from Paddle.com (which in turn gets data
 * from WordPress) and processes the data, creates a
 * finalData object and saves it in MongoDB Atlas.
 *
 * @param context To pass data between function to / from runtime.
 * @param req HTTP Request sent to the Azure function by Paddle.
 */
module.exports = async function(context, req) {
    // Let's call it log.
    const log = context.log;
    // Log the entire request just for the demo.
    log('[RAN] RequestUri=%s', req.originalUrl);
    /**
     * Azure function Response.
     *
     * Processes the `req` request from Paddle.com
     * and saves the data to MongoDB Atlas while
     * responding the `res` response.
     */
    // Database interaction.
    const mongoose = require('mongoose');
    const DATABASE = process.env.MongodbAtlas;
    // Connect to our Database and handle any bad connections
    mongoose.connect(DATABASE);
    mongoose.Promise = global.Promise; // Tell Mongoose to use ES6 promises
    mongoose.connection.on('error', (err) => {
        context.log(`ERROR→ ${err.message}`);
    });
    // Sale Schema.
    require('./modelSale');
    const Sale = mongoose.model('Sale');
    // Create a Response.
    if (req.query.customFieldName) { // Simple authentication for the purpose of demo.
        // Build the data we need.
        const sale_gross = req.query.p_sale_gross || '0';
        const earnings = JSON.parse(req.query.p_earnings)['16413'] || '0'
        const currency = req.query.p_currency || 'USD';
        const memberSince = req.query.memberSince || new Date();
        const customerEmail = req.query.customerEmail || '';
        const event_time = new Date();
        log('[OUTPUT]—— sale_gross: ' + sale_gross);
        log('[OUTPUT]—— earnings: ' + earnings);
        log('[OUTPUT]—— currency: ' + currency);
        const finalData = {
            sale_gross: sale_gross,
            earnings: earnings,
            currency: currency,
            memberSince: memberSince,
            customerEmail: customerEmail,
            event_time: event_time,
        }
        // Save to db.
        const sale = await (new Sale(finalData))
            .save();
        log("[OUTPUT]—— SALE SAVED: ", sale);
        // Respond with 200.
        context.res = {
            status: 200,
            body: "Thank You for the payment! " + (req.query.customFieldName || req.body.customFieldName)
        };
    } else {
        context.res = {
            status: 400,
            body: "Please pass a name on the query string or in the request body"
        };
    }
    // Informs the runtime that your code has finished. You must call context.done, or else the runtime never knows that your function is complete, and the execution will time out.
    // @link: https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-node#contextdone-method
    context.done();
};

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.

GIF for MongoDB Atlas, Microsoft Azure, & Serverless Functions

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!

— So, yes, try out Microsoft Azure functions and share your thoughts below, over to you!


📺#

Folks, I just found out that this post was featured in Azure Functions Live by the Azure Functions Team. They said some really nice stuff about it. Check it out below.

Founder & CEO at Langbase.com · Ex VP DevRel Rapid · Google Developers Advisory Board (gDAB) founding member. 🧑‍💻 AI/ML/DevTools Angel InvestorAI/ML Advisory Board member San Francisco, DevNetwork

🎩 Award-winning Open Source Engineer & Dev Advocate 🦊 Google Developers Expert Web DevRel 🚀 NASA Mars Ingenuity Helicopter mission code contributor 🏆 8th GitHub Stars Award recipient with 3x GitHub Stars Award (Listed as GitHub's #1 JavaScript trending developer).

🌳 Node.js foundation Community Committee Outreach Lead, Member Linux Foundation, OpenAPI Business Governing Board, and DigitalOcean Navigator. 📟 Teaching thousands of developers Node.js CLI Automation (100 videos · 22 Projects) & VSCode.pro course. Over 142 Million views, 22 yrs Blogging, 56K developers learning, 200+ FOSS.

✌️ Author of various open-source dev-tools and software libraries utilized by millions of developers worldwide WordPress Core Developer 📣 TEDx Speaker with 100+ international talks.

As quoted by: Satya Nadella · CEO of Microsoft — Awais is an awesome example for developers.
🙌 Leading developers and publishing technical content for over a decade 💜 Loves his wife (Maedah) ❯ Read more about Ahmad Awais.

👋… Awais is mostly active on Twitter @MrAhmadAwais

📨

Developers Takeaway

Stay ahead in the web dev community with Ahmad's expert insights on open-source, developer relations, dev-tools, and side-hustles. Insider-email-only-content. Don't miss out - subscirbe for a dose of professional advice and a dash of humor. No spam, pinky-promise!

✨ 172,438 Developers Already Subscribed
Comments 5
  • Mian Shahzad Raza
    Posted on

    Mian Shahzad Raza Mian Shahzad Raza

    Reply Author

    Thank you for this guide ✌


  • Charles Dilip
    Posted on

    Charles Dilip Charles Dilip

    Reply Author

    Really useful information, Thanks.


  • Chris
    Posted on

    Chris Chris

    Reply Author

    Nice article, The use of gifs and full screen width really makes this one stand out! Great job!