Fetching data with serverless functions (BETA)
-
Sales Hub
- Enterprise
-
Service Hub
- Enterprise
-
Content Hub
- Enterprise
When needing to fetch data for a project-based private app, whether for a UI extension or CMS React project, you'll use a serverless function. When executed, HubSpot runs the serverless function server-side using JavaScript. Because HubSpot runs the function, you don't need to manage your own server.
Your access to using serverless functions depends on your HubSpot subscription:
- UI extensions: using serverless functions for UI extensions requires a Sales Hub or Service Hub Enterprise subscription. You can also test out UI extensions for private apps for free in a developer test account.
- CMS: using serverless functions for CMS React projects requires a Content Hub Enterprise subscription.
Within the project file structure, serverless functions live in the src/app
directory within a <AnyName>.functions
folder. At the most basic level, this folder should include:
- One or more JavaScript files that export a
main
function. - A
serverless.json
file that registers and configures your functions. Learn more about serverless function configuration.
Serverless functions for private apps in projects can be executed in two ways:
- App function: a serverless function that gets executed directly from within the project. The function is made available to UI extension's React file through the
runServerless
argument. - Endpoint function (Content Hub Enterprise only): an app function that is invoked by calling a public URL. The URL is determined by the account's connected domains and the path specified in the
serverless.json
file. This is more common for implementing serverless functions in CMS React modules.
In the serverless functions directory, configure the serverless function with a serverless.json
file. In this file, you'll configure your serverless function name and the path of the JavaScript file to execute, along with any secrets that might need to be included for authentication.
If you have a Content Hub Enterprise subscription, you can configure a serverless function to be invoked by a public URL by including an endpoint
object in the config. Learn more about endpoint functions.
Parameter | Type | Description |
---|---|---|
file
| String | The |
secrets
| Array | To authenticate requests, you can include secrets as string values in this array. Learn more about managing secrets. |
endpoint
| Object | If invoking the function by a public URL (Content Hub Enterprise only), this object defines the endpoint details:
|
Each serverless function exports a main
function that gets called when HubSpot executes it. The function receives the context
argument, which is an object that contains data based on how the function is being used. This includes context about where the card is loaded as well as the authenticated user and account. Learn more about what's included in the context object.
Below is an example of a function that returns a 200 status code and a Hello World message:
For a more complete example of an app function, HubSpot's boilerplate quickstart template includes the following function:
- When invoked, the function returns a response containing static text along with variable text (which is entered into the extension's input field).
- The
serverless.json
file specifies the name of the function, which is used in the extension's React file. It also specifies where the function file is located in the project. - The extension includes invokes the function on button click, providing a text value to the function if text is included in the input field. The React file below is based on the boilerplate quickstart template, but has been simplified to highlight the serverless function.
Please note: serverless functions have a response limit of 15 seconds. Functions that take longer to execute will fail.
If you have a Content Hub Enterprise subscription, you can configure a serverless function to be invoked by a public URL. When calling the URL of a HubSpot-hosted serverless function, you can use any domain connected to your account with the following URL structure: https://<domain>/hs/serverless/<endpoint-path-from-config>
.
For example, if both website.com and subdomain.brand.com are connected to the account, you could call the function using https://website.com/hs/serverless/path/to/endpoint
or https://subdomain.brand.com/hs/serverless/path/to/endpoint
.
In the URL to call the function, the endpoint path is global rather than scoped to the app or project. If you have identical endpoint paths across multiple apps or projects, the most recently deployed endpoint function will take precedence.
When developing a private app with projects, each private app comes with a private access token that you can use to authenticate calls to HubSpot's APIs. You can also authenticate calls using secrets, which you'll manage through the CLI. To make your private app access token or secrets available for local development, you'll need to create a .env
file in the .functions
directory.
For example, if you wanted to use Node to make a request to a HubSpot API:
- Ensure the @hubspot/api-client library is included as a dependency in your project.
- Include
@hubspot/api-client
in function file. - Instantiate it within
exports.main
and includePRIVATE_APP_ACCESS_TOKEN
for authentication:
You can then configure the rest of the function using Node.js. For example, the following code would create a serverless function that retrieves the current contact by ID using the contacts API:
To get started, you can find Node.js code snippets on the Endpoints tabs of HubSpot's API docs.
If your serverless function requires secrets, include a secrets
field in the serverless.json
configuration file. Follow the steps below to make them accessible when the function is deployed and when running the local development server.
- Create your secrets by running
hs secrets add <secret name>
. HubSpot will securely store this secret on its backend and inject them into the runtime environment when a function is invoked in production. - In your
serverless.json
file, list the names of the secrets needed by each function. Do not includePRIVATE_APP_ACCESS_TOKEN
in this array, as this is automatically created for you and already available in the serverless function.
- To make secrets available for local development, create a
.env
file in the<AnyName>.functions
directory. HubSpot will never retrieve your secrets outside of its protected infrastructure, so you'll need to specify the secret values that you want to use when the function is executed locally. If your function usesPRIVATE_APP_ACCESS_TOKEN
, you'll need to copy the private app's access token from HubSpot and store it in the.env
file for local access. The following snippet demonstrates what an example.env
file might look like:
- After saving secrets to the
.env
file, you can access them in your function usingprocess.env["<keyName>"]
.
- To update a secret's value, you can run the
hs secrets update
command. If you're using a Node runtime of 14 or higher, updated secret values will automatically be updated in your deployed function within one minute, meaning you won't have to build and deploy to get the updated secret.
Please note:
- To limit exposure of a secret, it's strongly recommended to never include it in console statements to prevent it from being recorded in logs.
- If your project is linked to a GitHub repository, be sure to never commit the
.env
file when uploading to GitHub. You can include an entry for.env
in your.gitignore
file to ensure that it is omitted from your commits.
Keep the following recommendations in mind while you develop and test your serverless function:
To ensure that variables are correctly assigned and initialized with every function invocation, you should opt to assign variables within the function itself. This practice prevents potential issues related to stale or persistent variable states, which can lead to unexpected behaviors. See the example below for additional context:
The hsprojects.json
configuration file includes a platformVersion
field which specifies which platform version to run the project on. It's strongly encouraged to use the latest platform version to ensure that your project and its assets are up to date with the latest improvements, optimizations, and feature enhancements. In addition, some previously available features may not be available in older versions due to deprecation.
The platform version also dictates which version of Node the project runs on. The latest version, 2023.2
, uses Node18, and doesn't support older versions of Node.
By default, HubSpot provides a small number of NPM dependencies in addition to the Node.js standard library. To add your own dependencies, you can list the package in dependencies
within the package.json
file. When the app is built, dependencies will be bundled with your function code. All dependencies must be published to NPM and be public.
For example, if you wanted to add the lodash library in a serverless function, you would first update package.json
to include the dependency:
Then, at the top of your serverless function JavaScript file, you would require the lodash dependency:
In HubSpot, you can view a serverless function's log history for both app functions and endpoint functions, including successful requests and errors.
To access a serverless function's logs in HubSpot:
- In your HubSpot account, navigate to CRM Development.
- In the left sidebar menu, navigate to Private apps.
- Select the private app that contains the serverless function.
- Click the Logs tab.
- To view logs for a serverless app function, click the Serverless functions tab. To view logs for a serverless endpoint function, click the Endpoint functions tab.
- In each tab, you can view logs for specific requests by clicking the request. You can also use the search bar to search by request ID.
- In the right panel, you can then click View log trace for a more in-depth breakdown of the request.
You can also include console.log()
in your serverless function code for debugging purposes, then view its output in the function log details sidebar.
Log messages are produced every time HubSpot executes a serverless function. To view a serverless function's logs in the CLI, run the hs project logs
command. Learn more about using the hs project logs command.
There are two types of log messages produced:
- Log messages that record the execution of a function, along with its status and timing. For example:
2021-04-28T19:19:21.666Z - SUCCESS - Execution Time: 279ms
- Log messages that are produced through console statements in the function code. For example, your serverless function JavaScript might include:
A log output for the above code would then produce the following:
2021-04-28T19:15:13.200Z INFO Log some debug info
2021-04-28T19:15:14.200Z ERROR An error occurred
Thank you for your feedback, it means a lot to us.