0
0
AzureHow-ToBeginner · 4 min read

How to Use Azure Function with Node.js: Simple Guide

To use Azure Functions with Node.js, create a function app in Azure, write your JavaScript code in the function's index.js, and deploy it. Azure Functions run your Node.js code in response to events like HTTP requests, making serverless apps easy to build.
📐

Syntax

An Azure Function in Node.js typically exports a function that takes context and req parameters. context manages the function's runtime and logging, while req contains the incoming request data.

The basic syntax looks like this:

  • module.exports = async function (context, req) { ... } defines the function.
  • context.log() logs messages.
  • context.res sets the HTTP response.
javascript
module.exports = async function (context, req) {
  context.log('Node.js HTTP trigger function processed a request.');
  const name = (req.query.name || (req.body && req.body.name));
  context.res = {
    status: 200,
    body: name ? `Hello, ${name}!` : "Please pass a name on the query string or in the request body"
  };
};
💻

Example

This example shows a simple HTTP-triggered Azure Function in Node.js that greets a user by name. It reads the name from the query string or request body and returns a greeting message.

javascript
module.exports = async function (context, req) {
  context.log('Processing request...');
  const name = (req.query.name || (req.body && req.body.name));
  context.res = {
    status: 200,
    body: name ? `Hello, ${name}!` : "Please pass a name on the query string or in the request body"
  };
};
Output
HTTP 200 OK Body: Hello, Alice! (if ?name=Alice is passed)
⚠️

Common Pitfalls

Common mistakes when using Azure Functions with Node.js include:

  • Not setting context.res properly, causing no response to be sent.
  • Forgetting to handle asynchronous code with async/await or promises, leading to premature function exit.
  • Not reading input from both query parameters and request body.
  • Logging too much or too little, making debugging harder.
javascript
/* Wrong: Missing context.res causes timeout */
module.exports = async function (context, req) {
  context.log('No response set');
};

/* Right: Proper response set */
module.exports = async function (context, req) {
  context.res = { status: 200, body: "OK" };
  context.log('Response sent');
};
📊

Quick Reference

ConceptDescription
module.exportsExports the function to Azure runtime
contextManages logs, response, and function state
reqIncoming HTTP request data
context.resSets HTTP response status and body
async functionAllows use of await for async operations

Key Takeaways

Always set context.res to send a response in your Azure Function.
Use async/await to handle asynchronous code cleanly in Node.js functions.
Read input from both query parameters and request body for flexibility.
Use context.log for helpful debugging messages.
Export your function with module.exports for Azure to run it.