Installation
Install and configure Stacks.js packages for your project
Package overview
Stacks.js is modular - install only the packages you need for your use case:
Package | Description | Use case |
---|---|---|
@stacks/connect | Wallet connection and web app integration | Web apps that need wallet connectivity |
@stacks/transactions | Transaction building and encoding | All apps that interact with contracts |
@stacks/network | Network configuration and API client | Configuring mainnet/testnet connections |
@stacks/encryption | Encryption and key management | Apps that need to encrypt data or manage keys |
@stacks/storage | Gaia storage integration | Apps that store user data |
@stacks/wallet-sdk | Wallet generation utilities | Creating new wallets programmatically |
@stacks/stacking | PoX stacking operations | Apps that interact with stacking |
@stacks/bns | Bitcoin Name System | Apps that work with BNS names |
Installation by use case
Web application with wallet
For a typical web app that connects to user wallets:
$npm install @stacks/connect @stacks/transactions @stacks/network
This gives you:
- Wallet connection UI
- Transaction building
- Network configuration
Node.js/CLI application
For backend services or command-line tools:
$npm install @stacks/transactions @stacks/network @stacks/encryption
This provides:
- Transaction creation and signing
- Network connectivity
- Key management utilities
Full-stack application
For apps that need comprehensive Stacks functionality:
$npm install @stacks/connect @stacks/transactions @stacks/network @stacks/storage @stacks/encryption
Framework-specific setup
Next.js
For Next.js applications, you may need to handle server-side rendering:
'use client';import { AppConfig, UserSession } from '@stacks/connect';import { ReactNode, useState, useEffect } from 'react';const appConfig = new AppConfig(['store_write']);const userSession = new UserSession({ appConfig });export function StacksProvider({ children }: { children: ReactNode }) {const [mounted, setMounted] = useState(false);useEffect(() => {setMounted(true);}, []);if (!mounted) return null;return <>{children}</>;}
Then wrap your app:
import { StacksProvider } from './providers';export default function RootLayout({children,}: {children: React.ReactNode;}) {return (<html lang="en"><body><StacksProvider>{children}</StacksProvider></body></html>);}
Vite
For Vite projects, you might need to configure polyfills:
import { defineConfig } from 'vite';import react from '@vitejs/plugin-react';import { nodePolyfills } from 'vite-plugin-node-polyfills';export default defineConfig({plugins: [react(),nodePolyfills({// Enable specific polyfillsglobals: {Buffer: true,global: true,process: true,},}),],});
Create React App
For CRA projects, install required polyfills:
$npm install --save-dev react-app-rewired crypto-browserify stream-browserify buffer
Create config-overrides.js
:
const webpack = require('webpack');module.exports = function override(config) {config.resolve.fallback = {crypto: require.resolve('crypto-browserify'),stream: require.resolve('stream-browserify'),buffer: require.resolve('buffer'),};config.plugins.push(new webpack.ProvidePlugin({Buffer: ['buffer', 'Buffer'],}));return config;};
TypeScript configuration
Stacks.js is written in TypeScript and provides comprehensive type definitions. No additional setup needed, but ensure your tsconfig.json
includes:
{"compilerOptions": {"target": "ES2020","lib": ["ES2020", "DOM", "DOM.Iterable"],"module": "ESNext","moduleResolution": "bundler","strict": true,"esModuleInterop": true,"skipLibCheck": true}}
Environment setup
Network configuration
Configure different networks for your environments:
import { StacksMainnet, StacksTestnet, StacksMocknet } from '@stacks/network';export const network = (() => {switch (process.env.NEXT_PUBLIC_NETWORK) {case 'mainnet':return new StacksMainnet();case 'testnet':return new StacksTestnet();case 'devnet':return new StacksMocknet();default:return new StacksTestnet();}})();
Environment variables
Common environment variables for Stacks apps:
# Network configurationNEXT_PUBLIC_NETWORK=testnet# API endpoints (optional - defaults are provided)NEXT_PUBLIC_STACKS_API=https://api.testnet.hiro.soNEXT_PUBLIC_BITCOIN_API=https://blockstream.info/testnet/api# Contract addressesNEXT_PUBLIC_CONTRACT_ADDRESS=ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGMNEXT_PUBLIC_CONTRACT_NAME=my-contract
Troubleshooting
Common issues
"Buffer is not defined" error
This occurs in browser environments. Install polyfills:
$npm install buffer
Add to your app's entry point:
import { Buffer } from 'buffer';window.Buffer = Buffer;
"Can't resolve 'crypto'" error
Install the crypto polyfill:
$npm install crypto-browserify
Configure your bundler to use it (see framework-specific setup above).
TypeScript errors with node types
Install node types as a dev dependency:
$npm install --save-dev @types/node
Verify installation
Create a simple test to verify everything is working:
import { makeSTXTokenTransfer, AnchorMode } from '@stacks/transactions';import { StacksTestnet } from '@stacks/network';async function testSetup() {try {const network = new StacksTestnet();console.log('✅ Network configured:', network.coreApiUrl);const tx = await makeSTXTokenTransfer({recipient: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',amount: 1000000,fee: 200,nonce: 0,network,anchorMode: AnchorMode.Any,// Note: Don't include senderKey for wallet-based appssenderKey: 'your-private-key-here', // Only for testing!});console.log('✅ Transaction created:', tx.txid());} catch (error) {console.error('❌ Setup error:', error);}}testSetup();
Run with:
$npx tsx test-setup.ts[32m✅ Network configured:[0m https://api.testnet.hiro.so[32m✅ Transaction created:[0m 0x123...