Facebook Business SDK for NodeJS

repository·main·Indexed 20 days ago

https://github.com/facebook/facebook-nodejs-business-sdk

A unified Javascript and Node.js library for the Facebook Marketing API, bundling multiple APIs including Marketing, Pages, Business Manager, and Instagram. Version 25.0.3 provides CRUD operations for Facebook objects, pagination via Cursors, batch API requests through FacebookAdsApiBatch, and a server-side client for the Conversions API with a built-in Parameter Builder for automatic event parameter extraction.

Tokens
6.5K
Snippets
20
Records
23
Agent score
70%

What's inside facebook-nodejs-business-sdk

  1. Auto-fill event parameters with Conversions API Parameter Builder

    main

    The SDK includes the Conversions API Parameter Builder to automatically extract key event parameters from incoming HTTP requests. By calling .setRequestContext(request) on a ServerEvent, the SDK can auto-fill missing fields such as user_data.fbc, user_data.fbp, user_data.client_ip_address, event_source_url, and referrer_url at the time of sending.

    Key Behaviors:

    • Non-destructive: If you manually set a value, the Parameter Builder will not overwrite it.
    • Automatic Hashing: Customer information (email, phone, etc.) in UserData is automatically normalized and SHA-256 hashed.
    • Gated by Preference: You can control which fields are allowed to be auto-filled using the Preference class.
    const Preference = bizSdk.Preference;
    
    const serverEvent = (new ServerEvent())
      .setEventName('Purchase')
      .setEventTime(Math.floor(Date.now() / 1000))
      .setUserData((new UserData()).setEmail('joe@eg.com'))
      .setActionSource('website')
      .setRequestContext(request);
    
    // Optional: gate which fields may be auto-filled (all default true).
    // Order: fbc, fbp, client_ip_address, referrer_url, event_source_url.
    // .setRequestContext(request, new Preference(true, true, true, true, false));
  2. Handle Pagination with Cursors

    main

    When fetching collections (Edges), the SDK returns a Cursor object. A Cursor is a specialized Array that includes hasNext() and hasPrevious() methods, as well as next() and previous() methods which return Promises that resolve to the next set of objects.

    To iterate through all objects in a collection, use a while loop with await campaigns.next().

    const adsSdk = require('facebook-nodejs-business-sdk');
    const AdAccount = adsSdk.AdAccount;
    const Campaign = adsSdk.Campaign;
    const account = new AdAccount('act_<AD_ACCOUNT_ID>');
    
    void async function () {
        let campaigns = await account.getCampaigns([Campaign.Fields.name], {limit: 20});
        campaigns.forEach(c => console.log(c.name));
        
        while (campaigns.hasNext()) {
            campaigns = await campaigns.next();
            campaigns.forEach(c => console.log(c.name));
        }
    }();
  3. How Facebook Objects and Fields work

    main

    Facebook entities (like AdAccount, Campaign, etc.) are represented as classes. To ensure maintainability and type safety, each class provides enum-like field objects (e.g., Campaign.Fields) to reference valid property names.

    When performing operations like read, create, or update, you should use these field constants instead of raw strings to avoid errors.

    const adsSdk = require('facebook-nodejs-business-sdk');
    const AdAccount = adsSdk.AdAccount;
    const Campaign = adsSdk.Campaign;
    const account = new AdAccount('act_<AD_ACCOUNT_ID>');
    
    // Accessing fields as properties
    console.log(account.id);
  4. Read, Create, Update, and Delete Facebook Objects

    main

    The SDK provides standard CRUD methods on object instances.

    Note: When reading objects, only request the fields you actually need to minimize response time.

    Read: Use .read([Fields...]). Create: Use .create([Fields...], { data }). Update: Instantiate a new object with the ID and data, then call .update(). Delete: Call .delete() on an existing instance.

    const adsSdk = require('facebook-nodejs-business-sdk');
    const accessToken = '<VALID_ACCESS_TOKEN>';
    const api = adsSdk.FacebookAdsApi.init(accessToken);
    const AdAccount = adsSdk.AdAccount;
    const Campaign = adsSdk.Campaign;
    const account = new AdAccount('act_<AD_ACCOUNT_ID>');
    
    // Read
    account.read([AdAccount.Fields.name, AdAccount.Fields.age])
      .then((account) => console.log(account))
      .catch((error) => console.error(error));
    
    // Create
    account.createCampaign(
      [Campaign.Fields.name, Campaign.Fields.status, Campaign.Fields.objective],
      {
        [Campaign.Fields.name]: 'Page likes campaign',
        [Campaign.Fields.status]: Campaign.Status.paused,
        [Campaign.Fields.objective]: Campaign.Objective.page_likes
      }
    )
    .then((campaign) => {})
    .catch((error) => {});
    
    // Update
    const campaignId = '<CAMPAIGN_ID>';
    new Campaign(campaignId, {
      [Campaign.Fields.id]: '<CAMPAIGN_ID>',
      [Campaign.Fields.name]: 'Campaign - Updated'
    }).update();
    
    // Delete
    new Campaign(campaignId).delete();
  5. Configure an APIRequest instance

    main

    The APIRequest class is used to construct the details of a Facebook Business API call. It is initialized with a nodeId, an HTTP method (e.g., GET, POST), and an endpoint (the edge of the API call).

    Key properties available via getters:

    • nodeId: The ID of the node being acted upon.
    • method: The HTTP method.
    • endpoint: The edge/endpoint string.
    • path: The full path array (nodeId + endpoint).
    • fields: The list of requested fields.
    • params: A deep-cloned object of the request parameters.
    • fileParams: A deep-cloned object of the file parameters.
    // Conceptual initialization (internal usage via SDK)
    const request = new APIRequest('12345', 'GET', '/me');
  6. Manage object edges and pagination

    main

    Facebook objects often have related entities known as 'edges'. The AbstractCrudObject provides methods to interact with these relationships.

    Get Paginated Edges

    Use getEdge() to retrieve a collection of related objects. This method returns a Cursor object, which is used for paginating through results.

    • targetClass: The class constructor for the objects in the edge.
    • fields: Array of fields to include in the edge objects.
    • params: Additional query parameters.
    • fetchFirstPage: If true, it immediately executes the first request and returns the first page of results.

    Create and Delete Edges

    • createEdge(endpoint, fields, params, targetClassConstructor, ...): Creates a new related object at the specified endpoint. If targetClassConstructor is provided, it returns an instance of that class.
    • deleteEdge(endpoint, params, basePath): Deletes a specific edge relationship.
    // Example: Getting a paginated edge of 'comments'
    const commentsCursor = myPost.getEdge(Comment, ['id', 'message'], {}, true, 'comments');
    
    // Example: Creating a new edge
    await myPost.createEdge('comments', ['message'], { message: 'Hello!' }, Comment);
  7. Use FacebookAdsApiBatch for batch API requests

    main

    The FacebookAdsApiBatch class allows you to group multiple API calls into a single HTTP request to the Facebook Graph API. This is more efficient than making individual requests.

    Workflow

    1. Initialize: Create a new instance of FacebookAdsApiBatch passing an existing FacebookAdsApi instance.
    2. Queue Calls: Use .add() or .addRequest() to add individual API calls to the batch.
    3. Execute: Call .execute() to send the batch. This returns a Promise that resolves when the batch is processed.
    4. Handle Results: Each call in the batch can have its own successCallback and failureCallback which are triggered individually based on the response of that specific sub-request.

    Error Handling

    Individual exceptions within the batch are not thrown by .execute(). Instead, you should use the failureCallback provided during the .add() phase to handle errors for specific calls. If a response is missing entirely, .execute() may return a new FacebookAdsApiBatch instance containing only the failed/missing requests for retry purposes.

    import FacebookAdsApi from './api';
    import FacebookAdsApiBatch from './api-batch';
    
    const api = FacebookAdsApi.init('YOUR_ACCESS_TOKEN');
    const batch = new FacebookAdsApiBatch(api);
    
    // Add a GET request
    batch.add('GET', ['me'], { fields: 'id,name' }, null, (response) => {
      console.log('Success:', response);
    }, (error) => {
      console.error('Failed:', error);
    });
    
    // Add a POST request
    batch.add('POST', ['me/feed'], { message: 'Hello world' }, null, (response) => {
      console.log('Post Success:', response);
    });
    
    // Execute the batch
    await batch.execute();
  8. Perform CRUD operations on Facebook Business objects

    main

    The AbstractCrudObject (and classes extending it) provides methods to interact with Facebook's Graph API for specific business entities. These methods handle the underlying HTTP calls and manage object state.

    Core CRUD Methods

    • read(fields, params): Fetches the latest data for the object. Pass an array of fields to specify which properties to retrieve. Returns a Promise that resolves to the updated object instance.
    • update(params): Sends a POST request to update the object. It automatically includes any changes made to the object's properties since the last read or setData call via exportData().
    • delete(params): Sends a DELETE request to remove the object.

    Managing Changes

    When you modify properties on a CRUD object, the SDK tracks these changes internally.

    • Use exportData() to see only the fields that have changed.
    • Use exportAllData() to see the full object state.
    • Use clearHistory() to reset the change tracker.
    • Use setData(data) to overwrite the object with new data from the server, which also clears the change history.
    // Example: Updating an object
    const myObject = await MyBusinessObject.get(id);
    myObject.name = 'New Name'; // This tracks the change
    await myObject.update(); // Sends the POST request with the change
    
    // Example: Reading specific fields
    await myObject.read(['id', 'name', 'status']);
  9. Use the Conversions API to send server-side events

    main

    The SDK provides a server-side client for the Conversions API, allowing you to send web, app, and offline events directly from your server to Meta. To send an event, you must initialize the API with an access token, construct UserData and CustomData objects, wrap them in a ServerEvent, and finally execute the request using EventRequest with your Pixel ID.

    const bizSdk = require('facebook-nodejs-business-sdk');
    const ServerEvent = bizSdk.ServerEvent;
    const EventRequest = bizSdk.EventRequest;
    const UserData = bizSdk.UserData;
    const CustomData = bizSdk.CustomData;
    
    bizSdk.FacebookAdsApi.init('<ACCESS_TOKEN>');
    
    const userData = (new UserData())
      .setEmail('joe@eg.com')
      .setClientIpAddress(request.connection.remoteAddress)
      .setClientUserAgent(request.headers['user-agent']);
    
    const customData = (new CustomData())
      .setCurrency('usd')
      .setValue(123.45);
    
    const serverEvent = (new ServerEvent())
      .setEventName('Purchase')
      .setEventTime(Math.floor(Date.now() / 1000))
      .setUserData(userData)
      .setCustomData(customData)
      .setEventSourceUrl('http://jaspers-market.com/product/123')
      .setActionSource('website');
    
    const response = await (new EventRequest('<ACCESS_TOKEN>', '<PIXEL_ID>'))
      .setEvents([serverEvent])
      .execute();
    console.log(response);
  10. Enable Debug Mode for API requests

    main

    To log all outgoing requests made by the SDK, call api.setDebug(true) on your initialized FacebookAdsApi instance.

    const adsSdk = require('facebook-nodejs-business-sdk');
    const accessToken = '<VALID_ACCESS_TOKEN>';
    const api = adsSdk.FacebookAdsApi.init(accessToken);
    api.setDebug(true);
  11. Initialize the FacebookAdsApi

    main

    The FacebookAdsApi object is the foundation of the SDK. It encapsulates the logic to execute requests against the Graph API. You must initialize it with a valid access token before making API calls.

    const adsSdk = require('facebook-nodejs-business-sdk');
    const accessToken = '<VALID_ACCESS_TOKEN>';
    const api = adsSdk.FacebookAdsApi.init(accessToken);