Twilio Functions – Common Cases

Twilio Functions are the glue that connect user code and Studio to the Twilio environment. They offer a convenient way to execute JavaScript while remaining inside of the Twilio ecosystem.  Functions have access to environment variables and shared NPM packages.  Functions also have access to the Twilio REST Helper Library. With this Studio flows can be extended to access more APIs.  This article provides a few common cases we encountered building Twilio offerings for clients.  It also builds upon Understanding Twilio Studio Flow.

Supporting CORS

It may become necessary to make a request from a domain external to the Twilio project.  To support Cross-Origin Resource Sharing, CORS, responding to OPTIONS request is necessary.  To achieve this consider the following example:

Microsoft - The Essential Guide to Microsoft Teams End-User Engagement
The Essential Guide to Microsoft Teams End-User Engagement

We take you through 10 best practices, considerations, and suggestions that can enrich your Microsoft Teams deployment and ensure both end-user adoption and engagement.

Get the Guide

The above code relies on the assumption that all OPTIONS requests will have no request body, event is an empty object. This assumption breaks down when dealing with GET requests. A GET request will have no request body. It is possible to support GET, but it would require duplicating the work in both the OPTIONS and GET. I would suggest sticking to CORS-enabled POST request for Twilio Functions that need to be accessed outside of the Twilio environment.

Calling Other Twilio Functions and Assets

Twilio Functions have access to the Runtime Client which provides access to Functions, Assets, and Sync.  For now let us ignore Sync and focus on Functions and Assets.  A typical Twilio Function will export a handler method.  Using the Runtime Client we can get the path of that function and proceed to load that module and call:

Putting common functionality into Assets is another way to share code across Twilio Functions.  The code below handles loading an asset JavaScript and calling a method exposed via exports.

A or B

This method has helped in numerous Studio cases where two paths converge and only one value will be present in the Twilio Function call.  It handles both JSON and raw data values.

About the Author

More from this Author

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Subscribe to the Weekly Blog Digest:

Sign Up