# Host API

Host API is the supplementary API that supports communication between different parts of an app and YouTrack.

## How to Use the Host API

When you want your [widget](apps-reference-extension-points.html) to send HTTP requests to YouTrack or communicate with it using any of the YouTrack APIs, you must include a script that registers the widget in YouTrack in the HTML code of the widget.

Here you can see an example of the registration script:

```HTML
<script type="module">
    const host = await YTApp.register();
    host.alert('Hello world');
</script>
```

When you've registered the widget, you can use the Host API to send alerts in YouTrack, invoke functions implemented as custom [HTTP handlers](apps-reference-http-handlers.html), or store app data locally in the browser.

## YTApp Object

YouTrack injects the `YTApp` object into the widget iframe. Use this object to register the widget with the host application and to read information about the widget context.

| Property or Method | Description |
| --- | --- |
| `register(plugin)` |    Registers the widget in YouTrack and returns the Host API object. The optional `plugin` argument lets the widget expose callback functions to YouTrack.      ```JAVASCRIPT const host = await YTApp.register(); ```    |
| `entity` |    The YouTrack entity that hosts the widget, or `null` when the widget doesn't have an entity context.     The object always contains `id` and `type`. Depending on the extension point, it can also contain additional fields such as an issue summary, project key, or article summary.    |
| `me` |    The current user in the widget context. This object contains basic user profile fields such as `id`, `login`, `name`, `avatarUrl`, and `userType`.     To read additional user data, use the YouTrack REST API with [host.fetchYouTrack()](#fetch-youtrack) or call a custom [HTTP handler](apps-reference-http-handlers.html).    |
| `locale` | The locale of the current YouTrack user interface. |
| `widget` | The current widget identifiers, including `id` and `appId`. |

## Host API Reference

Here is the list of methods and objects that the Host API provides.

### alert

This method allows you to send an alert message to YouTrack from within an app.

| Parameter | Type | Description | Required |
| --- | --- | --- | --- |
| `message` | String | The text of the alert message. | ✓ |

Here you can find a sample code that uses this method:

```JAVASCRIPT
const host = await YTApp.register();
host.alert('Hello world');
```

### fetchYouTrack

This method lets the app use the YouTrack REST API.

> **Note:**
> The `fetchYouTrack` method sends requests to YouTrack REST API endpoints under `/api`. It doesn't send requests to Hub REST API endpoints. To work with users, groups, and access management in YouTrack 2026.1 and later, use the corresponding [YouTrack REST API endpoints](api-users-yt-vs-hub.html). For Hub REST API calls, use [fetchHub()](#fetch-hub) where this method is available.

| Parameter | Type | Description | Required |
| --- | --- | --- | --- |
| `relativeURL` | String | The relative URL to the REST API endpoint. | ✓ |
| `requestParams` | RequestParams | Optional [fetch](https://developer.mozilla.org/en-US/docs/Web/API/fetch) parameters.     For additional information, see [requestParams](#request-params) below.   |   |

Here you can find a sample code that uses this method:

```JAVASCRIPT
const host = await YTApp.register();
const user = await host.fetchYouTrack(`users/${YTApp.entity.id}?fields=id,login,name`);
```

Here's a sample that contains optional query parameters:

```JAVASCRIPT
const ytResponse = await host.fetchYouTrack(
    'users',
    {
        query: {
            fields: 'id,login,email'
        }
    }
);
```

> **Warning: Requests That Require User Confirmation**
> When a widget sends a REST request that can change or delete data, YouTrack can ask the user to confirm the request before it is sent. This confirmation is stored for the current user only.
>
>
>
> If the widget is available to a broad audience, any user who can open the widget can confirm these requests on their own behalf. Configure [app visibility](app-visibility.html) and [widget permissions](app-permissions.html) so widgets that send such requests are available only to users who are expected to perform these actions.

### fetchApp

This method lets the app communicate with the custom HTTP handler and invoke its methods. The `fetchApp` method is similar to the `fetchYouTrack` method, but has an additional `scope` parameter. This parameter lets you indicate whether the request should be made to a scoped or global endpoint.

The `fetchApp` method parses JSON and returns a ready-to-use response object.

| Parameter | Type | Description | Required |
| --- | --- | --- | --- |
| `relativeURL` | String | The relative URL to the custom HTTP endpoint. For more details, see [HTTP Handlers](apps-reference-http-handlers.html#path). | ✓ |
| `requestParams` | [RequestParams](#request-params) |    Optional [fetch](https://developer.mozilla.org/en-US/docs/Web/API/fetch) parameters. For details, see [requestParams](#request-params) below.    |   |

Here you can find a sample code that uses this method:

```JAVASCRIPT
const host = await YTApp.register();
const appResponse = await host.fetchApp(
    'backend/demo',
    {
        scope: true
    }
);
```

Here's a sample GET request with query parameters:

```JAVASCRIPT
const appResponse = await host.fetchApp(
    'backend/demo',
    {
        query: {
            key: '12345',
            count: 20,
            filter: true
        }
    }
);
```

Here's a sample POST request with body:

```JAVASCRIPT
const appResponse = await host.fetchApp(
    'backend/demo',
    {
        method: 'POST',
        body: {
            test: 'test'
        }
    }
);
```

### navigation

The Host API provides the `navigation` object to full-page widgets. This object lets a widget read and update the part of the page URL that belongs to the app. Use it when your widget has internal navigation and users need to open, share, or return to a specific screen.

The `navigation` object is only available for widgets that use full-page extension points, such as `MAIN_MENU_ITEM` and `ADMINISTRATION_MENU_ITEM`.

The methods provided by the `navigation` object are asynchronous and return promises.

For a working example, see the full-page widget in the built-in YouTrack Demo App.

The app-controlled part of the URL is represented by the following object:

```TYPESCRIPT
type AppLocation = {
    pathname: string;
    search: string;
    hash: string;
};
```

| Property | Type | Description |
| --- | --- | --- |
| `pathname` | String | The custom path segment that follows the part of the app URL controlled by YouTrack. |
| `search` | String | The query string without the leading `?` character. If the app URL has no query string, this property is an empty string. |
| `hash` | String | The fragment identifier without the leading `#` character. If the app URL has no fragment identifier, this property is an empty string. |

#### getAppLocation

```
host.navigation.getAppLocation(): Promise<AppLocation>
```

Returns an `AppLocation` object that represents the current app URL.

Here you can find a sample code that reads query parameters from the current app URL:

```JAVASCRIPT
const host = await YTApp.register();
const location = await host.navigation.getAppLocation();
const params = new URLSearchParams(location.search);
const requestType = params.get('requestType');
```

#### updateAppLocation

```
host.navigation.updateAppLocation(location: Partial<AppLocation>): Promise<void>
```

Updates the app URL and adds a new entry to the browser history. Use this method when the user navigates to another screen inside the widget and the browser Back button should return to the previous app URL.

You can update `pathname`, `search`, and `hash` independently. Properties that are not specified in the `location` object keep their current values.

| Parameter | Type | Description | Required |
| --- | --- | --- | --- |
| `location` | `Partial<AppLocation>` | The app URL properties to update. This object can contain any combination of `pathname`, `search`, and `hash`. | ✓ |

Here you can find a sample code that updates the app URL when a user opens a specific screen inside the widget:

```JAVASCRIPT
const host = await YTApp.register();
const params = new URLSearchParams();
params.set('requestType', 'vacation');

await host.navigation.updateAppLocation({
    pathname: '/requests/new',
    search: params.toString()
});
```

#### replaceAppLocation

```
host.navigation.replaceAppLocation(location: Partial<AppLocation>): Promise<void>
```

Replaces the current app URL without adding a new entry to the browser history. Use this method when you need to normalize or clean up the URL without changing how the browser Back button behaves.

You can replace `pathname`, `search`, and `hash` independently. Properties that are not specified in the `location` object keep their current values.

| Parameter | Type | Description | Required |
| --- | --- | --- | --- |
| `location` | `Partial<AppLocation>` | The app URL properties to replace. This object can contain any combination of `pathname`, `search`, and `hash`. | ✓ |

Here you can find a sample code that removes a temporary query parameter from the current app URL:

```JAVASCRIPT
const host = await YTApp.register();
const location = await host.navigation.getAppLocation();
const params = new URLSearchParams(location.search);
params.delete('temporaryToken');

await host.navigation.replaceAppLocation({
    search: params.toString()
});
```

#### onAppLocationChange

To handle changes to the app URL, pass the `onAppLocationChange` callback to `YTApp.register()`.

This callback is invoked when the app URL changes, including cases when the user navigates with the browser Back and Forward buttons.

```JAVASCRIPT
const host = await YTApp.register({
    onAppLocationChange: (location) => {
        renderScreen(location.pathname, location.search, location.hash);
    }
});
```

### storage

> **Note:**
> Available since YouTrack version 2026.2.

The Host API provides the `storage` object for app data stored locally in the browser. Use it for values that should remain in the user's browser, such as the last active tab, UI preferences, dismissed hints, draft text, or cached data that lets the widget render immediately while fresh data loads.

The methods provided by the `storage` object are asynchronous and return promises. This is because widget code runs in a sandboxed iframe and storage operations are handled by the host application.

The storage area is isolated per app. All widgets from the same app share one storage area, while widgets from other apps can't read or modify its values. Coordinate key names between widgets from the same app to avoid overwriting shared values accidentally.

Keys and values are strings. To store structured data, serialize it with `JSON.stringify()` and parse it after reading. The total storage size for one app is limited to 1 MB. This quota counts the byte size of both keys and values.

The data is stored locally in the browser and isn't a replacement for server-side app storage. It isn't tied to a YouTrack user account, so don't use it for secrets or values that must be protected by YouTrack permissions. Use [app global storage](apps-extension-properties.html#global-storage) or extension properties for data that must be available to backend scripts, other users, or the same user in another browser.

The `storage` object provides persistent storage only. Session storage and cookies aren't exposed to app widgets.

Keys that start with `__meta:` are reserved for internal use. Operations with reserved keys throw or reject with `InvalidAccessError`. Write operations that exceed the app quota reject with `QuotaExceededError`.

```TYPESCRIPT
type AppStorage = {
    getItem(key: string): Promise<string | null>;
    setItem(key: string, value: string): Promise<void>;
    removeItem(key: string): Promise<void>;
    clear(): Promise<void>;
    getKeys(): Promise<string[]>;
};
```

| Method | Description |
| --- | --- |
| `getItem(key)` | Returns the stored value for the key, or `null` when the key doesn't exist. |
| `setItem(key, value)` | Stores a string value for the key. |
| `removeItem(key)` | Removes the stored value for the key. If the key doesn't exist, the operation has no effect. |
| `clear()` | Removes all values from the app storage area. |
| `getKeys()` | Returns all keys stored by the app. |

Here you can find a sample code that stores and reads widget settings:

```JAVASCRIPT
const host = await YTApp.register();

const settings = {
    theme: 'dark',
    collapsedGroups: ['done', 'archived']
};

await host.storage.setItem('settings', JSON.stringify(settings));

const rawSettings = await host.storage.getItem('settings');
const restoredSettings = rawSettings ? JSON.parse(rawSettings) : {};
```

### requestParams

The `requestParams` object is an extended version of the [Ring UI RequestParams](https://github.com/JetBrains/ring-ui/blob/4c8d21a1afe8479335ad4a880a93119d79164f2d/src/http/http.ts#L43C18-L43C31), which builds upon the Fetch API's [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/RequestInit) object with a few key differences.

Unlike `RequestInit` in the standard Fetch API, `RequestParams`:

* includes the `query` parameter to pass the query parameters for the call.

* automatically provides the necessary call header: `"Accepts": "application/json"`.

* automatically stringifies the `body` parameter.

In addition to the base properties supported by the `RequestInit` object, `requestParams` supports the following supplemental properties:

| Property | Description |
| --- | --- |
| `query` | A JavaScript object containing key-value pairs that are used as query parameters for the HTTP request. For example:      ```JSON const query = {     key: '12345',     shelterID: 'abc00',     count: 20,     animals: true }; ```   |
| `scope` | A Boolean property that indicates whether the request should be made to a scoped or global endpoint. Pass `true` for scoped handlers. This ensures that the scope entity will be available for the handler from the context. For more details, see [Scope](apps-reference-http-handlers.html#scope).      ```JAVASCRIPT // appResponse is a parsed JSON: const appResponse = await host.fetchApp('backend/demo', {scope: true}); console.log('test', appResponse.test); ```    |

## Custom Widget API Reference

Apps that use the [DASHBOARD_WIDGET](apps-reference-extension-points.html#places-dashboard-widget) and [MARKDOWN](apps-reference-extension-points.html#places-markdown) extension points generate a special embedding component each time its widgets are inserted into a dashboard or text field. This component stores the data the widget displays in these locations. As a result, these widgets are supported by a more extensive API that we call the `CustomWidgetAPILayer`.

Here is the list of additional methods that are supported for these extension points.

### setTitle

```
setTitle(label: string, ?labelUrl: string): void
```

Sets the text displayed in the widget header. If a value is specified for the `labelUrl` parameter, the text is set as a link to the target URL.

Only available for widgets that use the `DASHBOARD_WIDGET` or `MARKDOWN` extension points.

| Parameter | Type | Description | Required |
| --- | --- | --- | --- |
| `label` | String | The string that is shown as the widget title. | ✓ |
| `labelURL` | String | The address of the target page that opens when a user clicks the widget title. If this optional parameter is not specified, the widget title is set as text only. |   |

### setLoadingAnimationEnabled

```
setLoadingAnimationEnabled(isEnabled: boolean): void
```

Toggles the image rotation animation for the widget reload icon. Call this method when the widget populates data from a remote server to indicate that a process is running in the background.

Only available for widgets that use the `DASHBOARD_WIDGET` or `MARKDOWN` extension points.

| Parameter | Type | Description | Required |
| --- | --- | --- | --- |
| `isEnabled` | Boolean | Determines whether the widget reload icon rotates or not. | ✓ |

### enterConfigMode

```
enterConfigMode(): void
```

Invokes configuration mode. When in configuration mode, the visual presentation of the widget changes to indicate that its settings can be updated. The refresh icon is also hidden.

Only available for widgets that use the `DASHBOARD_WIDGET` or `MARKDOWN` extension points.

### exitConfigMode

```
exitConfigMode(): void
```

Exits configuration mode.

### setError

```
setError(e: Error): void
```

Sets an error state in the widget, displaying an error message or taking other error-handling actions.

Only available for widgets that use the `DASHBOARD_WIDGET` or `MARKDOWN` extension points.

| Parameter | Type | Description | Required |
| --- | --- | --- | --- |
| `e` | Error | The error object that contains details about the error. | ✓ |

### clearError

```
clearError(): void
```

Clears any previously set error state in the widget.

Only available for widgets that use the `DASHBOARD_WIDGET` or `MARKDOWN` extension points.

### readCache

```
readCache(): Promise<unknown>
```

> **Note:**
> Deprecated. Use [host.storage](#storage) for new widgets.

Reads data previously stored in the cache. Returns a promise that resolves to the cached data.

Only available for widgets that use the `DASHBOARD_WIDGET` or `MARKDOWN` extension points.

### storeCache

```
storeCache(data: unknown): Promise<Void>
```

> **Note:**
> Deprecated. Use [host.storage](#storage) for new widgets.

Stores any object in the client-side cache. Use this method to store populated data locally and display it immediately in the widget, then refresh it from the server. Returns a promise that resolves when the data is successfully stored.

Only available for widgets that use the `DASHBOARD_WIDGET` or `MARKDOWN` extension points.

| Parameter | Type | Description | Required |
| --- | --- | --- | --- |
| `data` | Unknown | Specifies the data to be stored in the cache. | ✓ |

### readConfig

```
readConfig(): Promise<unknown>
```

Reads the widget configuration data. Returns a promise that resolves to the configuration data.

The schema for the config object must be declared in the `settingsSchemaPath` property of the widget manifest. Any undeclared payloads are ignored.

Only available for widgets that use the `DASHBOARD_WIDGET` or `MARKDOWN` extension points.

### storeConfig

```
storeConfig(config: unknown): Promise<Void>
```

Stores configuration data for the widget. Exits configuration mode if configuration mode is active.

The schema for the config object must be declared in the `settingsSchemaPath` property of the widget manifest. Any undeclared payloads are ignored.

Returns a promise that resolves when the configuration data is successfully stored.

Only available for widgets that use the `DASHBOARD_WIDGET` or `MARKDOWN` extension points.

| Parameter | Type | Description | Required |
| --- | --- | --- | --- |
| `config` | Unknown | The configuration data to be stored. | ✓ |

### downloadFile

```
downloadFile(serviceID: string, relativeURL: string, requestParams: unknown, fileName?: string): Promise<void>
```

Downloads a file from a specified service.

Returns a promise that resolves when the file is successfully downloaded.

Only available for widgets that use the `DASHBOARD_WIDGET` or `MARKDOWN` extension points.

| Parameter | Type | Description | Required |
| --- | --- | --- | --- |
| `serviceID` | String | The ID of the service from which the file will be downloaded. | ✓ |
| relativeURL | String | The relative URL path to the file within the service. | ✓ |
| requestParams | Unknown | Parameters to be included in the request. | ✓ |
| fileName | String | The name of the file to be downloaded. If not specified, the service may provide a default name. |   |

### fetchHub

```
fetchHub(relativeURL: string, requestParams: RequestParams): unknown
```

Fetches data from the Hub service that is connected to or built into YouTrack. Similar to the `fetch` method but specifically designed for Hub services.

Returns the fetched data. The return type depends on the information retrieved from the service.

Only available for widgets that use the `DASHBOARD_WIDGET` or `MARKDOWN` extension points.

| Parameter | Type | Description | Required |
| --- | --- | --- | --- |
| `relativeURL` | String | Sets the URL to the Hub service API endpoint. This is the path to the resource that you want to fetch. The URL is relative to the server home URL. For more information, refer to the [Hub documentation](https://www.jetbrains.com.cn/en-us/help/hub/Hub-Rest-Api-URL.html). | ✓ |
| `requestParams` | RequestParams | Optional parameters that you want to include in the request. |   |

For example:

```TYPESCRIPT
CustomWidgetAPILayer.fetchHub('api/rest/users/me?fields=name,login,profile(avatar(url))')
    .then(response => console.log(response));
```

The following example shows how to use this method in a POST request:

```TYPESCRIPT
host.fetchHub('api/rest/users/me', {
    method: 'POST',
    body: {favoriteProjects: []}
    })
    .then(response => console.log(response));
```

### alert

```
alert(...args: Parameters<(typeof AlertService)['addAlert']>): void
```

Displays a system alert in the lower left corner of the page.

This is a wrapper for the [AlertService](https://github.com/JetBrains/ring-ui/blob/22c62cf9728e732d6ad8ecbedbf0acb335981854/src/alert-service/alert-service.tsx) component from the JetBrains Ring UI component library.

Only available for widgets that use the `DASHBOARD_WIDGET` or `MARKDOWN` extension points.

| Parameter | Type | Description | Required |
| --- | --- | --- | --- |
| `args` | Parameters | The parameters required by the `addAlert` method of the `AlertService`. | ✓ |

For example:

```TYPESCRIPT
host.alert('Hello world', 'success', 5000)
```

### removeWidget

```
removeWidget(): void
```

Removes the embedded widget from the user interface.

Only available for widgets that use the `DASHBOARD_WIDGET` or `MARKDOWN` extension points.

