Bubble Docs
  • Introduction
  • New? Start Here
  • What is Bubble?
  • The Glossary
  • User manual
    • Getting started
      • What is Bubble?
      • Building your first app
        • Planning features
        • Database structure
        • Design and UX
        • eCommerce and payments
          • Shopping cart
          • Checkout page
          • One-time payments
          • Subscriptions
          • Marketplace
      • Creating and managing apps
      • The Bubble editor
        • Tabs and sections
          • Design tab
            • The element tree
            • The property editor
          • Workflow tab
          • Data tab
          • Styles tab
          • Plugins tab
          • Settings tab
            • Application settings
              • Custom headers/body
              • Visual settings
              • Social media sharing
              • Translating your app
              • Email settings
              • Collaboration
            • Custom domain and DNS
          • Logs tab
        • Tools
          • Key features
          • The search tool
          • The Issue Checker
          • The element tree
          • The element property editor
          • The debugger
          • Notes
        • Previewing your app
      • Transitioning to Bubble from...
        • JavaScript
        • HTML and CSS
        • SQL
    • Design
      • Elements
        • The element hierarchy
          • The element tree
        • The page
        • Containers
          • Groups
          • Repeating groups
          • Table elements
          • Popups
          • Floating groups
          • Group focus
        • Visual elements
        • Input forms
          • Text and numbers
          • Dates and time
          • File uploads
          • Selection controls
        • Reusable Elements
      • Styling
        • Color variables
        • Font variables
        • Styles
        • Custom Fonts
      • Responsive design
        • Building responsive pages
        • Legacy articles
          • The Basics (Legacy)
          • Building Responsive Pages (Legacy)
          • Migrating Legacy Pages
          • Tips When Designing (Legacy)
      • Templates
      • The Component Library
      • Importing from Figma
    • Data
      • The database
        • Data types and fields
        • Creating, saving and deleting data
        • Finding data
        • Displaying data
        • Protecting data with privacy rules
        • The database editor
        • Export/import data
          • Exporting data
          • Importing data (CSV)
        • Working with location data
        • Using Algolia
        • Database structure by app type
          • Marketplace Apps
          • Directory & Listings Apps
          • Social Network Apps
          • SaaS Apps
          • Project Management Apps
          • CRM Apps
          • Professional Services Apps
          • On-demand Apps
          • Documentation/ CMS Apps
          • Applicant Tracking System (ATS) Apps
          • Portfolio Apps
          • Gallery Apps
          • Online Store / Ecommerce Apps
          • Blog Apps
          • Messaging App
          • Dashboards
          • Building Block Apps
          • Bubble as a backend
      • Files
      • Images
      • Static data
        • App texts (translations)
        • Option sets
      • Temporary data
        • Custom states
        • URL parameters
      • User accounts
        • Authentication plugins
          • Facebook plugin
          • Fitbit plugin
          • Google plugin
          • Instagram plugin
          • LinkedIn plugin
          • Pinterest plugin
          • Slack plugin
          • Wistia plugin
          • YouTube plugin
        • Cookies set by Bubble
      • Time, dates and time zones
    • Logic
      • The frontend and backend
      • Workflows
        • Events
          • Frontend events
            • Recurring workflows
            • Custom events
          • Backend events
            • Database trigger events
        • Actions
        • API Workflows
      • Dynamic expressions
      • Conditions
      • Navigation
        • Single-page applications (SPA)
        • Multi-page applications
        • Page slugs
    • Workload
      • Understanding workload
        • Activity types
        • The workload calculation
        • Client-side and server-side processing
      • Tracking workload
        • Measuring
          • Using App Metrics
        • Monitoring
          • Workload notifications
          • Infinite recursion protection
      • Optimizing workload
        • Optimization framework
        • Optimization checklist
          • Page load
          • Searches
          • Workflows and actions
          • Backend workflows
        • Agency showcases
          • Minimum Studio
          • Neam
          • Support Dept
    • Security
      • Bubble's security features
      • Planning app security
      • Client-side and server-side
      • Bubble account security
      • App security
      • Page security
      • Database security
      • API security
        • API Connector security
        • Data API security
        • Workflow API security
      • Flusk
        • Overview
        • Flusk plan features
        • Getting started with Flusk
        • Flusk security tools
          • The Issues Explorer
          • Issue details
          • Tools and settings
            • Pages rating
            • Database rating
        • Flusk FAQ
      • Cookies
      • Security checklist
    • Publishing your app
      • Web app
      • Native mobile app
        • Global native mobile settings
        • iOS App Store
        • Google Play Store
        • Publishing FAQ
    • AI
      • Generate apps with AI
        • About AI app generation
      • AI page designer
      • Connect to AI agents
    • Maintenance
      • Collaborators
      • Version control
        • Best practices: Version control
        • Transitioning from the legacy version control
        • Terminology: Version control
        • Version Control (legacy)
      • Commenting
      • Database maintenance
        • Copying the database
        • Restoring database backups
        • Bulk operations
          • Bulk operation methods compared
        • Wiping change history
      • Performance
        • Hard limits
        • Capacity Usage (legacy)
        • Notes on queries
      • SEO
        • Introduction to SEO
        • SEO: App
        • SEO: Page
      • Testing and debugging
        • Introduction to testing and debugging
        • The debugger
        • The server logs
        • Supported browsers
      • API workflow scheduler
    • Integrations
      • API
        • Introduction to APIs
          • What is a RESTful API?
        • The Bubble API
          • Bubble API terminology
          • Authentication
            • How to authenticate
            • No authentication
            • As a User
            • As an admin
          • The Data API
            • Data API Privacy Rules
            • Data API endpoints
            • Data API requests
          • The Workflow API
            • Workflow API privacy rules
            • Workflow API endpoints
            • API workflows
              • Creating API workflows
              • Scheduling API workflows
              • Recursive API workflows
              • API Workflow Scheduler
              • Case: Stripe notifications
        • The API Connector
          • Authentication
          • API Connector security
          • API guides
            • OpenAI
              • Authentication
              • Calls
                • ChatGPT
                  • Chat
            • Google Translate
              • How to setup Google API keys
          • Streaming API
        • API security
        • Plugins that connect to APIs
        • API Glossary
      • Plugins
        • What Plugins Can Do
        • Installing and using Plugins
        • Authentication plugins
        • Special Plugins
      • SQL Database Connector
      • Bubble App Connector
      • WorkOS
        • WorkOS SSO
        • WorkOS API
    • Infrastructure
      • Sub-apps
      • Bubble release tiers
      • Hosting and scaling
        • How Bubble hosting works
        • Scaling with Bubble
        • CDN (Cloudflare)
        • Bubble app names
        • Domain and DNS
      • Compliance
        • GDPR
        • SOC 2 Type II
        • HIPAA
        • Other frameworks and standards
    • Bubble for Enterprise
      • Hosting and infrastructure
        • Dedicated instance
          • The Dedicated editor experience
          • Technical specs
          • Main cluster dependencies
          • Customizable options
          • Migration process
            • Pre-migration
            • During migration
            • Post-migration
      • Security and compliance
        • Single sign-on (SSO)
        • GDPR
        • SOC 2 Type II
        • HIPAA
        • Other frameworks
        • Bubble's security features
      • Admin and collaboration
      • Priority support
      • Billing and Payment Guideline for Dedicated Instances
  • Core Reference
    • Using the core reference
    • Bubble's Interface
      • Design tab
      • Design tab (Legacy)
      • Workflow tab
      • Data tab
      • Styles tab
      • Styles tab (Legacy)
      • Plugins tab
      • Settings tab
      • Logs tab
      • Template tab
      • Toolbar
      • Top and context menu options
      • Deployment and version control
        • Deployment & Version Control Dropdown (legacy)
      • Notes
    • Elements
      • General properties
      • General properties (Legacy)
      • Styling properties
      • Styling Properties (Legacy)
      • Responsive Properties
      • Responsive Properties (Legacy)
      • Conditional formatting
      • States
      • Page Element
        • Page Element (Legacy)
      • Visual Elements
      • Containers
      • Container Layout Types
      • Containers (Legacy)
      • Input Forms
      • Reusable Elements
      • Element Templates (legacy)
    • Workflows
    • Events
      • General events
      • Element events
      • Custom events
      • Recurring event
      • Database trigger event
    • Actions
      • Account
      • Navigation
      • Data (things)
      • Email
      • Element
      • Custom
    • Data
      • Data Sources
      • Operators and comparisons
      • Search
      • Privacy
    • Styles
    • API
      • The Bubble API
        • The Data API
          • Authentication
          • Data API endpoints
          • Data API requests
        • The Workflow API
      • The API Connector
        • Authentication
        • Adding calls
    • Bubble-made Plugins
      • AddtoAny Share Buttons
      • Airtable
      • API Connector
      • Blockspring
      • Box
      • Braintree
      • Bubble App Connector
      • Chart.js
      • Circle Music Player
      • Draggable Elements
      • Dropzone
      • Facebook
      • Fitbit
      • Full Calendar
      • Google
      • Google Analytics
      • Google Optimize
      • Google Places
      • Ionic Elements
      • iTunes
      • Slidebar Menu
      • LinkedIn
      • Localize Translation
      • Mixpanel
      • Mouse & Keyboard Interactions
      • Multiselect Dropdown
      • Progress Bar
      • Rich Text Editor
      • Rich Text Editor (Legacy)
      • Screenshotlayer
      • SelectPDF
      • Slack
      • Segment
      • Slick Slideshow
      • SQL Database Connector
      • Star Rating
      • Stripe
      • Tinder-like Element
      • Twitter
      • YouTube
      • Zapier
    • Application Settings
      • App plan
      • General
      • Domain / email
      • Languages
      • SEO / metatags
      • API
      • Collaboration
      • Sub-apps
      • Versions
  • Account & Marketplace
    • Account and billing
      • Pricing and plans
        • Plans and billing
        • Billing cycle
        • FAQ: Pricing and Workload
      • Account Management
      • Building Apps for Others
      • Selling on the Marketplace
      • Plans & Billing (legacy)
    • Official Bubble Certification
      • Hiring certified developers
    • Building Plugins
      • The Plugin Editor
      • General Settings
      • Updating to Plugin API v4
      • Adding API Connections
      • Building Elements
      • Building Actions
      • Loading Data
      • Publishing and versioning
      • Github Integration
    • Building Templates
    • Application and data ownership
    • Marketplace policies
    • Bug reports
  • Vulnerability Disclosure Policy
  • Beta features
    • About the Beta features section
    • Native mobile apps 🔒
      • Introduction
        • What is a native mobile app?
        • Native mobile vs. web development
        • Differences in native and web elements
        • Native mobile app terminology
      • Building
        • Views and navigation
        • Native mobile actions
        • Components and gestures
        • Device resources
          • Location services
          • Camera/photo library
      • Previewing
      • Publishing
Powered by GitBook
On this page
  • Changes
  • Step-by-step guide
  • Examples
  • context.request: Versions 3 and below plugin API
  • context.request: Updated plugin API
  • .length(): Current plugin API
  • .length(): Updated plugin API
  • Using node-fetch instead of context.request
  • Using promises instead of context.async
  • Using utils.promisify instead of context.async
  • Change log

Was this helpful?

  1. Account & Marketplace
  2. Building Plugins

Updating to Plugin API v4

This documentation covers how to update your server-side actions to be compatible with plugin API v4, which runs on Node 18.

Last updated 1 year ago

Was this helpful?

Node 18 removes support for the Fibers extension, which allowed the existing version of the server-side actions API to expose functions that returned results directly, rather than as Promises. Consequently, some API functions will change in a non-backwards-compatible way.

If your plugin uses any server-side actions from the versions 3 and below, you will have to manually update your plugin to be compatible with the updated version.

This document explains in detail what the plugin API looks like and how to update plugins on the plugin API versions 3 and below to work with the updated plugin API. In most cases, the necessary changes will be straightforward.

What's the difference between the Fibers extension and Promises?

Fibers and Promises have two different approaches to handling asynchronous operations.

The Fibers extension (old) lets you write asynchronous code in a more synchronous-looking way. By using Fibers, you can pause and resume the execution of your code at certain points, effectively making it appear as if the asynchronous tasks are running synchronously. This can make the code easier to read and understand, as it resembles typical synchronous code flow.

Promises (new), on the other hand, are a native JavaScript feature for managing asynchronous operations. They represent the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises provide a more standardized approach to handling asynchronous tasks, allowing you to chain operations, handle errors, and improve the overall structure of your code.

Changes

Function Name
Old API
New API

context.request

context.request

context.v3.request

context.async

context.async

context.v3.async

.get method on Bubble Things

.get method

.get method (returns promise)

.get method on Bubble Lists

.get method

.get method (returns promise)

.length method on Bubble Lists

.length method

.length method (returns promise)

get_object_from_id

get_object_from_id

context.getThingById

get_objects_from_ids

get_objects_from_ids

context.getThingsById

These functions now return a promise for their original return value (see on promises). If you have a server-side action that uses any of these functions in your plugin, the action will break when you update. See below for a guide on how to fix this.

Step-by-step guide

  • Prepend async to any top-level function that calls context.request, and await just before context.request. Change context.request to context.v3.request.

    • Also, consider switching over to using node-fetch, which has a more modern, standardized API.

  • Prepend async to any top-level function that calls context.async, and await just before context.async. Change context.async to context.v3.async.

    • Also, consider switching over to using util.promisify, which is a more modern syntax.

  • Prepend async to any top-level function that calls the .get method on Bubble Things and await just before .get.

  • Prepend async to any top-level function that calls the .get method on Bubble Lists and await just before .get.

  • Prepend async to any top-level function that calls the .length method on Bubble Lists and await just before .length.

  • Finally, switch your Bubble Plugin API Version to 4 in the “Dependencies” dropdown of the “Shared” tab

Examples

Here are a few examples of how to update the run_server function of your plugin’s server-side actions.

context.request: Versions 3 and below plugin API

function(properties, context) {
    // Send a request to the cat API synchronously
    const response = context.request({
        url: 'https://api.thecatapi.com/v1/images/search',
        json: true
    })
const cat_image = response.body[0].url
    return { cat_image }
}

context.request: Updated plugin API

async function(properties, context) {
    // Send a request to the cat API asynchronously, with promises
    const response = await context.v3.request({
        url: 'https://api.thecatapi.com/v1/images/search',
        json: true
    })
const cat_image = response.body[0].url
    return { cat_image }
}

function(properties, context) {
  let list_length = properties.my_list.length()
  return { list_length }
}

.length(): Current plugin API

function(properties, context) {
  let list_length = properties.my_list.length()
  return { list_length }
}

.length(): Updated plugin API

async function(properties, context) {
  let list_length = await properties.my_list.length()
  return { list_length }
}

Using node-fetch instead of context.request

Here’s an example of how to update your code using context.request to use node-fetch, based on the same starting point as the earlier context.request example.

async function(properties, context) {
    // Use the node-fetch module to make an HTTP request
    const response = await fetch('https://api.thecatapi.com/v1/images/search')
    const body = await response.json()
    const cat_image = body[0].url
    return { cat_image }
}

Using promises instead of context.async

In the old version of the API, plugin authors frequently had to use context.async to interoperate with modern, Promise-using JS libraries. For instance, to use the weathered npm package to fetch a list of real-time weather warnings, you might write code like this:

function(properties, context) {
    const { Client } = require('weathered')
const client = new Client()
    const region = properties.region || 'NY'
    
    const alerts = context.async((cb) => {
        client.getAlerts(true, { region })
            .then((result) => cb(null, result))
         .catch((error) => cb(error))
    })
    
    const weather_alerts = alerts.features.map(f => f.properties.description)
    return { weather_alerts }
}

In the new API, which is Promise-based already, you don’t need to jump through this hoop; you can await the result of the call directly.

async function(properties, context) {
    const { Client } = require('weathered')
const client = new Client()
    const region = properties.region || 'NY'
    
    const alerts = await client.getAlerts(true, { region })
   
    const weather_alerts = alerts.features.map(f => f.properties.description)
    return { weather_alerts }
}

Using utils.promisify instead of context.async

But if the code you’re trying to wait for with context.async is callback-based rather than promise-based, you'll still need some sort of wrapper.

Here’s a (somewhat contrived) example of using the callback-based fs.stat API from Node to inspect the filesystem of the lambda your action is running on:

function(properties, context) {
    const fs = require('node:fs')
    const { inspect } = require('node:util')
    
const stats = context.async((cb) => {
        fs.stat('/', cb)
    })
    return { stats: inspect(stats) }
}

Instead of using context.async, you could also wrap fs.stat with node’s built in promisify utility to make it return a promise, then await that promise:

async function(properties, context) {
    const fs = require('node:fs')
    const { inspect, promisify } = require('node:util')
    
    const stats = await promisify(fs.stat)('/')
    return { stats: inspect(stats) }
}

Change log

Here are the changes that we will make to the plugin API:

  • context.request is being deprecated (this means that we plan to eventually stop supporting it), moved to context.v3.request, and will now return a promise. We recommend that plugin authors use the globally-available node-fetch instead.

  • context.async is also being deprecated, moved to context.v3.async, and will now return a promise. We recommend that plugin authors use promisify from Node’s built-in util module instead.

  • The .get method available on Bubble Things now returns a promise.

  • The .get method available on Bubble Lists now returns a promise.

  • The .length method available on Bubble Lists now returns a promise.

  • We are adding a utility method on Bubble Things

    • getAll(): returns a promise for an object with all fields of the Thing

  • We are adding a new field on Bubble Things:

    • id: the Thing’s ID

  • Lists now also implement the AsyncIterable interface, so you can use for (await ... of ...) loop syntax to loop over the list.

  • the single_api and list_api fields are still present, but no longer encouraged (we will also remove official documentation for these fields). In their place are two new context methods: isBubbleThing and isBubbleList.

  • We are adding official support for two previously usable, but undocumented functions: getThingById and getThingsById. We added these functions to the context object to be more consistent with the rest of API. These functions also now return promises.

See below for more detail.

export type Primitive = string | number | boolean |  Date | null | undefined

/** Any value that can be passed as a property to an action or stored in the DB. */
export type BubbleValue = Primitive | Primitive[] | BubbleThing | BubbleList

/** Fields present on any Bubble data type. */
export interface ThingFields {
    // These fields are guaranteed to be present on any database Thing.
    'Slug'?: string
    'Created Date': Date
    'Modified Date': Date

    // Other fields might also be present, depending on the data type.
    [_: string]: BubbleValue
}

/** Additional fields present on the User data type. */
export interface UserFields extends ThingFields {
    'email': string
    'logged_in': boolean
}

/**
 * An object representing a single Thing from the Bubble app's database.
 */
export interface BubbleThing {
    /** Returns the names of the fields on the Thing. */
    listProperties(): string[]

    // CHANGED - now returns a promise
    /** Returns the value stored in a particular field of this Thing. */
    get(propertyName: string): Promise<BubbleValue>

    // NEW
    /** Returns an object with all the thing's fields and their values. */
    getAll(): Promise<Record<string, BubbleValue>>

    // NEW
    /** Field that contains the unique ID of this Thing. */
    readonly id: string

    // for historical interest - maybe de-document these
    single_api: true
    list_api: false
}

/**
 * An object representing a list of Things from the Bubble app's database.
 * 
 * As lists may be quite large, the data contained in the list isn't all
 * loaded up front. Therefore, methods for accessing data within the list
 * are generally asynchronous.
 */
export interface BubbleList {
    // CHANGED - now returns a promise
    /** The number of items in this BubbleList. */
    length(): Promise<number>

    // CHANGED - now returns a promise
    /** Fetch a portion of a BubbleList as an array. */
    get(start: number, length: number): Promise<BubbleThing[]>

    // NEW
    /** Allows you to use a BubbleList with the `for (await x of list)` syntax */
    [Symbol.asyncIterator](): AsyncIterator<BubbleThing>

    // for historical interest - maybe de-document these
    single_api: false
    list_api: true
}

/** An object containing utility functions available to server-side actions. */
export interface Context {
    /** The current user who initiated the workflow that's running this action. */
    currentUser: BubbleThing

    /** The timezone the workflow is running in. */
    userTimezone: string

    /** An object containing any keys set for this plugin in the app. */
    keys: Record<string, string>

    // NEW
    /** Check if a JS value is a BubbleThing object. */
    isBubbleThing(x: unknown): boolean

    // NEW
    /** Check if a JS value is a BubbleList object. */
    isBubbleList(x: unknown): boolean

    // NEW - was secret global before
    /** Fetch a BubbleThing object for a given unique ID. */
    getThingById(id: string): Promise<BubbleThing | null>

    // NEW - was secret global before
    /**
     * Fetch the corresponding BubbleThing objects for each ID in an array.
     * Results will be returned in the same order as requested, with `null`
     * in place of any IDs with no corresponding Thing.
     */
    getThingsById(ids: string[]): Promise<Array<BubbleThing | null>>

    // NEW/CHANGED - these used to be top-level properties of the context
    v3: ContextDeprecatedV3
}

/** Context functions that are no longer recommended, but are provided for backwards compatibility. */
export interface ContextDeprecatedV3 {
    // CHANGED - now returns a promise
    /**
     * See documentation for the `request` library.
     * 
     * @deprecated We recommend you use node-fetch instead.
     */
    request(...args: unknown[]): Promise<unknown>

    // CHANGED - now returns a promise
    /**
     * Takes a node-style asynchronous function which expects to be passed a callback,
     * and turns it into a promise.
     * 
     * @deprecated We recommend you use node's built-in `util.promisify`.
     */
    'async': <T>(fn: (callback: (err: unknown, res?: T) => void) => void) => Promise<T>
}

declare global {
    /** Exposes node-fetch to plugins. */
    function fetch(...args: unknown[]): Promise<unknown>
}
JavaScript documentation