For AI agents: a documentation index is available at /llms.txt
Skip to main content

Function API

Execute custom Puppeteer code via HTTP requests without installing libraries. Your function receives a page object (Puppeteer page) and optional context data from the JSON body. What your function returns sets the response: return bytes (such as await page.pdf()) to get a file back, a string to get text back, or an object or array to get JSON back.

Endpoint

  • Method: POST
  • Path: /function
  • Auth: token query parameter (?token=)
  • Content-Type: application/javascript or application/json
  • Response: */* (set by the return value; see Return values)

See the OpenAPI reference for complete details.

Prerequisites

Quickstart​

The /function API accepts requests in two content types: application/javascript (raw code) and application/json (code + context data).

Sending code as Javascript​

JS Code

export default async ({ page }) => {
await page.goto("https://books.toscrape.com/", { waitUntil: "networkidle2" });
const books = await page.$$eval(".product_pod", (nodes) =>
nodes.slice(0, 5).map((el) => ({
title: el.querySelector("h3 a").getAttribute("title"),
price: el.querySelector(".price_color").textContent,
}))
);
return { books };
};
curl -s -X POST "https://production-sfo.browserless.io/function?token=YOUR_API_TOKEN_HERE" -H "Content-Type: application/javascript" -d 'export default async({page})=>{await page.goto("https://books.toscrape.com/",{waitUntil:"networkidle2"});const b=await page.$$eval(".product_pod",n=>n.slice(0,5).map(e=>({title:e.querySelector("h3 a").getAttribute("title"),price:e.querySelector(".price_color").textContent})));return{books:b};}'

Response

{
"books": [
{ "title": "A Light in the Attic", "price": "£51.77" },
...
]
}

Sending code as JSON​

You can send a JSON payload with the following fields:

  • code: String, required — custom function code.
  • context: Object, optional — value used to pass context values and arguments to the code

JS Code

export default async ({ page, context }) => {
await page.goto(
`https://quotes.toscrape.com/page/${context.pageNumber}/`,
{ waitUntil: "networkidle2" }
);
const quotes = (
await page.$$eval(".quote", (nodes) =>
nodes.map((el) => ({
text: el.querySelector(".text").textContent,
author: el.querySelector(".author").textContent,
}))
)
).slice(0, context.maxQuotes);
return { page: context.pageNumber, quotes };
};
curl -s -X POST "https://production-sfo.browserless.io/function?token=YOUR_API_TOKEN_HERE" -H "Content-Type: application/json" -d '{"code":"export default async({page,context})=>{await page.goto(\"https://quotes.toscrape.com/page/\"+context.pageNumber+\"/\",{waitUntil:\"networkidle2\"});const q=(await page.$$eval(\".quote\",n=>n.map(e=>({text:e.querySelector(\".text\").textContent,author:e.querySelector(\".author\").textContent})))).slice(0,context.maxQuotes);return{page:context.pageNumber,quotes:q};}","context":{"pageNumber":2,"maxQuotes":3}}'

Response

{
"page": 2,
"quotes": [
{
"text": "\u201cThere are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.\u201d",
"author": "Albert Einstein"
},
...
]
}

Return values​

Browserless picks the response Content-Type from the type of value your function returns. There's no wrapper to set it yourself.

Return valueResponse bodyContent-Type
Bytes (Buffer or Uint8Array), such as await page.pdf() or await page.screenshot()The raw bytesDetected from the bytes (for example application/pdf or image/png)
String starting with <The stringtext/html
Any other stringThe stringtext/plain
Object, array, or nullThe value, JSON-serializedapplication/json
Number or booleanThe value as texttext/plain

Return bytes directly, not inside an object. A Buffer nested in an object is serialized as JSON like any other field, so you get a JSON object of byte values instead of a file.

Debug your code​

Before sending your code through the /function API, you can test and troubleshoot it using our Live Debugger. It lets you write and execute your Puppeteer code in a browser environment, making it easy to iterate and debug before making API calls.

You can access the Live Debugger directly from your account page. Once your code is working as expected, simply copy and paste it as the request body and send it with the application/javascript content-type header to the /function endpoint.

For more details on how to use the BaaS Debugger and its features, see our Dashboard documentation.

Importing libraries​

Since the /function API uses ESM modules, you can use import syntax over HTTP to load modules. For instance, let's try loading the Faker module.

JS Code

import { faker } from "https://esm.sh/@faker-js/faker";

export default async function () {
const Internet = faker.internet;
const rndData = [...Array(5)].map(() => ({
domain: Internet.domainName(),
ip: Internet.ip(),
mac: Internet.mac(),
protocol: Internet.protocol(),
}));

return { domains: rndData };
}

cURL

curl -X POST "https://production-sfo.browserless.io/function?token=YOUR_API_TOKEN_HERE" -H 'Content-Type: application/javascript' -d 'import{faker}from"https://esm.sh/@faker-js/faker";export default async function(){const I=faker.internet;const d=[...Array(5)].map(()=>({domain:I.domainName(),ip:I.ip(),mac:I.mac(),protocol:I.protocol()}));return{domains:d};};'

Returning files​

The /function API can return other file types beyond JSON, such as PDF files. In this example, we'll generate a PDF of Hacker News using the built-in page.pdf() method.

JS Code

export default async ({ page }) => {
await page.goto("https://news.ycombinator.com/", { waitUntil: "networkidle2" });
return await page.pdf({ printBackground: true });
};

cURL

curl -s -X POST "https://production-sfo.browserless.io/function?token=YOUR_API_TOKEN_HERE" -H "Content-Type: application/javascript" -d 'export default async({page})=>{await page.goto("https://news.ycombinator.com/",{waitUntil:"networkidle2"});return await page.pdf({printBackground:true});}' -o hn.pdf

Exception handling​

When working with the /function API, you can catch exceptions and handle errors gracefully. This is particularly useful for debugging and providing meaningful error responses when automation fails.

The following example shows how to implement error handling, allowing you to:

  • Capture the error message when an automation step fails
  • Take a screenshot when an error occurs for visual debugging
  • Handle screenshot capture errors gracefully
  • Return both successful data and error information in a structured format

JS Code

export default async ({ page }) => {
let error;
let title;
try {
await page.goto("https://books.toscrape.com/", { waitUntil: "networkidle2" });
title = await page.title();
await page.click(".nonexistent");
} catch (err) {
error = { message: err.message };
try {
error.screenshot = await page.screenshot({ encoding: "base64" });
} catch (_) {}
}
return { title, error };
};

cURL

curl -s -X POST "https://production-sfo.browserless.io/function?token=YOUR_API_TOKEN_HERE" -H "Content-Type: application/javascript" -d 'export default async({page})=>{let e,t;try{await page.goto("https://books.toscrape.com/",{waitUntil:"networkidle2"});t=await page.title();await page.click(".nonexistent");}catch(r){e={message:r.message};try{e.screenshot=await page.screenshot({encoding:"base64"});}catch(x){};}return{title:t,error:e};};'
Session Persistence

The /function API, like all REST APIs, automatically closes the browser session after execution completes. If you need to persist sessions or keep browsers alive between requests, consider using BaaS with session management or BrowserQL with the reconnect mutation.

FAQ & Troubleshooting​

Why am I getting a 401 Unauthorized error?

Your API token is missing or invalid. Include it as the ?token= query parameter, as in the examples on this page. Verify the token in your account dashboard.

My request returns an empty response

The page may not have finished loading. Increase waitForTimeout or use waitForSelector to wait for specific content before extracting data.

Why does my response include data and type fields?

Your function returns a { data, type } object. /function doesn't unwrap it, so the whole object comes back as JSON and type doesn't change the response. Return the data directly (return { books };), or return bytes for a file. See Return values.

My PDF or screenshot comes back as a JSON object of numbers

You returned the bytes inside an object, so they were serialized as JSON. Return them directly, for example return await page.pdf();.

Why do I get Couldn't determine function's response type.?

Your function returned bytes that aren't a recognized file format, so Browserless can't pick a Content-Type. File types are detected from the bytes themselves, so plain text encoded as a Uint8Array (for example with TextEncoder) fails. Return a string for text, or an object for JSON.

Next steps​

Was this page helpful?