How To Create Node.js Azure Functions

How To Create Node.js Azure Functions

In this Azure tutorial, we will discuss How To Create Node.js Azure Functions. Along with this, we will also discuss a few other topics like How To Create Node.js Azure Functions using Visual Studio Code and also we have discussed Deploy Node js Azure Function To Azure from Visual Studio Code, Call Azure Function From Javascript, Azure Function Console Log, Azure Function npm Install.

How To Create Node.js Azure Functions? We can create the Node.js Azure Functions using the Azure Portal along with the Visual Studio Code IDE.

How To Create Node.js Azure Functions

Here, as part of this functionality, we will create Azure Functions using the Node.js and we will use here the IDE as the Visual Studio Code for our development activities.

Step-1: Login to Azure Portal (https://portal.azure.com/)

Step-2: From the Home page, click on the + Create a resource and from the New Window and then click on “Compute”. Now, choose the “Function App”.

How To Create Azure Function Apps In The Azure Portal

Step-3: Provide the below details on the Create Function App window, on the Basics tag, .

  • Choose your Correct Subscription.
  • Resource GroupChoose your Existing Resource Group and you can create a new one by clicking the Create new link if you don’t have a resource group created till now.
  • Function App name: You need to Provide a valid Function App name.
  • Publish: You can choose the Code option.
  • Runtime stack: Choose the Node.js Option here.
  • Version: You can choose the latest version
  • Region: Select the Region for your Function App.

Click on the Next : Hosting > button now.

How To Create Node.js Azure Functions

On the Hosting tab, choose an existing storage account if you have or else you need to create a new storage account by clicking on the Create new link.

Next is, select the operating system as Windows and Plan type as Consumption (Serverless).

Keep the other configuration as it is and then finally, click on the Review + create button.

Create Node.js Azure Functions

Now it will validate the details for all the fields, then click on the Create button on the next window to create the Azure Function App.

The deployment is completed successfully. Click on the Go to resource button to see the function app that we have created.

What are the Steps To Create Node.js Azure Functions

Now the Azure function App is created successfully.

Steps To Create Node.js Azure Functions
azure functions nodejs

Now Our Function App is ready and now this is the time to create the Azure function now.

Here, there are two approaches to create the Azure Function

First Approach

To create the Azure function, Click on the Functions link from the left navigation and then click on the + Add button on the Azure Function App page.

How to Create Node.js Azure Functions With VS Code IDE

Now we need to choose the trigger for the Azure Function. Choose the HTTP trigger template from the list of templates. Of course, you can choose any of the triggers based on your choice based on your requirement. But for this example, I am choosing here the HTTP trigger.

How to Create Node.js Azure Functions With Visual Studio Code

Now provide a name for the New Function and choose the Authorization level as Function on the New Function window and then finally, click on the Create Function button to create the Azure function.

azure function node.js example
azure function console log

Now you can able to see the Azure function created successfully.

azure function app node.js example
azure functions nodejs example

Now you can click on the Code + Test link to test if the Azure function is working fine and you can able to see the File created and your function code. This is the index.js file code and that is the entry point to the Azure function.

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    const name = (req.query.name || (req.body && req.body.name));
    const responseMessage = name
        ? "Hello, " + name + ". This HTTP triggered function executed successfully."
        : "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.";

    context.res = {
        // status: 200, /* Defaults to 200 */
        body: responseMessage
    };
}
how to create node js azure function
azure functions nodejs tutorial

The below is the Function.json code. All the configuration for the Azure function will be done in this file.

{
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}
Use Azure Functions to write serverless Node.js code on Azure
azure functions node js

Now, if you want to test the function, if it is working fine, click on the Test/Run button from the top. Then select the HTTP method and provide the name value in the body of the function and then click on the Run button

Creating a Simple Azure Function in JavaScript with VS Code
node js azure function

You can able to see below the expected output with the proper response code 200 OK.

Creating a Simple Azure Function in JavaScript with Visual Studio Code

Second Approach

How To Create Node.js Azure Functions using Visual Studio Code

Let’s discuss the second approach to create the Azure function i.e using the Visual Studio Code IDE.

On the Azure Function App page, click on the Switch to classic experience drop-down and then select the Continue to classic experience button from the top navigation.

Creating a Simple Azure Function in Nodejs with Visual Studio Code IDE

Now click on the + New function button as highlighted below to create the Azure function.

how to create node js azure functions
node.js azure tutorial

Select the VS Code as the development tool for the Azure function and then click on the Continue button.

steps to create node js azure functions

Now select the Direct publish option and then click on the Continue button.

azure function javascript http request

As mentioned below you didn’t install all these stuff then you can install Visual Studio Code, Node.js, .NET Core 2.1, and Azure Functions Core Tools, Azure Functions extensions for Visual Studio Code as mentioned below and then click on the Finish button.

azure function nodejs

Once you click on the Install the Azure Functions extension for Visual Studio Code link, it will show you pop up with the message Visual Studio Code is required to install this extension and click on the Continue button.

azure functions node js example c#

Click on the Open Visual Studio Code button to open the Visual Studio Code.

azure functions node.js example c#

Now, It will open the Visual Studio from the local machine with the below pop up. since I have already installed the Azure Functions Extensions so it is showing the Uninstall button for me or else it will show you the Install button to install that in your Visual Studio Code in the below popup.

azure functions node.js example c# Visual Studio Code

Now in Visual Studio Code, click on the Azure button from the left side, it will prompt you to enter your Azure login Credentials, Assuming you are already logged in, now follow the below steps

Click on the Azure button from the left navigation and then click on the Create Function button as highlighted below

How to Create Node.js Azure Functions using VS Code

Then it will ask you to choose a project location, After selecting the project location, Select the language as JavaScript from the below Pop up

How to Create Node.js Azure Functions in VS Code

Now you need to choose the trigger for your Azure Function. Select the HTTP trigger option here.

How to Create Node.js Azure Functions using ViSual Studio Code

Now provide a name for your Azure Function.

How to Create Node js Azure Functions using ViSual studio Code

Select the Authorization Level as Function

How to Create Node js Azure Function using ViSual studio Code

Now if you can able to see the Azure Function Created successfully.

Below is the Code for the index.js file.

Create Node js Azure Function using ViSual studio Code

Here is the code for the function.json file. This is a very important file. This includes all the configurations needed for your Azure Function.

azure functions node js tutorial

Test Node js Azure Function Locally

Now the Azure Function is created. To make sure the function is working as expected. We can test it locally. Press F5 to run the function. Now you can able to see the Azure Function project ran successfully and provided us with the below Azure Function URL.

http://localhost:7071/api/MyNewAzureFunctionVS

How to test the Nodejs Azure Function Locally

Now Open Your Favorite browser and paste the above URL, you can able to see, we got the expected output. We tried executing the below URL with the name value as a query string parameter. http://localhost:7071/api/MyNewAzureFunctionVS?name=Sakti

azure functions node js visual studio code

Deploy Node js Azure Function To Azure from Visual Studio Code

Now to deploy the Node js Azure Function to the Azure, You need to follow the below steps

You can click on the Deploy To function App button as highlighted below.

How to Deploy Node js Azure Function

Or else for the same option, right click on the Function name —-> Click on the Deploy to Function App option as highlighted below.

How to Deploy Node js Azure Function using Visual Studio Code

Now select the Azure Function App that you have created in the Azure Portal. You can search with your Azure Function App name and then select that.

Deploy the Node.Js Azure Function to Azure

The next step is click on the Deploy button from the below Pop up

How to Deploy the Node.Js Azure Function to Azure

Now you can able to see it deployed the Azure Function to the selected Azure Function App successfully.

How to Deploy the Node.Js Azure Function to Azure Portal

Run Node js Azure Function From Package Configuration

After you have deployed the Azure function, you can click on the Website Run from Package option in the Application settings as highlighted. This actually creates a zip file with all the necessary code every time it’s getting deployed. This is one of the best options that really improves the performance of the Nodejs Azure Function.

Run Node js Azure Function From Package Configuration

Call Azure Function From Javascript

Calling the Azure Function from the Javascript is not possible directly. So you need to configure the CORS option in the Azure Portal for your Azure Function App first. To configure the CORS option in Azure Portal Follow the below steps.

Step-1: Login to the Azure Portal (https://portal.azure.com/)

Step-2: Navigate to the Azure Function App, and then click on the CORS from the left navigation.

Call Azure Function From Javascript

Now, add your domain to the list of Allowed Origins and then click on the Save button.

The second thing is If you want to allow all the domain to access your app, you need to remove all domains from the Allowed Origins list and add a “*” to the list as one of the single entry. You can see the below screen shot for the reference.

How to Call Azure Function From Javascript

This is how you can call Azure Function From Javascript. But remember one thing here, in terms of Security, this implementation is not at all a good idea.

Azure Function Console Log

From Azure Function version v2.x, you can use the Console Log for logging trace outputs in your Azure Function. But Problem with the Console Log is, the trace outputs logs are captured only at the Function app level. These logs will not bind to the specific functions so ultimately, you will not find the logs for any specific function which is not at all a good idea.

Now to Overcome this scenario, instead of Console.log, try using the context.log which is one of the best options as of now. You can use the context.log to write the trace output logs to the console in the case of your Azure function.

User context.log instead of console.log in your Azure Function

module.exports = async function (context, req) {
    context.log('Log the Details.');

Console.log in Node.js Azure Function does not work Properly

You might not find the output of your logs easily, If you are using the Console.log in your Azure functions to log the Stack trace outputs, As mentioned above, the logs are captured only at the function app level and will not bind to the Specific function.

so, it will be really difficult for you to find out the logs in terms of any specific Azure function. So instead of the Console.log use the context.log and that will fix your issue for sure.

Azure Function npm Install

For this, you can refer to azure function npm install, which i have posted earlier.

Azure Functions Typescript

Now, easily you can create Azure Functions with Typescript. Azure functions now support the Typescript. Typescript is nothing but a superset of JavaScript that helps you with static typing, different interfaces, and classes that makes the development process much easier.

Create a function in Azure with TypeScript using Visual Studio Code

Well, let’s discuss How to create a typescript Azure Function using Visual Studio Code. Before starting the actual development we should know what are the Prerequisites needed to create the Azure Function using typescript.

Prerequisites

Below are the prerequisites needed to start with the development

  • Make sure you have an Azure subscription or Azure Account. If you don’t have an Azure account as of now, Create a free Azure Account now.
  • Next thing is, you must have Visual Studio Code installed on your machine. If you have not yet installed it, you can install the Visual Studio Code now.
  • Don’t forget to install the Azure Function Extensions for Visual Studio Code.

Assuming you have all the prerequisites needed here, let’s start with creating the Azure Function Project.

Create the Azure Function Project

  • Open the visual studio code IDE and click on the Azure button from the left side and then click on the Create new project button as highlighted below.
Create the Azure Function Project using Visual Studio Code
  • Browse a location where you want to save your Azure Function project.
  • Make sure to choose the language as Typescript as highlighted below.
Create a function in Azure with TypeScript
  • On the next window, select the trigger as per your requirement. Here for the demo perspective, I am choosing the simple and basic trigger that is the HTTP trigger option as highlighted below.
Create a function in Azure with TypeScript using Visual studio code
  • Provide a unique name for your Azure Function Project in the next window and then press Enter.
  • On the next window, choose the Authorization level based on your requirement as highlighted below. The available options are Function, Anonymous, Admin.
How to create a typescript Azure Function using Visual Studio Code

Now, it will take a few seconds to create the Azure Function, You can able to see the project got created successfully, and below is the index.ts file code.

import { AzureFunction, Context, HttpRequest } from "@azure/functions"

const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> {
    context.log('HTTP trigger function processed a request.');
    const name = (req.query.name || (req.body && req.body.name));
    const responseMessage = name
        ? "Hello, " + name + ". This HTTP triggered function executed successfully."
        : "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.";

    context.res = {
        // status: 200, /* Defaults to 200 */
        body: responseMessage
    };

};

export default httpTrigger;

Now if you will press F5 to run the Azure function project, you can able to see that, it ran successfully and provided us the Azure Function URL as highlighted below.

Creating a function in Azure with TypeScript using Visual Studio Code

Test Typescript Azure Function Locally

Now the Azure Function is created. To make sure the function is working as expected. We can test it locally. Press F5 to run the function. Now you can able to see the Azure Function project ran successfully and provided us with the below Azure Function URL.

http://localhost:7071/api/myazuretypescriptfunction

Now Open Your Favorite browser and paste the above URL, you can able to see, we got the expected output.

Test Typescript Azure Function Locally

We tried executing the below URL with the name value as a query string parameter. You can able to see we got the expected output.

How To Test Typescript Azure Function Locally

Deploy Typescript Azure Function To Azure from Visual Studio Code

Since the typescript Azure Function is working properly, So let’s Deploy the typescript Azure Function to the Azure Portal. Follow the below steps to deploy the typescript Azure Function.

You can click on the Deploy To function App button as highlighted below.

How to Deploy Node js Azure Function

Or else for the same option, right-click on the Function name —-> Click on the Deploy to Function App option as highlighted below.

Deploy Typescript Azure Function To Azure from Visual Studio Code

Now select the Azure Function App that you have created in the Azure Portal. You can search with your Azure Function App name and then select that.

Note: Make sure to create an Azure Function App in the Azure Portal. You can refer to the above section to create the Azure Function App in Azure Portal.

How To Deploy Typescript Azure Function To Azure from Visual Studio Code

Now it will take few seconds to deploy the Azure Function to the selected Azure Function App successfully.

Azure Functions Tutorial

You can find out an excellent Azure Functions Tutorial now.

Azure Function JavaScript HTTP Request

A JavaScript or a Node.js Azure function that executes based on the trigger. The context object is the first argument that helps to send or receive data and logging, etc.

You can configure the triggers in the function.json file.

Remember that you must export the JavaScript functions using the module.exports file. index.js file is an important file. Your function runtime always looks for the index.js file. Mainly, the index.js file is the entry point for your JavaScript Azure Function.

Bindings

While working with a JavaScript function, you need to configure the bindings on the function.json file. There are two types of bindings basically in case of the JavaScript function.

  • Input Bindings: Input Bindings are basically divided into two subcategories again.
  1. Trigger Input
  2. Additional Input

You can read Input bindings from the JavaScript function in three formats those are

You can pass as parameter to your function:

The syntax can be like below.

module.exports = async function(context, Trigger1, Input1, Input2) { ... };

This is the recommended approach from Microsoft.

Can be defined as the member of context.bindings object:

The syntax can like below

module.exports = async function(context) { 
    context.log("Trigger: " + context.bindings.Trigger);
    context.log("Input1: " + context.bindings.Input1);
    context.log("Input2: " + context.bindings.Input2);
};

You can also provide as an input passing as an JavaScript argument

The syntax can be like below

module.exports = async function(context) { 
    context.log("Trigger: " + arguments[1]);
    context.log("Input1: " + arguments[2]);
    context.log("Input2: " + arguments[3]);
};
  • Output Bindings

There are different ways to assign data to output bindings.

You can return an Object: This is one of the recommended approach if you are working for multiple outputs. The syntax will be as below

module.exports = async function(context) {
    let rmsg = 'Welcome';
    return {
        httpResponse: {
            body: rmsg 
        },
        queueOutput: rmsg 
    };
};

You can assign values to the context.bindings: The syntax is like below

module.exports = async function(context) {
    let rmsg = 'Welcome';
    context.bindings.httpResponse = {
        body: rmsg
    };
    context.bindings.queueOutput = rmsg;
    return;
};

Check out, Azure Function JavaScript HTTP Request for more information.

Create Azure Function

There are multiple ways to create Azure Functions. You can check out Create Azure Function using Visual Studio Code and PowerShell, Creating AzureFunction using Azure Portal, and How To Create Azure Functions In Visual Studio for more information.

You may also like following the below articles

Wrapping Up

Well, in this article, we have discussed How To Create Node.js Azure Functions, How To Create Node.js Azure Functions using Visual Studio Code and we also discussed Deploy The Node js Azure Function To Azure from Visual Studio Code, Call Azure Function From Javascript, Azure Function Console Log, Azure Function npm Install. Hope you have enjoyed this Article !!!