Serverless functions reference
CMS Hub
- Enterprise
In this article, learn about the files found inside of a serverless .functions
folder and the CLI commands you can use with serverless functions.
For a high-level overview of serverless functions, see the serverless functions overview.
Please note: serverless function files must be uploaded locally using the HubSpot CLI.
Your serverless.json
file stores your configuration settings for functions inside of your .functions
folder. This file is required for serverless functions to work. This file maps your functions to their endpoints.
key | Type | Description |
---|---|---|
runtime
required
| String | The runtime environment. Supports the following Node.js versions:
|
version
required
| String | HubSpot serverless function schema version. (Current version 1.0) |
endpoints
required
| Object | Endpoints define the paths that are exposed and their mapping to specific JavaScript files, within your functions folder. |
environment
| Object | Configuration variables passed to the executing function as environment variables at runtime. You might use this to add logic for using a testing version of an API instead of the real thing based on an environment variable. |
secrets
| array | An API key is a secret. The secrets in the config file refers to the name of the secret not it’s value. Do not put secrets directly in this file, only reference secret names. |
Please note: do not assign the same name to your secrets and environment variables. Doing so will result in conflicts when returning their values in the function.
Each endpoint can have its own environment variables and secrets. Variables specified outside of endpoints should be used for configuration settings that apply to all functions and endpoints.
Endpoints have a couple unique keys.
key | Type | Description |
---|---|---|
method
| String or array of strings | HTTP method or methods that the endpoint supports. Defaults to GET. |
file
required
| String | Path to JavaScript function file with the implementation for the endpoint. |
Serverless functions are exposed through a path at your HubSpot CMS account’s domain. This includes default .hs-sites.com
sub-domains.
You can access these functions at the following URL:
https://{domainName}/_hcms/api/{endpoint-name/path}?portalid={hubId}
.
Below, learn about each URL component:
Parameter | Description |
---|---|
domainName
| Your domain name. |
/_hcms/api/
| The path reserved for serverless functions. All endpoints exist inside this path. |
endpoint-name/path
| The endpoint name or path that you specified in the |
hubId
| Your Hub ID. Providing this in the request will enable you to test your functions within module and template previews. |
Each function is created as a Node.js JavaScript file in a folder ending in .functions
. In addition to the Node.js standard library, functions can leverage the request library to make HTTP request to HubSpot APIs and other APIs.
A basic serverless-function.js
file looks like:
Parameter | Description |
---|---|
accountId
| The HubSpot account ID containing the function. |
body
| body is populated if the request is sent as a POST with a content type of application/json |
contact
| If the request is from a cookied contact, the contact object will be present with a set of basic contact properties. These additional properties will also be available:
|
headers
| Contains headers sent from the client hitting your endpoint. See headers. |
params
| params is populated with query string values plus any HTML Form-POSTed values. These are structured as a map with strings as keys and an array of strings for each value. |
limits
| Returns how close you are to hitting the serverless function rate limits.
|
Sometimes it can be helpful to have the headers of the client hitting your endpoint. We provide the following headers through context.headers
. This is similar to how you would access information through context.body
.
header | Description |
---|---|
accept
| Communicates which content types expressed as MIME types, the client understands. See MDN. |
accept-encoding
| Communicates the content encoding the client understands. See MDN. |
accept-language
| Communicates which human language and locale is preferred. See MDN. |
cache-control
| Holds directives for caching. See MDN. |
connection
| Communicates whether the network connection stays open. See MDN. |
cookie
| Contains cookies by sent the client. See MDN. |
host
| Communicates the domain name and TCP port number of a listening server. See MDN. |
true-client-ip
| IP address of the end-user. See Cloudflare true-client-ip. |
upgrade-insecure-requests
| Communicates the clients preference for an encrypted and authenticated response. See MDN. |
user-agent
| Vendor defined string identifying the application, operating system, application vendor, and version. See MDN. |
x-forwarded-for
| Identifies the originating IP address of a client through a proxy or load balancer. See MDN. |
You can perform a redirect from your serverless function by sending a response with a location header and 301
statusCode.
For headers that support multiple values, you can use multiValueHeaders
, to pass the values. For example: you can tell the browser to set multiple cookies.
API keys, and authentication information are referred to as secrets. Once added they are accessible through environment variables (process.env.secretName). You can assign secrets available for specific endpoints to use by adding the "secrets" key to your serverless.json
file. Secrets are managed through the HubSpot CLI using the following commands:
Do not return your secret's value through console logging or as a response. Doing so would expose your secrets in your logs or in front-end pages that call your serverless function.
Cross Origin Resource Sharing (CORS) is a browser security feature. By default browsers restrict cross-origin requests initiated by javascript. This prevents malicious code running on a different domain, from affecting your site. This is called the same-origin policy. Because sending and retrieving data from other servers is sometimes a necessity, the external server, can supply HTTP headers that communicate which origins are permitted to read the information from a browser.
You should not run into CORS issues calling your serverless function within your HubSpot hosted pages. If you do, verify you are using the correct protocol.
Getting this CORS error?
"Access to fetch at [your function url] from origin [page making request] has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
Is your request to a different origin than the site calling it?
- If the domain name is different, yes.
- If using a different protocol(http, https), yes.
If using a different protocol, simply change the protocol to match and that will fix it.
You can't modify HubSpot's Access-Control-Allow-Origin
header at this time.
Get requests may be able to make CORS requests depending on the client. Do not make GET requests write anything, just return data.
HubSpot serverless functions currently come preloaded with the following packages:
- @hubspot/api-client: ^1.0.0-beta
- axios: ^0.19.2
- request: ^2.88.0
- requests: ^0.2.2
To use the latest supported version of a preloaded package, or to use a newly added package:
- Clone or copy your function file.
- Change your function's endpoint in the
serverless.json
file to point to your new function file. You can safely delete the old version.
If you want to include packages outside of the preloaded package set, you can use webpack to combine your node modules and have your bundled files be your function files.
Serverless functions are intended to be fast and have a narrow focus. To enable quick calls and responses, HubSpot serverless functions are limited to:
- 50 secrets per account
- 128MB of memory
- No more than 100 endpoints per HubSpot account
- You must use contentType
application/json
when calling a function. - serverless function logs are stored for 90 days.
- 6MB on an AWS Lambda invocation payload.
Execution limits
- Each function has a maximum of 10 seconds of execution time.
- Each account is limited to 600 total execution seconds per minute.
This means either of these scenarios can happen:
- 60 function executions that take 10 seconds each to complete.
- 6,000 function executions that take 100 milliseconds to complete.
Functions that exceed those limits will throw an error. Execution count and time limits will return a 429
response. The execution time of each function is included in the serverless function logs.
To assist in avoiding these limits, limit data is provided automatically to the function context during execution. You can use that to influence your application to stay within those limits. For example, if your application requires polling your endpoint, then you can return with your data a variable to influence the frequency of the polling. That way when traffic is high you can slow the rate of polling avoiding hitting limits, then ramp it back up when traffic is low.
Thank you for your feedback, it means a lot to us.