# Using the Web SDK via Package Manager
source: https://developer.mastercard.com/open-finance-au/documentation/connect/integrating-with-connect/web-sdk/sdk/index.md

You can either use npm to install the SDK, or download our starter pack and use the code provided (this will install what it needs). If you prefer not to download or install anything via package manager, you can reference it as needed [via our CDN](https://developer.mastercard.com/open-finance-au/documentation/connect/integrating-with-connect/web-sdk/web-sdk-cdn/index.md) (using the ESM, UMD, or IIFE module formats).

## Installation Options {#installation-options}

If you have an existing web project that uses a module compiler, such as Webpack or Babel, or you want to start from scratch, install the SDK direct from npm. If you haven't used a module compiler before, or want to get started with some helpful scaffolding code, download the Starter Code.

Click the tabs below depending on your preference.

The Connect Web SDK is available for installation via Node Package Manager (npm). You will need Node.js and npm in order to install the Web SDK. If you are not familiar with this process, see the [npm docs](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm).

1. If you don't already use node modules in your project you can create a `package.json` file using the following terminal command: `npm init -y`

2. Then, to install the Open Finance Web SDK you can use the following commands:

   * For Open Finance Web SDK version 1.x: `npm install connect-web-sdk core-js --save`

   * For Open Finance Web SDK version 2.0 or higher: `npm install connect-web-sdk --save`

Note: `core-js` is a peer dependency for the Open Bank Web SDK which you must install if you are installing a version of the Open Finance Web SDK which is earlier than 2.0.0.

From version 2.0.0 on, `connect-web-sdk` no longer requires CoreJS as a peer dependency. This change might affect projects that relied on our package to provide CoreJS functionality. Since we are no longer supporting IE and older browsers, we have removed the `core-js` peer dependency and `core-js-pure` dependency. If you were installing CoreJS solely because of our package's peer dependency, you may now remove it from your project if it is not needed for other purposes.

Once you have installed the SDK refer to the [example code](https://developer.mastercard.com/open-finance-au/documentation/connect/integrating-with-connect/web-sdk/sdk/index.md#example-code) below to see how to launch a Connect instance.
Tip: You can view the SDK source code on [Github](https://github.com/Mastercard/connect-web-sdk). The starter code demonstrates using the Web SDK in `TypeScript`, using [`webpack`](https://webpack.js.org/) as a module bundler.

1. Download the starter code:
   [openfinance-webpack.zip](https://static.developer.mastercard.com/content/open-finance-au/code/openfinance-webpack.zip) (64KB).

2. After downloading, install the node modules by navigating to the folder the code resides in and running the following command: `npm i`. Note that this will install `connect-web-sdk` and `core-js` so you don't have to run the command mentioned in the installation instructions when using this starter code.

Once all the modules have downloaded, visit the `index.ts` page, which contains the code that uses the Connect Web SDK. All you need to do is add the URL that you received when [generating a Connect URL](https://developer.mastercard.com/open-finance-au/documentation/connect/generate-2-connect-url-apis/index.md) into the `connectURL` variable.

## SDK Parameters {#sdk-parameters}

|            Parameter            |                              Description                               |
|---------------------------------|------------------------------------------------------------------------|
| connectURL (required)           | The SDK loads the Connect URL provided to show the Connect experience. |
| connectEventHandlers (required) | A class implementing the EventHandler interface.                       |
| connectOptions (optional)       | Additional options that can be passed.                                 |

### Additional SDK Options {#additional-sdk-options}

The SDK provides the following additional Connect options. You do not need to set any of these options unless you want to change some aspect of the default behavior. Note that some options are mutually exclusive.

|    Option    |                                                                                                                       Description                                                                                                                        |
|--------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| overlay      | Changes the overlay color where the Connect modal is displayed (only for iframe, defaults to rgba(0,0,0,0.8)). Not applicable if Connect is displayed in a popup.                                                                                        |
| selector     | CSS selector in which Connect should be embedded. Connect will expand to fill the container's dimensions, the element's position must not be static. Connect will be displayed in a modal by default. Not applicable if Connect is displayed in a popup. |
| node         | Element in which Connect should be embedded. Connect will expand to fill the container's dimensions, the element's position must not be static. Connect will be displayed in a modal by default. Not applicable if Connect is displayed in a popup.      |
| popup        | Indicates if Connect should be displayed in a popup (defaults to false).                                                                                                                                                                                 |
| popupOptions | If Connect is being displayed in a popup (see the popup boolean value above) then this option can be used to configure the popup's width/height and positioning (top/left).                                                                              |

## Callback Events {#callback-events}

The Web SDK provides the following events which you must provide handlers for:

|  Event   |                            Description                             |
|----------|--------------------------------------------------------------------|
| onDone   | Sent when the user successfully completes the Connect application. |
| onCancel | Sent when the user cancels the Connect application.                |
| onError  | Sent when there is an error during the Connect application.        |

Optionally, you can also provide handlers for the following events:

|  Event  |                                                                                                            Description                                                                                                             |
|---------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| onLoad  | Sent when the Connect web page is loaded and ready to display.                                                                                                                                                                     |
| onRoute | Sent when the user navigates to a new route or screen in Connect,                                                                                                                                                                  |
| onUser  | Sent when a user performs an action. User events provide visibility into what action a user could take within the Connect application.                                                                                             |
| onUrl   | Sent when a popup is triggered from the Connect application. This allows for custom handling of URL events, so that the partner application can handle the the popup. **Note:** This event is not used in the Deposit Switch flow. |

Warning: If you provide a handler for the onUrl event you must manage popups gracefully. The Connect SDK will not handle popups for you if this handler is provided. Only provide a handler for this event if you want to diverge from the default behavior.

The onUrl handler accepts two parameters:

1. `type`: A string literal that can be either `OPEN` or `CLOSE`.
   * `OPEN`: Indicates that a URL should be opened.
   * `CLOSE`: Indicates that a URL event should be closed.
2. `url`: An optional string parameter that is only present when type is `OPEN`. This represents the URL to be opened.

## Example Code {#example-code}

* TypeScript

```TypeScript
import { Connect, ConnectEventHandlers, ConnectOptions, ConnectDoneEvent,
         ConnectCancelEvent, ConnectErrorEvent, ConnectRouteEvent } from 'connect-web-sdk';

const connectURL = 'replace with your generated connect url';

const connectEventHandlers: ConnectEventHandlers = {
    onDone: (event: ConnectDoneEvent) => { console.log(event); },
    onCancel: (event: ConnectCancelEvent) => { console.log(event); },
    onError: (event: ConnectErrorEvent) => { console.log(event); },
    onRoute: (event: ConnectRouteEvent) => { console.log(event); },
    onUser: (event: any) => { console.log(event); },
    onLoad: () => { console.log('loaded'); },
    onUrl: (type, url) => {
      if (type === 'OPEN' && url) {
        console.log(`Opening URL: ${url}`);
        // Custom logic to open a URL
        window.open(url, 'targetWindow', 'width=600,height=600');
      } else if (type === 'CLOSE') {
        console.log('Closing..');
        // Custom logic to close
      }
    }
  };

  const connectOptions: ConnectOptions = {
    overlay: 'rgba(199,201,199, 0.5)'
  };

  Connect.launch( connectURL, connectEventHandlers, connectOptions );
```

After adding your connect URL you can create a build using the starter code with the following command `npm run build`.

This will use webpack to create a JavaScript distribution bundle that the `index.html` file loads. Once the build is successful you can load the html file in the `dist` folder, using a local server, and you will see the Connect experience load.

### Using a Popup Window {#using-a-popup-window}

As per the Connect options, you have the choice of starting the Connect experience in a popup window. When doing so you must supply the `redirectUri` in the [Generate Connect URL](https://developer.mastercard.com/open-finance-au/documentation/connect/generate-2-connect-url-apis/index.md) request body to supply a web page to redirect Connect users to when they are finished.

Here is an example of a request to generate a Connect URL using the `redirectUri` parameter:

```JSON
{
  "partnerId": "{{PARTNER_ID}}", "customerId": "{{CUSTOMER_ID}}",
  "consumerId": "{{CONSUMER_ID}}",
  "redirectUri": "https://example.com/redirectHandler",
  "webhook": "{{WEBHOOK}}",
  "webhookContentType": "application/json"
}
```

With the returned Connect URL you can open the experience in a new window as follows:
* TypeScript

```TypeScript
import { Connect, ConnectEventHandlers, ConnectOptions, ConnectDoneEvent,
         ConnectCancelEvent, ConnectErrorEvent, ConnectRouteEvent } from 'connect-web-sdk';

const connectURL = 'https://connect2.finicity.com/?customerId=5025447962&origin=url&partnerId=2445583330983&redirectUri=https://example.com/redirectHandler&signature=2eb1bc83fd04b89d2ba0cfd9d2dcca572f76d59afc47f4654299cab1a230b34b&timestamp=1653319208065&ttl=1653326408065&webhook=https://webhook.site/a787d273-87b8-452b-b05a-b52a92e5b266&webhookContentType=application/json';

const connectEventHandlers: ConnectEventHandlers = {
  onDone: (event: ConnectDoneEvent) => { console.log(event); },
  onCancel: (event: ConnectCancelEvent) => { console.log(event); },
  onError: (event: ConnectErrorEvent) => { console.log(event); },
  onRoute: (event: ConnectRouteEvent) => { console.log(event); },
  onUser: (event: any) => { console.log(event); },
  onLoad: () => { console.log('loaded'); }
};

const connectOptions: ConnectOptions = {
  popup: true,
  popupOptions: {
    width: 600,
    height: 600,
    top: window.top.outerHeight / 2 + window.top.screenY - (600 / 2),
    left: window.top.outerWidth / 2 + window.top.screenX - (600 / 2)
  }
};

Connect.launch( connectURL, connectEventHandlers, connectOptions );
```

When the user finishes with Connect, they will be redirected to the web page that was supplied in the `redirectUri` parameter. After the user completes Connect, report data is also returned through the `redirectUri` parameter specified:

```sh
https://example.com/redirectHandler/?success=true&reasonCode=OK&id=quu1svkssc89&portfoliold=90w9y4t1eq5f-port&requestld=jhrsmfrkgf&consumerld=8c58c61c257e3e257a1d19d4d06f5e0b&consumerSsn=6789&type=voa&status=inProgress&source=Finicity%2520Connect&reportld=quu1svkssc89
```

