Registry / http-networking / near-api-js

near-api-js

JSON →
library7.2.0jsnpmunverified

near-api-js is the official JavaScript/TypeScript library for interacting with the NEAR Protocol blockchain via its RPC API. Currently at v7.2.0, this package consolidates all core NEAR functionality into a single library, simplifying development for backend services, CLIs, and scripts. It provides comprehensive tools for account management, transaction building, key management, smart contract interaction, and direct RPC calls. The library offers full TypeScript support and is designed to work seamlessly in both browser and Node.js environments. Key differentiators include its 'batteries-included' approach, user-friendly helpers for unit conversions (e.g., NEAR to yoctoNEAR, TeraGas to Gas), and advanced features like parallel transaction sending using multiple keys for improved performance and nonce management. While it can be used in browsers, the library is primarily recommended for backend applications, with official web login solutions suggested for frontend use cases.

npm install near-api-js
INSTALL
IMPORT
SIG · NEAR-API-JS
N
near-api-js
http-networkingjavascriptv7.2.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Account
import { Account } from 'near-api-js'
const { Account } = require('near-api-js')
near-api-js is primarily designed for ESM imports in modern JavaScript/TypeScript projects. CommonJS `require` might lead to issues in some environments or older versions.
JsonRpcProvider
import { JsonRpcProvider } from 'near-api-js'
import { Provider } from 'near-api-js'
Use `JsonRpcProvider` for standard RPC connections; there are other provider types like `FailoverRpcProvider` for redundancy.
nearToYocto
import { nearToYocto } from 'near-api-js'
import { convertNearToYocto } from 'near-api-js'
This helper converts NEAR tokens to yoctoNEAR (the smallest unit). Similarly, `teraToGas` is used for gas conversions.

This quickstart demonstrates both read-only RPC calls using a provider and state-changing contract calls requiring an `Account` and `KeyPairString` for signing, including unit conversions for gas and deposit.

import { Account, JsonRpcProvider, teraToGas, KeyPairString, nearToYocto } from "near-api-js"; // Configure your connection to a NEAR testnet RPC endpoint const provider = new JsonRpcProvider({ url: "https://test.rpc.fastnear.com", }); // For read-only calls (e.g., viewing contract state), you can use the provider directly const messages = await provider.callFunction({ contractId: 'guestbook.near-examples.testnet', method: "get_messages", args: {}, }); console.log("Guestbook messages:", messages); // To modify blockchain state, you need an account with a signer (private key) const accountId: string = 'example.testnet'; // Replace with an actual account ID // WARNING: Never hardcode private keys in production. Use environment variables or secure key management. const privateKey = process.env.NEAR_PRIVATE_KEY ?? 'ed25519:YOUR_PRIVATE_KEY_HERE' as KeyPairString; if (privateKey === 'ed25519:YOUR_PRIVATE_KEY_HERE') { console.warn("WARNING: Please set the NEAR_PRIVATE_KEY environment variable or replace the placeholder in quickstart. The example will not modify state without a valid key."); } else { const account = new Account(accountId, provider, privateKey); // Call a mutable contract method to add a message const result = await account.callFunction({ contractId: 'guestbook.near-examples.testnet', methodName: "add_message", args: { text: `Hello from near-api-js at ${new Date().toISOString()}!` }, gas: teraToGas('30'), // Attach 30 TeraGas for execution deposit: nearToYocto('0.1'), // Attach 0.1 NEAR as deposit }); console.log("Transaction result:", result); }
Debug
Known issues
breakingVersion 7.0.0 introduced breaking changes to `parseNearAmount`. It now strictly accepts only numeric strings or actual numbers and will throw an error for invalid input, rather than silently returning `null`. This requires updating any code that relied on the previous behavior or handled `null` returns.
fix
Ensure `parseNearAmount` is called with valid numeric strings or numbers. Implement proper error handling for invalid input instead of checking for `null`.
affects: >=7.0.0
breakingWith v7.0.0, the `near-api-js` library consolidated functionality previously spread across multiple `@near-js/*` monorepo packages (e.g., `@near-js/accounts`, `@near-js/crypto`, `@near-js/providers`) into a single package. Projects migrating from the older modular structure must update their imports.
fix
Refer to the `MIGRATION.md` guide in the repository. Replace imports from individual `@near-js/*` packages with direct imports from `near-api-js` (e.g., `import { Account } from '@near-js/accounts'` becomes `import { Account } from 'near-api-js'`).
affects: >=7.0.0
gotcha`near-api-js` is primarily designed for backend services, CLIs, and scripts. While usable in the browser, for frontend applications requiring user authentication (e.g., wallet login), the official `web login docs` and `Wallet Selector` are recommended for a more secure and integrated experience.
fix
For frontend applications with user interaction, integrate with `Wallet Selector` and follow the official web login documentation for authentication and transaction signing. Use `near-api-js` for its utility functions or read-only public data queries.
affects: >=1.0.0
gotchaWhen handling private keys, always use secure methods like environment variables (e.g., `process.env.NEAR_PRIVATE_KEY`) or dedicated key management systems. Hardcoding private keys directly in your application code is a severe security risk, especially in production environments.
fix
Store private keys in environment variables, use a secrets management service, or integrate with a secure KeyStore (`near-api-js` supports various keystores for Node.js and browser). Never commit private keys to version control.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: Cannot read properties of undefined (reading 'callFunction') or similar for RPC methods
The `provider` object (e.g., `JsonRpcProvider`) was not correctly initialized or the RPC URL is invalid/unreachable.
fix
Ensure `new JsonRpcProvider({ url: 'YOUR_RPC_URL' })` is correctly configured with a valid and accessible NEAR RPC endpoint (e.g., `https://test.rpc.fastnear.com`). Check network connectivity and firewall rules.
Error: Cannot find module 'near-api-js' or 'require() of ES Module ... not supported'
Attempting to `require()` `near-api-js` in a CommonJS module when the library is primarily published as an ES Module, or when your project environment is not configured for ESM.
fix
If using Node.js, ensure your project is configured for ES Modules (e.g., `"type": "module"` in `package.json`) and use `import` statements. For older CommonJS environments, ensure you are on a compatible `near-api-js` version or use dynamic `import()` if supported.
Error: Account not found for 'nonexistent.testnet'
The provided `accountId` in an `Account` constructor or transaction call does not correspond to an existing account on the specified NEAR network.
fix
Verify that the `accountId` is spelled correctly and exists on the target network (e.g., `testnet`, `mainnet`). You can use a NEAR explorer to confirm account existence.
TypeError: Invalid private key format
The `privateKey` string provided to the `Account` constructor or a `KeyPair` factory function does not adhere to the expected format (e.g., `ed25519:YOUR_PRIVATE_KEY_BASE58`).
fix
Ensure the private key string is correctly formatted, typically starting with `ed25519:` followed by the base58-encoded private key. Double-check for typos or truncation.
Upgrade
Version history
7.2.0latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
15 hits · last 30 days
node
10
Amazon
1
OpenAI (training)
1
Resources