# Function: Writing functions

## Table of Contents

- [Return any value](#return-any-value)
- [Custom parameters](#custom-parameters)
  - [CLI Microlink API example](#cli-microlink-api-example)
  - [cURL Microlink API example](#curl-microlink-api-example)
  - [JavaScript Microlink API example](#javascript-microlink-api-example)
  - [Python Microlink API example](#python-microlink-api-example)
  - [Ruby Microlink API example](#ruby-microlink-api-example)
  - [PHP Microlink API example](#php-microlink-api-example)
  - [Golang Microlink API example](#golang-microlink-api-example)
- [The target URL](#the-target-url)
- [Using npm packages](#using-npm-packages)
  - [Pin a version](#pin-a-version)
  - [Security restrictions](#security-restrictions)
- [When to add page](#when-to-add-page)
- [See also](#see-also)

---

Your function runs remotely in a Node.js sandbox. The simplest function is just plain JavaScript — no browser, no page, no Puppeteer:

```js
importcreateClientfrom'microlink.io'

constmicrolink=createClient()

constresult=awaitmicrolink.function('https://example.com',()=>40+2)

console.log(result.isFulfilled)// true

console.log(result.value)// 42
```

Every example on this page assumes the `microlink` client above. See [function](https://microlink.io/docs/sdk/methods/function) for the method reference.

When your function does not reference `page`, no browser is started. This makes execution faster and cheaper.

## Return any value

Functions can return strings, numbers, booleans, arrays, or plain objects:

```js
constresult=awaitmicrolink.function('https://example.com',()=>({

greeting:'Hello',

items:[1,2,3],

nested:{works:true}

}))

console.log(result.value)

// { greeting: 'Hello', items: [1, 2, 3], nested: { works: true } }
```

The return value is always available at `result.value`. If the function throws, `result.isFulfilled` is `false` and `result.value` contains the error details instead.

## Custom parameters

Any extra option you include in the request is forwarded to the function as a named argument:

```js
constgreet=({name,greeting})=>`${greeting}, ${name}!`

constresult=awaitmicrolink.function('https://example.com',greet,{

name:'Kiko',

greeting:'Hello'

})

console.log(result.value)// 'Hello, Kiko!'
```

This is the simplest way to make one function reusable across different requests without changing the function code.

The following examples show how to use the Microlink API with CLI, cURL, JavaScript, Python, Ruby, PHP & Golang, targeting 'https://example.com' URL with 'function' & 'greetings' API parameters:

### CLI Microlink API example

```bash
microlink https://example.com&function='({ greetings }) => greetings'&greetings='hello world'
```

### cURL Microlink API example

```bash
curl -G "https://api.microlink.io" \
  -d "url=https://example.com" \
  -d "function=(%7B%20greetings%20%7D)%20%3D%3E%20greetings" \
  -d "greetings=hello%20world"
```

### JavaScript Microlink API example

```javascript
import createClient from 'microlink.io'

const microlink = createClient()

const { value } = await microlink.function(
  'https://example.com',
  ({ greetings }) => greetings,
  {
    greetings: "hello world"
  }
)
```

### Python Microlink API example

```python
import requests

url = "https://api.microlink.io/"

querystring = {
    "url": "https://example.com",
    "function": "({ greetings }) => greetings",
    "greetings": "hello world"
}

response = requests.get(url, params=querystring)

print(response.json())
```

### Ruby Microlink API example

```ruby
require 'uri'
require 'net/http'

base_url = "https://api.microlink.io/"

params = {
  url: "https://example.com",
  function: "({ greetings }) => greetings",
  greetings: "hello world"
}

uri = URI(base_url)
uri.query = URI.encode_www_form(params)

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Get.new(uri)
response = http.request(request)

puts response.body
```

### PHP Microlink API example

```php
<?php

$baseUrl = "https://api.microlink.io/";

$params = [
    "url" => "https://example.com",
    "function" => "({ greetings }) => greetings",
    "greetings" => "hello world"
];

$query = http_build_query($params);
$url = $baseUrl . '?' . $query;

$curl = curl_init();

curl_setopt_array($curl, [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET"
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
    echo "cURL Error #: " . $err;
} else {
    echo $response;
}
```

### Golang Microlink API example

```
package main

import (
    "fmt"
    "net/http"
    "net/url"
    "io"
)

func main() {
    baseURL := "https://api.microlink.io"

    u, err := url.Parse(baseURL)
    if err != nil {
        panic(err)
    }
    q := u.Query()
    q.Set("url", "https://example.com")
    q.Set("function", "({ greetings }) => greetings")
    q.Set("greetings", "hello world")
    u.RawQuery = q.Encode()

    req, err := http.NewRequest("GET", u.String(), nil)
    if err != nil {
        panic(err)
    }

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    body, err := io.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }

    fmt.Println(string(body))
}
```

```javascript
importcreateClientfrom'microlink.io'

constmicrolink=createClient()

const{value}=awaitmicrolink.function(

'https://example.com',

({greetings})=>greetings,

{

greetings:"hello world"

}

)
```

## The target URL

The function always receives `url`, the target of the request. You do not need `page` — or a browser — just to resolve paths against that origin:

```js
constresult=awaitmicrolink.function(

'https://example.com',

({url})=>newURL('/robots.txt',url).href

)

console.log(result.value)// 'https://example.com/robots.txt'
```

`url` is the URL you requested, not the one a redirect settles on. Use `page.url()` when you need the settled one. See [url](https://microlink.io/docs/api/parameters/function#url).

## Using npm packages

You can `require()` any npm package inside your function. Dependencies are detected automatically and installed on-the-fly:

```js
constresult=awaitmicrolink.function('https://example.com',()=>{

const{kebabCase}=require('lodash')

returnkebabCase('Hello World')

})

console.log(result.value)// 'hello-world'
```

When your function contains a `require()` call, the runtime:

1.  Parses your code to detect all dependency names.
2.  Installs them into an isolated sandbox during the install phase.
3.  Bundles everything during the build phase.
4.  Caches the result so subsequent runs with the same dependencies skip installation.

You can see how long each step takes in `result.profiling.phases`. A high install value on the first run is normal — it drops to zero once cached.

### Pin a version

Append the version to the package name:

```js
constcheerio=require('cheerio@1.0.0')
```

When no version is specified, the latest version is installed.

### Security restrictions

The runtime restricts certain system capabilities for security. Operations such as spawning child processes or writing to the filesystem outside the sandbox are not permitted. If a package tries to use a restricted capability, the function will return an error:

```json
{

"isFulfilled":false,

"value":{

"name":"Error",

"code":"ERR_ACCESS_DENIED",

"permission":"ChildProcess",

"message":"Access to this API has been restricted."

}

}
```

## When to add page

Add `page` when you need the page for the URL you asked for. It is a [Puppeteer Page](https://pptr.dev/api/puppeteer.page), and the [page API](https://pptr.dev/api/puppeteer.page) is supported:

```js
constgetTitle=({page})=>page.title()

constresult=awaitmicrolink.function('https://example.com',getTitle)

console.log(result.value)// 'Example Domain'
```

Two methods extend it: [page.extract](https://microlink.io/docs/api/parameters/function#pageextract) takes the same rules as [data](https://microlink.io/docs/api/parameters/data), and [page.metadata](https://microlink.io/docs/api/parameters/function#pagemetadata) returns the same normalized metadata as [meta](https://microlink.io/docs/api/parameters/meta).

If you only need to compute a value, skip `page`. Your function will run faster.

See [Browser interaction](https://microlink.io/docs/guides/function/browser-interaction) for Puppeteer helpers, execution contexts, and browser automation.

## See also

- [Browser interaction](https://microlink.io/docs/guides/function/browser-interaction) — Puppeteer helpers and browser automation.
- [Profiling and performance](https://microlink.io/docs/guides/function/profiling-and-performance) — understand execution phases and optimization.
- [Function reference](https://microlink.io/docs/api/parameters/function) — response shape, plan limits, and compression.