Getting started with the JavaScript SDK

In this article:

Installation

Install the package with yarn:

$ yarn add @cognite/sdk
1

or npm

$ npm install @cognite/sdk --save
1

Usage

const { CogniteClient } = require('@cognite/sdk');
1

Using ES modules

import { CogniteClient } from '@cognite/sdk';
1

Using TypeScript

The SDK is written in native TypeScript, and you don't have to define any extra types.

Quickstart

Web

import { CogniteClient } from '@cognite/sdk';
async function quickstart() {
  const client = new CogniteClient({ appId: 'YOUR APPLICATION NAME' });
  client.loginWithOAuth({
    project: 'publicdata',
  });
  const assets = await client.assets.list().autoPagingToArray({ limit: 100 });
}
quickstart();
1
2
3
4
5
6
7
8
9
10
11

For more details, see the authentication guide. Also, visit the comprehensive introduction guide with a demo app here.

Backend

const { CogniteClient } = require('@cognite/sdk');
async function quickstart() {
  const client = new CogniteClient({ appId: 'YOUR APPLICATION NAME' });
  client.loginWithApiKey({
    project: 'publicdata',
    apiKey: 'YOUR_SECRET_API_KEY',
  });
  const assets = await client.assets.list().autoPagingToArray({ limit: 100 });
}
quickstart();
1
2
3
4
5
6
7
8
9
10
11
12

Hello, world! - React App

This guide shows you how to create a simple app using the Cognite JavaScript SDK. The app authenticates with, and fetches data from, Cognite Data Fusion (CDF).

The simplest way to retrieve data from CDF is to use an SDK. In this guide we use data from the Open Industrial Data project.

To use this guide you need to have npm installed on your machine.

  1. Install the create-react-app.
npx create-react-app hello-world
cd hello-world
1
2
  1. Install the Cognite Javascript SDK.
npm install @cognite/sdk --save
1

Now that everything is ready, we can proceed with coding.

To authenticate the SDK and get access to data, you can either use the OAuth login flow, or use API keys. In this example, we will use the OAuth login flow to avoid storing sensitive API keys in the source code. You can find a comprehensive guide to Cognite JS SDK authentication here.

There are two ways to sign in the user:

Authentication with redirect

Replace the code in ./src/App.js:

import React, { Component } from 'react';
import { CogniteClient } from '@cognite/sdk';
const project = 'publicdata';
class App extends Component {
  async componentDidMount() {
    const client = new CogniteClient({ appId: 'Cognite SDK tutorial' });
    client.loginWithOAuth({ project });
    client.authenticate();
  }
  render() {
    return <div className="App"></div>;
  }
}
export default App;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

To test the authentication it is important to enable SSL or HTTPS. Cognite only allows trusted webpages to authenticate.

  1. In a terminal window, run:
HTTPS=true npm run start
1
  1. Check the result in a browser. You should be able to sign in to the publicdata project.

  2. When we have authenticated the SDK, we are ready to fetch data. In this example, we will fetch 10 assets. client.authenticate() is redundant here, as the SDK calls it automatically on API request, and we have removed it from the code below. In ./src/App.js:

import React, { Component } from 'react';
import { CogniteClient } from '@cognite/sdk';
const project = 'publicdata';
class App extends Component {
  state = {
    assets: null,
  };
  async componentDidMount() {
    const client = new CogniteClient({ appId: 'Cognite SDK tutorial' });
    client.loginWithOAuth({ project });
    const assets = await client.assets.list().autoPagingToArray({ limit: 10 });
    this.setState({ assets });
  }
  render() {
    return <div className="App"></div>;
  }
}
export default App;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  1. We will do a very basic visualization of the assets we just fetched, and only print out the asset names. In ./src/App.js:
import React, { Component } from 'react';
import { CogniteClient } from '@cognite/sdk';
const project = 'publicdata';
class App extends Component {
  state = { assets: null };
  async componentDidMount() {
    const client = new CogniteClient({ appId: 'Cognite SDK tutorial' });
    client.loginWithOAuth({ project });
    const assets = await client.assets.list().autoPagingToArray({ limit: 10 });
    this.setState({ assets });
  }
  render() {
    const { assets } = this.state;
    return (
      <div className="App">
        {assets && assets.map((asset) => <p key={asset.id}>{asset.name}</p>)}
      </div>
    );
  }
}
export default App;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

That's it - you have now successfully fetched data using the SDK.

TIP

You can find the source code for the example application here.

Authentication with popup

You can authenticate the SDK by providing a popup window. The benefit is that you don’t lose the state of the application. Let's change our code to use a popup window. We'll also do some refactoring, to make the code more readable and add a button, so we can call the popup on user interaction and avoid having the popup window blocked by the browser. In ./src/App.js:

import React, { Component } from 'react';
import {
  CogniteClient,
  POPUP,
  loginPopupHandler,
  isLoginPopupWindow,
} from '@cognite/sdk';
const project = 'publicdata';
class App extends Component {
  state = {
    assets: null,
    client: null,
  };
  async componentDidMount() {
    if (isLoginPopupWindow()) {
      loginPopupHandler();
      return;
    }
    const client = new CogniteClient({ appId: 'Cognite SDK tutorial' });
    client.loginWithOAuth({
      project,
      onAuthenticate: POPUP,
    });
    this.setState({ client });
  }
  fetchAssets = async () => {
    const { client } = this.state;
    const assets = await client.assets.list().autoPagingToArray({ limit: 10 });
    this.setState({ assets });
  };
  renderAssets = () => {
    return (
      <>
        {this.state.assets.map((asset) => (
          <p key={asset.id}>{asset.name}</p>
        ))}
      </>
    );
  };
  render() {
    const { assets } = this.state;
    return (
      <div className="App">
        {assets ? (
          this.renderAssets()
        ) : (
          <button onClick={this.fetchAssets}>
            <h1>Click here to fetch assets from Cognite</h1>
          </button>
        )}
      </div>
    );
  }
}
export default App;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

TIP

You can find the source code for the example application here.

Last Updated: 9/10/2020, 12:11:40 PM