Events
Mar 17, 9 PM - Mar 21, 10 AM
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register nowThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
This article discusses the differences between version 3 and version 4 of the Node.js programming model and how to upgrade an existing v3 app. If you want to create a new v4 app instead of upgrading an existing v3 app, see the tutorial for either Visual Studio Code (VS Code) or Azure Functions Core Tools. This article uses "tip" alerts to highlight the most important concrete actions that you should take to upgrade your app.
Version 4 is designed to provide Node.js developers with the following benefits:
@azure/functions
npm package. It's versioned independently of the runtime. Both the runtime and the programming model use the number 4 as their latest major version, but that's a coincidence.Version 4 of the Node.js programming model requires the following minimum versions:
@azure/functions
npm package v4.0.0@azure/functions
npm package v4.0.0In v4, the @azure/functions
npm package contains the primary source code that backs the Node.js programming model. In previous versions, that code shipped directly in Azure and the npm package had only the TypeScript types. You now need to include this package for both TypeScript and JavaScript apps. You can include the package for existing v3 apps, but it isn't required.
Tip
Make sure the @azure/functions
package is listed in the dependencies
section (not devDependencies
) of your package.json file. You can install v4 by using the following command:
npm install @azure/functions
In v4 of the programming model, you can structure your code however you want. The only files that you need at the root of your app are host.json and package.json.
Otherwise, you define the file structure by setting the main
field in your package.json file. You can set the main
field to a single file or multiple files by using a glob pattern. The following table shows example values for the main
field:
Example | Description |
---|---|
src/index.js |
Register functions from a single root file. |
src/functions/*.js |
Register each function from its own file. |
src/{index.js,functions/*.js} |
A combination where you register each function from its own file, but you still have a root file for general app-level code. |
Example | Description |
---|---|
dist/src/index.js |
Register functions from a single root file. |
dist/src/functions/*.js |
Register each function from its own file. |
dist/src/{index.js,functions/*.js} |
A combination where you register each function from its own file, but you still have a root file for general app-level code. |
Tip
Make sure you define a main
field in your package.json file.
The trigger input, instead of the invocation context, is now the first argument to your function handler. The invocation context, now the second argument, is simplified in v4 and isn't as required as the trigger input. You can leave it off if you aren't using it.
Tip
Switch the order of your arguments. For example, if you're using an HTTP trigger, switch (context, request)
to either (request, context)
or just (request)
if you aren't using the context.
You no longer have to create and maintain those separate function.json configuration files. You can now fully define your functions directly in your TypeScript or JavaScript files. In addition, many properties now have defaults so that you don't have to specify them every time.
const { app } = require('@azure/functions');
app.http('httpTrigger1', {
methods: ['GET', 'POST'],
authLevel: 'anonymous',
handler: async (request, context) => {
context.log(`Http function processed request for url "${request.url}"`);
const name = request.query.get('name') || (await request.text()) || 'world';
return { body: `Hello, ${name}!` };
},
});
import { app, HttpRequest, HttpResponseInit, InvocationContext } from '@azure/functions';
export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {
context.log(`Http function processed request for url "${request.url}"`);
const name = request.query.get('name') || (await request.text()) || 'world';
return { body: `Hello, ${name}!` };
}
app.http('httpTrigger1', {
methods: ['GET', 'POST'],
authLevel: 'anonymous',
handler: httpTrigger1,
});
Tip
Move the configuration from your function.json file to your code. The type of the trigger corresponds to a method on the app
object in the new model. For example, if you use an httpTrigger
type in function.json, call app.http()
in your code to register the function. If you use timerTrigger
, call app.timer()
.
In v4, the context
object is simplified to reduce duplication and to make writing unit tests easier. For example, we streamlined the primary input and output so that they're accessed only as the argument and return value of your function handler.
You can't access the primary input and output on the context
object anymore, but you must still access secondary inputs and outputs on the context
object. For more information about secondary inputs and outputs, see the Node.js developer guide.
The primary input is also called the trigger and is the only required input or output. You must have one (and only one) trigger.
Version 4 supports only one way of getting the trigger input, as the first argument:
async function httpTrigger1(request, context) {
const onlyOption = request;
async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {
const onlyOption = request;
Tip
Make sure you aren't using context.req
or context.bindings
to get the input.
Version 4 supports only one way of setting the primary output, through the return value:
return {
body: `Hello, ${name}!`
};
async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {
// ...
return {
body: `Hello, ${name}!`
};
}
Tip
Make sure you always return the output in your function handler, instead of setting it with the context
object.
In v4, logging methods were moved to the root context
object as shown in the following example. For more information about logging, see the Node.js developer guide.
context.log('This is an info log');
context.error('This is an error');
context.warn('This is an error');
Version 3 doesn't support creating an invocation context outside the Azure Functions runtime, so authoring unit tests can be difficult. Version 4 allows you to create an instance of the invocation context, although the information during tests isn't detailed unless you add it yourself.
const testInvocationContext = new InvocationContext({
functionName: 'testFunctionName',
invocationId: 'testInvocationId'
});
The HTTP request and response types are now a subset of the fetch standard. They're no longer unique to Azure Functions.
The types use the undici
package in Node.js. This package follows the fetch standard and is currently being integrated into Node.js core.
Body. You can access the body by using a method specific to the type that you want to receive:
const body = await request.text();
const body = await request.json();
const body = await request.formData();
const body = await request.arrayBuffer();
const body = await request.blob();
Header:
const header = request.headers.get('content-type');
Query parameter:
const name = request.query.get('name');
Status:
return { status: 200 };
Body:
Use the body
property to return most types like a string
or Buffer
:
return { body: "Hello, world!" };
Use the jsonBody
property for the easiest way to return a JSON response:
return { jsonBody: { hello: "world" } };
Header. You can set the header in two ways, depending on whether you're using the HttpResponse
class or the HttpResponseInit
interface:
const response = new HttpResponse();
response.headers.set('content-type', 'application/json');
return response;
return {
headers: { 'content-type': 'application/json' }
};
Tip
Update any logic by using the HTTP request or response types to match the new methods.
Tip
Update any logic by using the HTTP request or response types to match the new methods. You should get TypeScript build errors to help you identify if you're using old methods.
See the Node.js Troubleshoot guide.
Events
Mar 17, 9 PM - Mar 21, 10 AM
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register nowDocumentation
Node.js developer reference for Azure Functions
Understand how to develop functions by using Node.js.
Troubleshoot Node.js apps in Azure Functions
Learn how to troubleshoot common errors when you deploy or run a Node.js app in Azure Functions.
Introduction to Developing Serverless Node.js Apps with Azure Functions - JavaScript on Azure
Learn how to develop serverless Node.js applications using Azure Functions. This guide introduces Azure's serverless technologies, enabling you to create scalable, on-demand HTTP endpoints with JavaScript and TypeScript.