# 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects) which means that common runtime functions such as `console` and `setTimeout` are not available. A sandboxed extension is given additional capabilities 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.

```json
"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.

```ts
/// <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`.

```js
import { log } from 'directus:api';

log('Hello World!');
```

### Required Scopes

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

```json
"requestedScopes": {
  "log": {}
}
```

## Sleep Scope

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

```js
import { sleep } from 'directus:api';

await sleep(1000);
```

### Required Scopes

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

```json
"requestedScopes": {
  "sleep": {}
}
```

## Request Scope

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

```js
import { request } from 'directus:api';

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

const postRequest = await request('https://directus.com', {
  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.

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

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