{"id":13588,"library":"near-api-js","title":"NEAR JavaScript API","description":"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.","status":"active","version":"7.2.0","language":"javascript","source_language":"en","source_url":"https://github.com/near/near-api-js","tags":["javascript"],"install":[{"cmd":"npm install near-api-js","lang":"bash","label":"npm"},{"cmd":"yarn add near-api-js","lang":"bash","label":"yarn"},{"cmd":"pnpm add near-api-js","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"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.","wrong":"const { Account } = require('near-api-js')","symbol":"Account","correct":"import { Account } from 'near-api-js'"},{"note":"Use `JsonRpcProvider` for standard RPC connections; there are other provider types like `FailoverRpcProvider` for redundancy.","wrong":"import { Provider } from 'near-api-js'","symbol":"JsonRpcProvider","correct":"import { JsonRpcProvider } from 'near-api-js'"},{"note":"This helper converts NEAR tokens to yoctoNEAR (the smallest unit). Similarly, `teraToGas` is used for gas conversions.","wrong":"import { convertNearToYocto } from 'near-api-js'","symbol":"nearToYocto","correct":"import { nearToYocto } from 'near-api-js'"}],"quickstart":{"code":"import { Account, JsonRpcProvider, teraToGas, KeyPairString, nearToYocto } from \"near-api-js\";\n\n// Configure your connection to a NEAR testnet RPC endpoint\nconst provider = new JsonRpcProvider({\n  url: \"https://test.rpc.fastnear.com\",\n});\n\n// For read-only calls (e.g., viewing contract state), you can use the provider directly\nconst messages = await provider.callFunction({\n  contractId: 'guestbook.near-examples.testnet',\n  method: \"get_messages\",\n  args: {},\n});\n\nconsole.log(\"Guestbook messages:\", messages);\n\n// To modify blockchain state, you need an account with a signer (private key)\nconst accountId: string = 'example.testnet'; // Replace with an actual account ID\n// WARNING: Never hardcode private keys in production. Use environment variables or secure key management.\nconst privateKey = process.env.NEAR_PRIVATE_KEY ?? 'ed25519:YOUR_PRIVATE_KEY_HERE' as KeyPairString;\n\nif (privateKey === 'ed25519:YOUR_PRIVATE_KEY_HERE') {\n  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.\");\n} else {\n  const account = new Account(accountId, provider, privateKey);\n\n  // Call a mutable contract method to add a message\n  const result = await account.callFunction({\n    contractId: 'guestbook.near-examples.testnet',\n    methodName: \"add_message\",\n    args: { text: `Hello from near-api-js at ${new Date().toISOString()}!` },\n    gas: teraToGas('30'), // Attach 30 TeraGas for execution\n    deposit: nearToYocto('0.1'), // Attach 0.1 NEAR as deposit\n  });\n\n  console.log(\"Transaction result:\", result);\n}\n","lang":"typescript","description":"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."},"warnings":[{"fix":"Ensure `parseNearAmount` is called with valid numeric strings or numbers. Implement proper error handling for invalid input instead of checking for `null`.","message":"Version 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.","severity":"breaking","affected_versions":">=7.0.0"},{"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'`).","message":"With 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.","severity":"breaking","affected_versions":">=7.0.0"},{"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.","message":"`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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"When 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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"search_vec":"'account':51 'advanc':105 'api':3,6,23 'applic':134 'approach':89 'backend':41,133 'batteri':87 'batteries-includ':86 'blockchain':19 'browser':78,126 'build':54 'call':63 'case':144 'clis':43 'comprehens':48 'consolid':29 'contract':58 'convers':96 'core':31 'current':24 'design':72 'develop':39 'differenti':83 'direct':61 'e.g':97 'environ':81 'featur':106 'friend':92 'frontend':142 'full':67 'function':33 'gas':103 'helper':93 'improv':115 'includ':84,88 'interact':14,59 'javascript':2,145 'javascript/typescript':11 'js':7 'key':55,82,113 'librari':12,37,65,128 'like':107 'login':138 'manag':52,56,119 'multipl':112 'near':1,5,17,32,98 'near-api-j':4 'node.js':80 'nonc':118 'offer':66 'offici':10,136 'packag':28 'parallel':108 'perform':116 'primarili':130 'protocol':18 'provid':47 'recommend':131 'rpc':22,62 'script':45 'seamless':75 'send':110 'servic':42 'simplifi':38 'singl':36 'smart':57 'solut':139 'suggest':140 'support':69 'teraga':101 'tool':49 'transact':53,109 'typescript':68 'unit':95 'use':111,124,143 'user':91 'user-friend':90 'v7.2.0':26 'via':20 'web':137 'work':74 'yoctonear':100","created_at":"2026-04-20T01:55:16.656811+00:00","updated_at":"2026-04-20T01:55:16.656811+00:00","problems":[{"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.","cause":"The `provider` object (e.g., `JsonRpcProvider`) was not correctly initialized or the RPC URL is invalid/unreachable.","error":"TypeError: Cannot read properties of undefined (reading 'callFunction') or similar for RPC methods"},{"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.","cause":"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.","error":"Error: Cannot find module 'near-api-js' or 'require() of ES Module ... not supported'"},{"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.","cause":"The provided `accountId` in an `Account` constructor or transaction call does not correspond to an existing account on the specified NEAR network.","error":"Error: Account not found for 'nonexistent.testnet'"},{"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.","cause":"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`).","error":"TypeError: Invalid private key format"}],"ecosystem":"npm","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null,"type":"library","homepage":"https://docs.near.org/tools/near-api-js","github":"https://github.com/near/near-api-js","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/near-api-js","openapi_spec":null,"status_page":null,"smithery":null,"categories":["http-networking","auth-security","serialization"],"base_url":null,"auth_type":null,"provenance":{"verified_status":null,"verified_at":null,"last_verified":"2026-06-17","next_check":"2026-07-18","install_tag":null}}