API Extensions

Sandbox

Sandboxed Extensions run in an isolated environment and must request permission scopes.

Sandboxed API Extensions run in an isolated environment and must request permission scopes to interact with the host environment.

The sandboxed environment only has access to JavaScript standard built-in objects which means that common runtime functions such as console and setTimeout are not available. A sandboxed extension is given additional capabilites through scopes and functions provided by the directus:api module.

Enabling the Sandbox

To enable the the sandbox, add the sandbox object to your extension's package.json file.

"directus:extension": {
    "type": "endpoint",
    "path": "dist/index.js",
    "source": "src/index.js",
    "host": "^10.7.0",
    "sandbox": {
        "enabled": true,
        "requestedScopes": {}
    }
}

Using TypeScript

To enable type checking for directus:api functions, use the api.d.ts file from @directus/extensions. Reference it directly or add it to tsconfig.json for global extension support.

/// <reference types="@directus/extensions/api.d.ts" />
import type { SandboxEndpointRouter } from 'directus:api';

export default (router: SandboxEndpointRouter) => {
    router.get("/hello", () => {
        return { status: 200, body: "Hello World" };
    });
};

Log Scope

The log function will print a message in the API's logger output. It can be used as a replacement for console.log.

import { log } from 'directus:api';

log('Hello World!');

Required Scopes

The log function requires the log scope. There are no additional configuration options.

"requestedScopes": {
  "log": {}
}

Sleep Scope

The sleep function will wait for a given number of milliseconds. It can be used as a replacement for setTimeout.

import { sleep } from 'directus:api';

await sleep(1000);

Required Scopes

The sleep function requires the sleep scope. There are no additional configuration options.

"requestedScopes": {
  "sleep": {}
}

Request Scope

The request function will make a network request to specified URLs.

import { request } from 'directus:api';

const getRequest = await request('https://directus.io');

const postRequest = await request('https://directus.io', {
  method: 'POST',
  headers: { Authorization: 'Bearer 1234567890' },
  body: { key: 'value' }
});

Responses contain a status, statusText, headers, and data property.

Required Scopes

The request function requires the request scope. You must specify which methods and URLs are allowed.

"requestedScopes": {
  "request": {
    "methods": ["GET", "POST"],
    "urls": ["https://directus.io/*"]
  }
}

The url property supports wildcards. For development purposes, you can use https://* to allow all URLs.