š Zero-config browser SDK for automatic log capture - console, network requests, user interactions, performance metrics, Core Web Vitals. Sends to your own Cloudflare Worker. Full TypeScript support.
npm install stackscopeš Zero-config browser SDK for automatic log capture - console, network requests, user interactions, performance metrics, Core Web Vitals. Requires StackScope Worker (separate package) for log collection. Full TypeScript support.
If you encounter CLI issues (ERR_USE_AFTER_CLOSE, interactive prompts failing):
- ā
Use non-interactive setup - Complete worker setup without prompts (see Step 1 below)
- ā
React developers: Jump to React Quick Start
- ā
Troubleshooting: See Worker Setup Troubleshooting
ā ļø BOTH packages are required:
- š stackscope (this package) - Browser SDK for log capture
- āļø stackscope-worker (separate package) - Cloudflare Worker for log processing
Without the worker, logs are only visible in browser console and NOT collected centrally. The worker is required for both development and production environments.
- šÆ Simplified API - createStackScope() with auto environment detection
- š Pre-built Logger - Ready-to-use logger object
- ā” Utility Functions - trackUserAction(), trackPerformance(), trackApiCall()
- āļø React Integration - Components, hooks, and error boundaries
- š§ Environment Variables - Auto-detection for Vite, Next.js, CRA
- š¦ Better Types - Complete TypeScript definitions
- š”ļø Zero Vulnerabilities - Secure dependencies
š Recommended: Non-Interactive Setup
``bashWorks in CI/CD, Claude Code, and automated environments
node node_modules/stackscope/scripts/create-worker-noninteractive.cjs my-app-logs
cd my-app-logs
npm install
node deploy.js # Deploys to Cloudflare automatically
`
šļø Alternative: StackScope Worker CLI
`bashInstall StackScope Worker CLI globally
npm install -g stackscope-worker
> ā ļø CLI Limitation: The
stackscope-worker init command requires an interactive terminal and fails in CI/CD, Claude Code, and automated environments. Use the non-interactive setup script above for these environments.šļø Worker is Required: The StackScope worker is required for both development and production to receive and process logs from your application. Without it, logs are only shown in the browser console and not collected centrally.
$3
`bash
npm install stackscope
`$3
Copy the environment template:
`bash
cp node_modules/stackscope/templates/.env.example .env
`Set your worker URL:
`bash
.env
VITE_STACKSCOPE_WORKER_URL=https://my-app-logs.your-username.workers.dev
`$3
š New Simple API:
`javascript
import { createStackScope } from 'stackscope';// Auto-detects VITE_STACKSCOPE_WORKER_URL from environment
const stackscope = createStackScope();
`Traditional API:
`javascript
import { init } from 'stackscope';const stackscope = init({
workerUrl: 'https://my-app-logs.your-username.workers.dev'
});
`That's it! Your application now automatically captures and sends logs to your worker.
āļø React Quick Start
Skip the worker complexity - get started with React components immediately:
$3
`bash
npm install stackscope
`$3
`jsx
import { StackScopeProvider, StackScopeErrorBoundary } from 'stackscope/react';function App() {
return (
);
}
`$3
`jsx
import { useStackScopeLogger } from 'stackscope/react';function MyComponent() {
const logger = useStackScopeLogger();
const handleClick = () => {
logger.info('Button clicked', { component: 'MyComponent' });
};
return ;
}
`ā
Complete setup required - Both SDK and Worker needed for full functionality!
š API Log Streaming (New!)
Automatically capture logs from your Cloudflare Worker APIs and stream them to StackScope for complete full-stack observability.
$3
`bash
1. Deploy your StackScope worker (if not done already)
npm install stackscope
node node_modules/stackscope/scripts/create-worker-noninteractive.cjs my-app-logs
cd my-app-logs && npm install && node deploy.js2. Stream API logs in real-time
./stream-api-logs.sh ../my-api-worker production
`$3
š HTTP Requests & Responses:
`json
{
"request": {
"url": "https://api.myapp.com/users/123",
"method": "GET",
"headers": {"authorization": "Bearer *"},
"cf": {"country": "US", "colo": "LAX"}
},
"response": {"status": 200}
}
`š Worker Console Logs:
`javascript
// In your API worker:
console.log('Processing user request', {userId: 123});
console.error('Database connection failed', error);// ā
Automatically captured and sent to StackScope
`ā ļø Exceptions & Errors:
`json
{
"exceptions": [{
"name": "TypeError",
"message": "Cannot read property 'id' of undefined",
"stack": "at handler (worker.js:42:15)"
}]
}
`š Performance & Edge Data:
- Request timing and diagnostics
- Cloudflare edge location (colo)
- Geographic data (country, region)
- Cache status and performance metrics
$3
Multiple Environments:
`bash
Development environment
./stream-api-logs.sh ../my-api-worker developmentProduction with custom StackScope URL
STACKSCOPE_URL="https://my-logs.workers.dev" ./stream-api-logs.sh ../my-api-worker
`Manual Streaming:
`bash
If you prefer direct control
cd ../my-api-worker
wrangler tail --env production --format json | \
while read -r line; do
echo "$line" | curl -X POST https://my-app-logs.workers.dev/webhook/api \
-H "Content-Type: application/json" \
-H "X-Source: api-manual" \
-d @-
done
`Integration with CI/CD:
`bash
Background streaming in production
nohup ./stream-api-logs.sh ../my-api-worker production > api-stream.log 2>&1 &
`$3
ā
Browser Logs (StackScope SDK) ā Console, network, interactions, performance
ā
API Logs (Wrangler tail) ā Requests, responses, worker console, exceptions
Result: Single dashboard showing your entire application stack!
Features
- š Zero Configuration - Works out of the box with sensible defaults
- š Automatic Capture - Console, network, interactions, performance, navigation
- š API Log Streaming - Stream Cloudflare Worker API logs via Wrangler tail
- š Private Infrastructure - Your own Cloudflare Worker, not shared
- š± TypeScript Support - Full type definitions included
- š Global Edge - Low latency via Cloudflare's global network
- šÆ Customizable - Configure what to capture and how
Automatic Capture
The SDK automatically captures:
$3
`javascript
console.log('User action'); // ā
Captured
console.error('API failed'); // ā
Captured
console.warn('Deprecated'); // ā
Captured
`$3
`javascript
fetch('/api/users'); // ā
Captured (method, URL, status, duration)
XMLHttpRequest calls; // ā
Captured
`$3
`javascript
button.click(); // ā
Captured (element, event type)
form.submit(); // ā
Captured (form data summary)
input.onChange(); // ā
Captured (field changes)
`$3
`javascript
// Core Web Vitals automatically captured:
// - Largest Contentful Paint (LCP)
// - First Input Delay (FID)
// - Cumulative Layout Shift (CLS)
// - Long tasks (>50ms)
`$3
`javascript
window.location.href = '/new'; // ā
Captured (route changes)
history.pushState(); // ā
Captured (SPA navigation)
page load/reload; // ā
Captured
`$3
`javascript
// Page focus/blur, tab switching, page unload
window.blur(); // ā
Captured
window.beforeunload(); // ā
Captured
`šÆ New v2.0 APIs
$3
Import and use immediately:
`javascript
import { logger } from 'stackscope';logger.info('User logged in', { userId: 123 });
logger.error('API failed', { endpoint: '/users' });
logger.debug('Cache hit', { key: 'user:123' });
`$3
Ready-to-use tracking functions:
`javascript
import { trackUserAction, trackPerformance, trackApiCall } from 'stackscope';// Track user interactions
trackUserAction('button_click', { buttonId: 'signup', page: '/home' });
trackUserAction('form_submit', { formType: 'contact', fields: 5 });
// Track performance metrics
trackPerformance('api_response_time', 245, 'ms');
trackPerformance('bundle_size', 1.2, 'MB');
// Track API calls with automatic error levels
trackApiCall('/api/users', 'GET', 200, 150); // Info level
trackApiCall('/api/users', 'POST', 500, 300); // Error level
`$3
Auto-detection for popular frameworks:
`bash
Vite
VITE_STACKSCOPE_WORKER_URL=https://your-worker.workers.dev
VITE_STACKSCOPE_API_KEY=optional-api-key
VITE_STACKSCOPE_DEBUG=trueNext.js
NEXT_PUBLIC_STACKSCOPE_WORKER_URL=https://your-worker.workers.dev
NEXT_PUBLIC_STACKSCOPE_API_KEY=optional-api-keyCreate React App
REACT_APP_STACKSCOPE_WORKER_URL=https://your-worker.workers.dev
REACT_APP_STACKSCOPE_API_KEY=optional-api-key
`āļø React Integration
$3
Automatically catch and log React errors:
`javascript
import { StackScopeErrorBoundary } from 'stackscope/react';function App() {
return (
);
}
`$3
`javascript
import {
useStackScopeLogger,
useUserActionTracking,
usePerformanceTracking
} from 'stackscope/react';function MyComponent() {
const logger = useStackScopeLogger();
const { trackClick, trackFormSubmit } = useUserActionTracking();
const { trackRenderTime } = usePerformanceTracking();
useEffect(() => {
const start = performance.now();
// Component logic...
trackRenderTime('MyComponent', performance.now() - start);
}, [trackRenderTime]);
return (
);
}
`$3
Wrap your app for centralized configuration:
`javascript
import { StackScopeProvider } from 'stackscope/react';function App() {
return (
);
}
`Configuration
$3
`javascript
import { createStackScope } from 'stackscope';// Auto-detects environment variables
const stackscope = createStackScope({
// Optional overrides
logLevel: 'error', // Only capture errors and above
debug: true // Verbose logging to browser console
});
`$3
`javascript
import { init } from 'stackscope';const stackscope = init({
workerUrl: 'https://your-worker.workers.dev',
apiKey: 'optional-auth-key',
// Capture controls
captureConsole: true, // Console logs
captureNetwork: true, // HTTP requests
captureInteractions: true, // User interactions
captureNavigation: true, // Page navigation
capturePerformance: true, // Performance metrics
captureVisibility: true, // Visibility events
captureResources: true, // Resource loading errors
// Transport settings
batchInterval: 2000, // ms between batch sends
maxBatchSize: 50, // max logs per batch
maxRetries: 3, // retry failed requests
retryBaseDelay: 1000, // ms delay between retries
// Filtering
logLevel: 'debug' // 'debug' | 'info' | 'warn' | 'error'
});
`$3
If your worker requires API key authentication:
`javascript
const stackscope = new StackScope({
workerUrl: 'https://your-worker.workers.dev',
apiKey: 'your-secret-key' // Set in worker via wrangler secret
});stackscope.start();
`Manual Logging
In addition to automatic capture, you can log manually:
`javascript
// Manual logging with metadata
stackscope.log('info', 'User completed purchase', {
userId: 12345,
amount: 99.99,
currency: 'USD'
});stackscope.log('error', 'Payment processing failed', {
error: 'card_declined',
attemptId: 'pay_123'
});
`Script Tag Usage
For non-module environments:
`html
`Log Format
All logs are sent as NDJSON to your worker:
`json
{
"level": "info",
"msg": "User login successful",
"ts": "2024-01-15T10:30:00.000Z",
"source": "browser",
"meta": {
"type": "console",
"sessionId": "sess_abc123",
"url": "https://app.example.com/login",
"userId": 12345
}
}
`$3
- browser - Frontend application logs
- worker - Your Cloudflare Worker logs
- github - Repository webhook events (if configured)$3
- console - Console output
- network - HTTP requests
- interaction - User interactions
- navigation - Page navigation
- performance - Performance metrics
- visibility - Page visibility changesViewing Logs
$3
`bash
Stream logs from your worker
wrangler tailFilter with jq
wrangler tail --format json | jq 'select(.level == "error")'
wrangler tail --format json | jq 'select(.meta.type == "performance")'
`$3
`bash
Check worker deployment status
wrangler deployments listTest specific worker URL
curl https://your-worker.workers.dev/health
`Error Handling
The SDK handles errors gracefully:
`javascript
const stackscope = new StackScope({
workerUrl: 'https://your-worker.workers.dev',
debug: true // Enable to see error details in console
});// SDK will retry failed requests automatically
// and degrade gracefully if worker is unavailable
stackscope.start();
`Browser Compatibility
- Modern Browsers: Chrome 60+, Firefox 55+, Safari 12+, Edge 79+
- ES6 Features: Uses modern JavaScript (async/await, fetch, etc.)
- Polyfills: Not included - add if targeting older browsers
TypeScript Support
Full TypeScript definitions included:
`typescript
import StackScope, { SdkConfig, LogLevel } from 'stackscope';const config: SdkConfig = {
workerUrl: 'https://your-worker.workers.dev',
logLevel: 'error' as LogLevel,
debug: true
};
const stackscope = new StackScope(config);
stackscope.start();
// Type-safe manual logging
stackscope.log('info', 'User action', { userId: 123 });
`Performance
- Minimal Overhead: < 30KB minified + gzipped
- Async Operations: Non-blocking log capture and transmission
- Batched Sending: Efficient network usage
- Error Resilience: Continues working if worker is temporarily unavailable
Troubleshooting
$3
1. Check worker URL:
`bash
curl https://your-worker.workers.dev/health
# Should return: {"status": "ok"}
`2. Enable debug mode:
`javascript
const stackscope = new StackScope({
workerUrl: 'https://your-worker.workers.dev',
debug: true // Shows detailed logs in browser console
});
`3. Check browser console for CORS or network errors
4. Verify worker deployment:
`bash
wrangler deployments list
`$3
If you see CORS errors and are using API key authentication:
`bash
Set allowed origins in your worker
wrangler secret put CORS_ORIGINS
Enter: https://yourdomain.com,https://localhost:3000
`$3
1. Generate test activity - click buttons, navigate, trigger console logs
2. Check worker logs:
wrangler tail
3. Verify network tab shows requests to your worker URL
4. Test worker endpoints with curl (see troubleshooting above)š¦ Two-Package Architecture
StackScope uses a two-package architecture:
$3
- š Browser SDK - Captures logs in your web application
- š¦ Zero dependencies - Lightweight and secure
- āļø React integration - Components, hooks, error boundaries
- š§ Auto-configuration - Environment variable detection$3
- āļø Cloudflare Worker - Receives and processes logs
- šļø Infrastructure CLI - Deployment and management tools
- š GitHub integration - Repository webhook support
- š Log processing - Enrichment and structured output$3
`
Browser App (stackscope) ā Network ā Cloudflare Worker (stackscope-worker)
ā ā
Automatic capture Structured logging
Manual logging GitHub webhooks
React components Health monitoring
`Worker Infrastructure
Install the worker infrastructure separately:
`bash
npm install -g stackscope-worker
stackscope-worker init my-app-logs
Follow setup instructions
`The worker:
- Receives logs from this browser SDK
- Processes and enriches log data with metadata
- Outputs structured logs to worker console
- Supports GitHub webhooks for repository events
- Provides health checks and monitoring endpoints
š§ Worker Setup Troubleshooting
$3
The
stackscope-worker init command fails in non-interactive environments with errors like:
- ERR_USE_AFTER_CLOSE: readline was closed
- ERR_TTY_INIT_FAILED
- Interactive prompts hanging in CI/CDš Solution 1: Non-Interactive Setup Script (Recommended)
`bash
Complete worker setup without any interactive prompts
node node_modules/stackscope/scripts/create-worker-noninteractive.cjs my-workerFollow the generated instructions to deploy
cd my-worker
npm install
node deploy.js
`š ļø Solution 2: Manual Setup
`bash
1. Install worker package
npm install -g stackscope-worker2. Find template directory
npm list -g stackscope-worker3. Copy template manually
cp -r /path/to/global/node_modules/stackscope-worker/templates/worker my-app-logs
cd my-app-logs4. Configure manually
Edit wrangler.toml with your account ID
Edit package.json name field
`Option 2: Non-Interactive Mode
`bash
Set environment variables first
export CF_ACCOUNT_ID="your-account-id"
export CF_API_TOKEN="your-api-token"Try with --yes flag (may still fail)
stackscope-worker init my-app-logs --yes
`
$3
React Import Errors
`bash
Ensure you're using the correct import path
import { StackScopeProvider } from 'stackscope/react'; // ā
Correct
import { StackScopeProvider } from 'stackscope'; // ā Wrong
`Environment Variables Not Working
`bash
Check your build tool's env prefix:
VITE_STACKSCOPE_WORKER_URL=... # ā
Vite
NEXT_PUBLIC_STACKSCOPE_WORKER_URL=... # ā
Next.js
REACT_APP_STACKSCOPE_WORKER_URL=... # ā
Create React App
`TypeScript Errors
`bash
Clear TypeScript cache and reinstall
rm -rf node_modules package-lock.json
npm install
`$3
- š Check GitHub Issues: Known Issues
- š Report Problems: Create New Issue
- š Workers Docs: Cloudflare Workers GuideSupport
- Worker Infrastructure: Install
stackscope-worker` package for deployment toolsMIT License - see LICENSE for details.