Next.js Setup with @alkanes/ts-sdk
Configuring Turbopack, Webpack, and WASM for development and production
This guide documents how to integrate @alkanes/ts-sdk into a Next.js application. The SDK uses WebAssembly (WASM) and requires specific bundler configuration to work correctly in both development and production environments.
Overview
The @alkanes/ts-sdk package contains WASM bindings compiled from Rust. Running WASM in Next.js requires:
- WASM module loading configuration for both Turbopack (dev) and Webpack (production)
- Browser polyfills for Node.js built-ins used by crypto libraries
- Module alias resolution for the WASM entry point
Installation
Install the SDK and required polyfills. The URL below is pinned to the latest commit on the develop branch:
Next.js Configuration
The complete next.config.ts handles both Turbopack (for fast development) and Webpack (for production builds). Here's the full configuration:
import type { NextConfig } from "next";
import path from "path";
import fs from "fs";
import webpack from "webpack";
// Check if local ts-sdk WASM is built (for local development)
const tsSdkWasmPath = path.join(process.cwd(), "ts-sdk/build/wasm/alkanes_web_sys.js");
const hasTsSdk = fs.existsSync(tsSdkWasmPath);
const nextConfig: NextConfig = {
// Turbopack configuration (for dev mode with --turbopack)
turbopack: hasTsSdk
? {
resolveAlias: {
"@alkanes/ts-sdk/wasm": "./ts-sdk/build/wasm/alkanes_web_sys.js",
},
}
: {},
// Webpack configuration (for production and dev with --webpack)
webpack: (config, { isServer }) => {
// WASM alias for local development (only if ts-sdk exists)
if (hasTsSdk) {
config.resolve.alias = {
...config.resolve.alias,
"@alkanes/ts-sdk/wasm": tsSdkWasmPath,
};
}
// Enable async WebAssembly
config.experiments = {
...config.experiments,
asyncWebAssembly: true,
};
// WASM loader rule
config.module.rules.push({
test: /\.wasm$/,
type: "webassembly/async",
});
// Client-side only configuration
if (!isServer) {
// Disable Node.js built-ins for browser
config.resolve.fallback = {
...config.resolve.fallback,
fs: false,
net: false,
tls: false,
crypto: false,
};
// Polyfill Buffer and process for browser
// Required by bitcoinjs-lib, ecpair, randombytes
config.plugins.push(
new webpack.ProvidePlugin({
Buffer: ["buffer", "Buffer"],
process: "process/browser",
})
);
// Define global as globalThis for universal compatibility
config.plugins.push(
new webpack.DefinePlugin({
global: "globalThis",
})
);
}
return config;
},
};
export default nextConfig;Turbopack Configuration (Development)
Turbopack is Next.js's new Rust-based bundler, offering faster refresh times during development. For WASM support, we configure module aliases:
// next.config.ts - Turbopack section
turbopack: {
resolveAlias: {
// Map the WASM import to the built module
"@alkanes/ts-sdk/wasm": "./ts-sdk/build/wasm/alkanes_web_sys.js",
},
},- resolveAlias maps the WASM import path to the built WASM module
- The alias is conditional—only enabled if the WASM files exist
- Run development with: next dev --turbopack or pnpm dev:turbo
Webpack Configuration (Production & Local Dev)
Webpack handles production builds and can be used for local development as an alternative to Turbopack. The configuration includes WASM loading, polyfills, and fallbacks:
WASM Support
Enables async WebAssembly loading with proper module rules
Browser Fallbacks
Disables Node.js modules (fs, net, tls, crypto) that don't exist in browsers
Polyfills
Provides Buffer and process globals required by bitcoinjs-lib and ecpair
Global Definition
Maps 'global' to 'globalThis' for universal compatibility
webpack: (config, { isServer }) => {
// Enable async WebAssembly experiments
config.experiments = {
...config.experiments,
asyncWebAssembly: true,
};
// Add WASM loader
config.module.rules.push({
test: /\.wasm$/,
type: "webassembly/async",
});
// Client-side configuration
if (!isServer) {
// Fallbacks for Node.js built-ins
config.resolve.fallback = {
...config.resolve.fallback,
fs: false,
net: false,
tls: false,
crypto: false,
};
// Provide Buffer and process globally
config.plugins.push(
new webpack.ProvidePlugin({
Buffer: ["buffer", "Buffer"],
process: "process/browser",
})
);
// Map global to globalThis
config.plugins.push(
new webpack.DefinePlugin({
global: "globalThis",
})
);
}
return config;
},Required Polyfills
The SDK depends on Bitcoin libraries that require Node.js globals. These must be polyfilled for browser environments:
| Global | Package | Why Needed |
|---|---|---|
| Buffer | buffer | Used by bitcoinjs-lib for binary data handling |
| process | process/browser | Used by randombytes and other crypto utilities |
These packages are included as dependencies and webpack's ProvidePlugin makes them globally available.
Development Modes
You can choose between two development modes based on your needs:
Turbopack (Recommended)
next dev --turbopackScript: pnpm dev:turbo
Pros:
- Faster hot module replacement
- Lower memory usage
- Incremental compilation
Cons:
- Newer, may have edge cases
Webpack
next dev --webpackScript: pnpm dev
Pros:
- Battle-tested
- More plugin compatibility
- Same as production
Cons:
- Slower rebuild times
Package.json Scripts
Configure these scripts for easy switching between modes:
{
"scripts": {
"dev": "next dev --webpack",
"dev:turbo": "next dev --turbopack",
"build": "next build --webpack",
"start": "next start"
}
}WASM Module Aliasing
The SDK exports WASM bindings at @alkanes/ts-sdk/wasm. This path must resolve to the compiled WebAssembly module:
// The SDK imports WASM like this:
import { someWasmFunction } from '@alkanes/ts-sdk/wasm';
// This resolves to (depending on your setup):
// - npm package: node_modules/@alkanes/ts-sdk/wasm/alkanes_web_sys.js
// - local build: ./ts-sdk/build/wasm/alkanes_web_sys.jsIf you're using the SDK from npm, the WASM files are included in the package. If building locally, ensure ts-sdk/build/wasm/alkanes_web_sys.js exists.
Local SDK Development
When developing the SDK locally alongside your Next.js app, the configuration detects the local build:
import path from "path";
import fs from "fs";
// Check if local WASM build exists
const tsSdkWasmPath = path.join(process.cwd(), "ts-sdk/build/wasm/alkanes_web_sys.js");
const hasTsSdk = fs.existsSync(tsSdkWasmPath);
// Conditionally apply alias based on local build availability
turbopack: hasTsSdk
? { resolveAlias: { "@alkanes/ts-sdk/wasm": "./ts-sdk/build/wasm/alkanes_web_sys.js" } }
: {},- Clone the ts-sdk repository to ./ts-sdk
- Build the WASM module: cd ts-sdk && pnpm build:wasm
- The config automatically detects and uses the local build
TypeScript Configuration
Add path aliases for the SDK in your tsconfig.json:
{
"compilerOptions": {
"paths": {
"@/*": ["./*"],
"@/ts-sdk": ["./ts-sdk"],
"@/ts-sdk/*": ["./ts-sdk/*"]
}
},
"exclude": [
"ts-sdk" // Exclude local SDK from type checking if needed
]
}Testing Configuration
For Vitest or other test runners, you'll need similar WASM handling. Here's a vitest.config.ts example:
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
import wasm from 'vite-plugin-wasm';
import topLevelAwait from 'vite-plugin-top-level-await';
export default defineConfig({
plugins: [react(), wasm(), topLevelAwait()],
test: {
environment: 'happy-dom',
},
resolve: {
alias: {
'@alkanes/ts-sdk/wasm': 'ts-sdk/build/wasm/index.js',
'@alkanes/ts-sdk': 'ts-sdk/dist/index.mjs',
},
},
optimizeDeps: {
exclude: ['@alkanes/ts-sdk'],
},
server: {
deps: {
inline: ['@alkanes/ts-sdk'],
},
},
});Troubleshooting
Error: Cannot find module '@alkanes/ts-sdk/wasm'
Ensure the WASM files are built. For local development, run the build:wasm script in the ts-sdk directory. For npm packages, reinstall the dependency.
ReferenceError: Buffer is not defined
The ProvidePlugin configuration is missing or not applied to client bundles. Ensure the polyfill config is inside the !isServer block.
ReferenceError: process is not defined
Add the process polyfill to ProvidePlugin. Use 'process/browser' (not 'process') to avoid including the full Node.js process module.
Turbopack: WASM module not loading
Verify the resolveAlias path is correct. Turbopack requires relative paths starting with './' for local files.
Build error: Can't resolve 'fs' (or net, tls, crypto)
Add browser fallbacks in webpack config: resolve.fallback = { fs: false, net: false, tls: false, crypto: false }
Complete Example
Here's a minimal example using the SDK in a Next.js component:
"use client";
import { useEffect, useState } from "react";
import { AlkanesProvider } from "@alkanes/ts-sdk";
export function BlockHeight() {
const [height, setHeight] = useState<number | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
async function fetchHeight() {
try {
const provider = new AlkanesProvider({
network: "mainnet",
rpcUrl: process.env.NEXT_PUBLIC_RPC_URL,
});
// Initialize loads the WASM module
await provider.initialize();
// Now we can use the provider
const currentHeight = await provider.getBlockHeight();
setHeight(currentHeight);
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to fetch");
} finally {
setLoading(false);
}
}
fetchHeight();
}, []);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
return <div>Current Block Height: {height?.toLocaleString()}</div>;
}Resources
- Next.js Turbopack Docs – Official Turbopack documentation
- Next.js Webpack Config – Customizing webpack configuration
- @alkanes/ts-sdk Guide – Full SDK usage documentation
- alkanes-rs GitHub – SDK source code