# Iota Browser

> The Iota Browser library provides front-end methods to initiate the request and parse the response from the Affinidi Iota Framework for the WebSocket data-sharing mode.

## Install Dependency

Package: @affinidi-tdk/iota-browser

```bash
npm install @affinidi-tdk/iota-browser --save
```

Check the latest version on the [npm registry](https://www.npmjs.com/package/@affinidi-tdk/iota-browser) or view the source on [GitHub](https://github.com/affinidi/affinidi-tdk/tree/main/libs/iota-browser).

## Implementation Note

The Iota Browser library is a browser-only module; make sure to invoke the library on the client side. It creates a WebSocket connection and requires access to the browser window object to initiate a data request to the Affinidi Vault.

If you are using a framework that has a server-side rendering like NextJS, you can do the following:

-          Window Checking

-          Dynamic Import

Check the availability of the Window object when rendering.

```typescript
useEffect(() => {
    if (typeof window !== 'undefined') {
        const initIota = async () => {
            const iotaSession = new Session({ credentials: iotaCredentials });
            await iotaSession.initialize();

        }
        initIota()
    }
}
```

Wrap the Iota Browser code in a component and disable the SSR with NextJS [Dynamic Imports](https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading#nextdynamic)

```typescript
import dynamic from 'next/dynamic'

const IotaClientComponent = dynamic(() => import('components/Iota/IotaClientComponent'), {
  ssr: false,
})

export default function Page() {
  return 
}
```

## Classes and Methods

### Session

Sets up and manages the request to Affinidi Iota Framework. To initialise Session, generate the Iota Credential using the [iota-core package](/dev-tools/affinidi-tdk.md#libraries#limitedtokentoiotacredentials) and pass it as a parameter.

Constructor parameters

    credentials
    SessionParams
    Required
  Iota Credentials object generated from limitedTokenToIotaCredentials.

Example

```typescript
const credentials = await getIotaCredentials(configurationId)
const iotaSession = new Session({ credentials })
```

getIotaCredentials is an async function that calls an exposed API endpoint from the backend to generate the Iota Credentials.

#### initialize

Initialises the Iota Session, opening a WebSocket that listens for callback events from the Affinidi Iota Framework service.

No parameters required.

Example

```typescript
const iotaSession = new Session({ credentials })

await iotaSession.initialize()
```

#### prepareRequest

Creates an IotaRequest object from the initialised Iota Session. The response contains the signed Request Token for the Affinidi Vault to request data.

Parameters

    params
    PrepareRequestParams
    Required
  Query ID (required), and optionally correlation ID and audience.

Example

```typescript
const request = await iotaSession.prepareRequest({ queryId })
```

### IotaRequest

Initiates the data-sharing flow between the application and Affinidi Vault. Obtained from the [prepareRequest](/dev-tools/affinidi-tdk.md#libraries#preparerequest) method.

#### openVault

Opens Affinidi Vault with the signed Request Token and queries the data.

Parameters

    params
    OpenVaultParams
    Optional
  Optionally accepts the Affinidi Vault URL and the mode to open it (NewTab is the default).

Example

```typescript
const iotaRequest = await iotaSession.prepareRequest({ queryId })

iotaRequest.openVault({ mode: openMode })
```

#### getResponse

Retrieves the response from Affinidi Vault through the open WebSocket.

No parameters required.

Example

```typescript
const iotaRequest = await iotaSession.prepareRequest({ queryId })
iotaRequest.openVault({ mode: openMode })

const response = await iotaRequest.getResponse()
```

### Check for Iota Request Response

To check if an Iota Request is a valid response and parse the Verifiable Presentation (verifiablePresentation), use the IotaResponse instance.

Example

```typescript
const iotaRequest = await iotaSession.prepareRequest({ queryId })
iotaRequest.openVault({ mode: openMode })

const response = await iotaRequest.getResponse()

if (response instanceof IotaResponse) {
  // parse the Verifiable Presentation and do business logic
}
```

### Check for Iota Request Error

To check if an Iota Request has failed and parse the error information, use the IotaError instance.

Example

```typescript
try {
  const iotaCredentials = await getIotaCredentials()
  const iotaSession = new Session({ credentials: iotaCredentials })
  await iotaSession.initialize()
} catch (error) {
  if (error instanceof IotaError) {
    console.log(error.code)
  }
}
```
