Nhảy đến nội dung chính

Using JavaScript API to interact with NEAR

Quick Reference

What is near-api-js

near-api-js is a complete library to interact with the NEAR blockchain. You can use it in the browser, or in Node.js runtime.

You'll typically first create a connection to NEAR with connect using a KeyStore. With the connection object you now can:

  • Interact with the Wallet in a browser.
  • Instantiate an Account object to:
    • Send tokens
    • Deploy contracts
    • Inspect, create or delete accounts
    • Manage keys for accounts.
  • Instantiate a Contract object to call smart contract methods.

The library also contains some utility functions.

To quickly get started with integrating NEAR in a web browser, read our Web Frontend integration article. :::
Note the difference between near-api-js and near-sdk-js:

The JavaScript SDK is a library for developing smart contracts. It contains classes and functions you use to write your smart contract code.

The JavaScript API is a complete library for all possible commands to interact with NEAR. It’s a wrapper for the RPC endpoints, a library to interact with NEAR Wallet in the browser, and a tool for keys management. :::


Include near-api-js as a dependency in your package.

npm i --save near-api-js


You can use the API library in the browser, or in Node.js runtime. Some features are available only in one of the environments. For example, the WalletConnection is only for the browser, and there are different KeyStore providers for each environment.

import * as nearAPI from "near-api-js";

Lưu trữ key

If you sign transactions, you need to create a Key Store. In the browser, the LocalStorage KeyStore will be used once you ask your user to Sign In with the Wallet.

// creates keyStore using private key in local storage

const { keyStores } = nearAPI;
const myKeyStore = new keyStores.BrowserLocalStorageKeyStore();

Class BrowserLocalStorageKeyStore

Connecting to NEAR

The object returned from connect is your entry-point for all commands in the API. To sign a transaction you'll need a KeyStore to create a connection.

const { connect } = nearAPI;

const connectionConfig = {
networkId: "testnet",
keyStore: myKeyStore, // first create a key store
nodeUrl: "https://rpc.testnet.near.org",
walletUrl: "https://testnet.mynearwallet.com/",
helperUrl: "https://helper.testnet.near.org",
explorerUrl: "https://testnet.nearblocks.io",
const nearConnection = await connect(connectionConfig);

Module connect

Was this page helpful?