Upgrade to version 4 of the Node.js programming model for Azure Functions

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 brand new v4 app instead of upgrading an existing v3 app, see the tutorial for either VS Code or Azure Functions Core Tools. This article uses "TIP" sections to highlight the most important concrete actions you should take to upgrade your app.

Version 4 was designed with the following goals in mind:

  • Provide a familiar and intuitive experience to Node.js developers
  • Make the file structure flexible with support for full customization
  • Switch to a code-centric approach for defining function configuration

Considerations

Note

Version 4 of the Node.js programming model is currently in public preview.

  • During preview, the v4 model requires you to set the app setting AzureWebJobsFeatureFlags to EnableWorkerIndexing. For more information, see Enable v4 programming model.
  • The Node.js "programming model" shouldn't be confused with the Azure Functions "runtime".
    • Programming model: Defines how you author your code and is specific to JavaScript and TypeScript.
    • Runtime: Defines underlying behavior of Azure Functions and is shared across all languages.
  • The programming model version is strictly tied to the version of the @azure/functions npm package, and is versioned independently of the runtime. Both the runtime and the programming model use "4" as their latest major version, but that is purely a coincidence.
  • Keep in mind that you can't mix the v3 and v4 programming models in the same function app. As soon as you register one v4 function in your app, any v3 functions registered in function.json files are ignored.

Requirements

Version 4 of the Node.js programming model requires the following minimum versions:

Include the npm package

For the first time, 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 only had the TypeScript types. Moving forward, you 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 with the command

npm install @azure/functions@preview

Set your app entry point

In v4 of the programming model, you can structure your code however you want. The only files 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. The main field can be set to a single file or multiple files by using a glob pattern. Common values for the main field may be:

  • TypeScript
    • dist/src/index.js
    • dist/src/functions/*.js
  • JavaScript
    • src/index.js
    • src/functions/*.js

Tip

Make sure you define a main field in your package.json file

Switch the order of arguments

The trigger input is now the first argument to your function handler instead of the invocation context. The invocation context, now the second argument, was simplified in v4 and isn't as required as the trigger input - it can be left off if you aren't using it.

Tip

Switch the order of your arguments. For example if you are using an http trigger, switch (context, request) to either (request, context) or just (request) if you aren't using the context.

Define your function in code

Say goodbye 👋 to function.json files! All of the configuration that was previously specified in a function.json file is now defined directly in your TypeScript or JavaScript files. In addition, many properties now have a default so that you don't have to specify them every time.

const { app } = require("@azure/functions");

app.http('helloWorld1', {
  methods: ['GET', 'POST'],
  handler: async (request, context) => {
    context.log('Http function processed request');

    const name = request.query.get('name') 
      || await request.text() 
      || 'world';

    return { body: `Hello, ${name}!` };
  }
});

Tip

Move the config from your function.json file to your code. The type of the trigger will correspond to a method on the app object in the new model. For example, if you use an httpTrigger type in function.json, you will now call app.http() in your code to register the function. If you use timerTrigger, you will now call app.timer() and so on.

Review your usage of context

The context object has been simplified to reduce duplication and make it easier to write unit tests. For example, we streamlined the primary input and output so that they're only accessed as the argument and return value of your function handler. The primary input and output can't be accessed 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.

Get the primary input as an argument

The primary input is also called the "trigger" and is the only required input or output. You must have one and only one trigger.

v4 only supports one way of getting the trigger input, as the first argument.

async function helloWorld1(request, context) {
  const onlyOption = request;

Tip

Make sure you aren't using context.req or context.bindings to get the input.

Set the primary output as your return value

v4 only supports one way of setting the primary output, through the return value.

return { 
  body: `Hello, ${name}!` 
};

Tip

Make sure you are always returning the output in your function handler, instead of setting it with the context object.

Create a test context

v3 doesn't support creating an invocation context outside of the Azure Functions runtime, making it difficult to author unit tests. v4 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'
});

Review your usage of HTTP types

The http request and response types are now a subset of the fetch standard instead of being types unique to Azure Functions. The types use Node.js's undici package, which follows the fetch standard and is currently being integrated into Node.js core.

HttpRequest

  • Body. You can access the body using a method specific to the type you would like 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 param:
    const name = request.query.get('name');
    

HttpResponse

  • Status:
    return { status: 200 };
    
  • Body:
    return { body: "Hello, world!" };
    
  • Header. You can set the header in two ways, depending if you're using the HttpResponse class or 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 using the http request or response types to match the new methods. If you are using TypeScript, you should receive build errors if you use old methods.

Troubleshooting

If you see the following error, make sure you set the EnableWorkerIndexing flag and you're using the minimum version of all requirements:

No job functions found. Try making your job classes and methods public. If you're using binding extensions (e.g. Azure Storage, ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. builder.AddAzureStorage(), builder.AddServiceBus(), builder.AddTimers(), etc.).