> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cognite.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Flows Auth API

> Reference for connectToHostApp and the HostAppAPI for apps running in Cognite Data Fusion (CDF).

Authentication and host communication APIs for Flows applications running in CDF.

Use these APIs when building Flows custom apps that need authenticated access to CDF resources. The `connectToHostApp` function establishes communication with the CDF host window and gives you a `HostAppAPI` instance to retrieve credentials and construct an authenticated Cognite SDK.

## Prerequisites

* A Flows app created with [`npx @cognite/cli@latest apps create`](/cdf/flows/guides/getting-started)
* Basic understanding of React hooks and `useEffect`

## Related guides

* [Get started with Cognite Flows](/cdf/flows/guides/getting-started) — Create your first app
* [Run your app locally](/cdf/flows/guides/running-locally) — Development with authentication
* [Flows features](/cdf/flows/concepts/features) — TanStack Query integration with `connectToHostApp`
* [App state in URLs](/cdf/flows/guides/shareable-app-state-with-urls) — Save and restore state with `syncInternalState`

## connectToHostApp

Connects your app to the CDF host window and returns a `HostAppAPI` instance.

```tsx theme={"languages":{"custom":["/_languages/kuiper.json","../_languages/kuiper.json"]}}
import { connectToHostApp } from "@cognite/app-sdk";

const { api } = await connectToHostApp();
```

### Return value

| Property       | Type                  | Description                                                              |
| -------------- | --------------------- | ------------------------------------------------------------------------ |
| `api`          | `HostAppAPI`          | API for communicating with the CDF host                                  |
| `initialState` | `string \| undefined` | Restored state from a previous session (if `syncInternalState` was used) |

### Example: connect and get project

```tsx theme={"languages":{"custom":["/_languages/kuiper.json","../_languages/kuiper.json"]}}
import { useEffect, useState } from "react";
import { connectToHostApp } from "@cognite/app-sdk";

function App() {
  const [project, setProject] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | undefined>();

  useEffect(() => {
    let cancelled = false;
    connectToHostApp()
      .then(async ({ api }) => {
        if (cancelled) return;
        const proj = await api.getProject();
        if (!cancelled) setProject(proj);
      })
      .catch((err: unknown) => {
        if (cancelled) return;
        setError(err instanceof Error ? err.message : String(err));
      })
      .finally(() => {
        if (!cancelled) setIsLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error}</div>;
  return <div>Project: {project}</div>;
}
```

## HostAppAPI

The `HostAppAPI` interface is returned by `connectToHostApp` and provides methods for interacting with the CDF host.

### getProject

Returns the current CDF project name.

```ts theme={"languages":{"custom":["/_languages/kuiper.json","../_languages/kuiper.json"]}}
const project = await api.getProject();
```

### getBaseUrl

Returns the base URL of the CDF cluster (for example, `https://greenfield.cognitedata.com`).

```ts theme={"languages":{"custom":["/_languages/kuiper.json","../_languages/kuiper.json"]}}
const baseUrl = await api.getBaseUrl();
```

### getAccessToken

Returns the current access token for authenticating CDF API calls.

```ts theme={"languages":{"custom":["/_languages/kuiper.json","../_languages/kuiper.json"]}}
const token = await api.getAccessToken();
```

### Example: construct a CogniteClient

Use `getProject`, `getBaseUrl`, and `getAccessToken` together to build an authenticated `CogniteClient` from `@cognite/sdk`:

```tsx theme={"languages":{"custom":["/_languages/kuiper.json","../_languages/kuiper.json"]}}
import { useEffect, useState } from "react";
import { connectToHostApp } from "@cognite/app-sdk";
import { CogniteClient } from "@cognite/sdk";

function App() {
  const [sdk, setSdk] = useState<CogniteClient | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | undefined>();

  useEffect(() => {
    let cancelled = false;
    connectToHostApp()
      .then(async ({ api }) => {
        if (cancelled) return;
        const [project, baseUrl] = await Promise.all([
          api.getProject(),
          api.getBaseUrl(),
        ]);
        const client = new CogniteClient({
          project,
          baseUrl,
          getToken: () => api.getAccessToken(),
        });
        if (!cancelled) setSdk(client);
      })
      .catch((err: unknown) => {
        if (cancelled) return;
        setError(err instanceof Error ? err.message : String(err));
      })
      .finally(() => {
        if (!cancelled) setIsLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error}</div>;
  // pass sdk down or use context
}
```

### navigateInternal

Navigates to a path within CDF.

```ts theme={"languages":{"custom":["/_languages/kuiper.json","../_languages/kuiper.json"]}}
await api.navigateInternal({
  path: "/my-other-app",
  queryParams: { tab: "overview" },
});
```

| Parameter     | Type                                | Description                      |
| ------------- | ----------------------------------- | -------------------------------- |
| `path`        | `string`                            | CDF-relative path to navigate to |
| `queryParams` | `Record<string, string>` (optional) | Query parameters                 |
| `hash`        | `string` (optional)                 | URL hash fragment                |

### navigateExternal

Opens an external URL.

```ts theme={"languages":{"custom":["/_languages/kuiper.json","../_languages/kuiper.json"]}}
await api.navigateExternal({
  url: "https://docs.cognite.com",
  openInNewTab: true,
});
```

| Parameter      | Type                 | Description               |
| -------------- | -------------------- | ------------------------- |
| `url`          | `string`             | HTTPS URL to navigate to  |
| `openInNewTab` | `boolean` (optional) | Open in a new browser tab |

### syncInternalState

Saves a serialized state string to the `customAppInternalState` URL search param. The saved state is passed back as `initialState` the next time the app mounts. Users can return to the same view after navigating away or refreshing. Because the state lives in the URL, the link is shareable.

```ts theme={"languages":{"custom":["/_languages/kuiper.json","../_languages/kuiper.json"]}}
const handled = await api.syncInternalState(
  JSON.stringify({ view: "dashboard", assetId: "12345" })
);
```

| Parameter | Type     | Required | Description                                                                    |
| --------- | -------- | -------- | ------------------------------------------------------------------------------ |
| `state`   | `string` | Yes      | JSON-serialized state. Must be a string. Call `JSON.stringify` before passing. |

|             |                                                                                                                                            |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| **Returns** | `Promise<boolean>`. `true` if the host saved the state; `false` if the host did not handle the call (for example, in standalone dev mode). |

<Tip>
  See [App state in URLs](/cdf/flows/guides/shareable-app-state-with-urls) for a full guide covering state restoration, what to include in persisted state, and a complete example.
</Tip>
