bitbabit / magento2-dev-tools
Advanced developer tools for Magento 2 with dynamic control and visualization
Package info
github.com/bitbabit/magento2-dev-tools
Language:JavaScript
Type:magento2-module
pkg:composer/bitbabit/magento2-dev-tools
Requires
- php: ^8.1|^8.2|^8.3
- magento/framework: ^103.0
- magento/module-backend: ^102.0
- magento/module-config: ^101.0
- magento/module-store: ^101.0
Requires (Dev)
- magento/magento-coding-standard: ^33.0
- phpstan/phpstan: ^1.0
- phpunit/phpunit: ^9.0|^10.0
- squizlabs/php_codesniffer: ^3.6
Suggests
- magento/module-developer: For enhanced developer mode features
This package is auto-updated.
Last update: 2026-04-02 06:19:54 UTC
README
Overview
BitBabit Developer Tools is a comprehensive development and debugging suite for Magento 2 that provides real-time performance monitoring, database query profiling, and advanced debugging capabilities. It features a modern, interactive web-based toolbar similar to Symfony's DebugBar or Laravel Debugbar.
Key Features
🔍 Database Query Profiling
- Real-time SQL query monitoring with execution times
- Slow query detection and highlighting
- Query parameter binding visualization
- Query type analysis (SELECT, INSERT, UPDATE, DELETE)
- Comprehensive query statistics
⚡ Performance Monitoring
- Application execution time tracking
- Memory usage monitoring (current, peak, real usage)
- Bootstrap time measurement
- Server load monitoring
- OPcache status and statistics
🛡️ Security & Authentication
- API key-based authentication system
- Secure header validation (
X-Debug-Api-Key) - Developer mode restrictions
- Cookie-based session management
🌐 Request Analysis
- HTTP request/response monitoring
- Header inspection
- Parameter analysis (GET, POST, FILES)
- Session data examination
- AJAX request interception
🖥️ Environment Information
- PHP version and configuration
- Server software details
- Operating system information
- PHP extensions listing
- Timezone and locale settings
🐛 Advanced Debugging
- Multi-level debug logging (info, warning, error, debug)
- Contextual debug messages
- Interactive JSON tree visualization
- Real-time message collection
📱 Interactive Web Interface
- Modern, responsive toolbar widget
- Real-time data updates
- Collapsible panels
- Multi-request tracking
- Mobile-friendly design
Installation
Via Composer (Recommended)
composer require bitbabit/magento2-dev-tools bin/magento module:enable BitBabit_DeveloperTools bin/magento setup:upgrade php bin/magento setup:di:compile bin/magento setup:static-content:deploy -f
If the package is not yet published to Packagist, you can install with explicit version:
composer require bitbabit/magento2-dev-tools:^1.2.0 bin/magento module:enable BitBabit_DeveloperTools bin/magento setup:upgrade php bin/magento setup:di:compile bin/magento setup:static-content:deploy -f
Manual Installation
- Download the module files
- Extract to
app/code/BitBabit/DeveloperTools/ - Run the following commands:
bin/magento module:enable BitBabit_DeveloperTools bin/magento setup:upgrade php bin/magento setup:di:compile bin/magento setup:static-content:deploy -f
Quick Setup
After installation, follow these steps to get started:
# Enable the profiler bin/magento bitbabit:devtools:enable # Generate API key for frontend widget bin/magento bitbabit:devtools:generate-api-key # Copy the generated API key for frontend widget usage # Clear cache bin/magento cache:flush
Monolithic Frontend Widget Activation
To enable the profiler widget and save the API key to cookies for persistent profiling:
https://YOUR_FRONTEND_URL?api_key=YOUR_GENERATED_API_KEY
This will:
- Enable the profiler widget on your frontend
- Save the API key to cookies for automatic profiling on subsequent requests
- Allow you to see the profiler widget on all pages
Note: Boot time and memory management features are currently under development, so data may not be 100% accurate.
Configuration
Admin Configuration
Navigate to Stores → Configuration → BitBabit → Developer Tools
Basic Settings
- Enable Developer Tools: Master toggle for the entire module
- Profiler Header Key: HTTP header to trigger profiling (default:
X-Debug-Mode) - Enable HTML Output: Show profiler data for web requests
- Enable JSON Injection: Inject profiler data into API responses
- Developer Mode Only: Restrict profiling to developer mode
- Slow Query Threshold: Highlight queries exceeding this time (ms)
- Toolbar Widget: Enable/disable the floating toolbar
- Memory Limit: Auto-disable threshold to prevent memory issues
API Security Settings
- Enable API Key Validation: Require API key for access
- API Key: Encrypted storage of the authentication key
Console Commands
Enable/Disable Profiler
# Enable profiler bin/magento bitbabit:devtools:enable # Disable profiler bin/magento bitbabit:devtools:disable # Check status bin/magento bitbabit:devtools:status
API Key Management
# Generate new API key bin/magento bitbabit:devtools:generate-api-key # Regenerate existing API key bin/magento bitbabit:devtools:generate-api-key --regenerate
Usage
Basic Usage
- Enable the module in admin configuration
- Generate an API key using the console command
- Configure your browser to send the debug header:
- Header:
X-Debug-Api-Key - Value: Your generated API key
- Header:
- Visit any frontend page to see the toolbar
Browser Extension Integration
The module is designed to work with browser extensions that can inject custom headers:
// Example browser extension configuration headers: { 'X-Debug-Mode': '1', 'X-Debug-Api-Key': 'your-generated-api-key' }
Next.js SSR & npm companion (@bitbabit/devtools-ssr-bridge)
For server-side calls from Next.js (or Node) to Magento, use the published npm package so the same debug headers are added to fetch() (and optionally axios) as in the browser:
- npm:
@bitbabit/devtools-ssr-bridge - Install:
npm i @bitbabit/devtools-ssr-bridge - What it does: patches global
fetch, optional axios interceptors, middleware correlation, and reads config from the__devtools_configcookie (written by the Chrome extension) or from environment variables on the Node process. - Chrome extension: Install the Magento Developer Tools Profiler extension on your storefront / Next origin so it can set that cookie (API key, paths, custom headers). Without the cookie or env fallback, the bridge does not inject headers.
- Env fallback (CI / no extension): on the Node process set
MAGENTO_DEVTOOLS_ENABLED=trueandMAGENTO_DEVTOOLS_API_KEY=<same key as Magento admin>. - Optional debug:
DEVTOOLS_SSR_BRIDGE_DEBUG=1logs bridge diagnostics to the Node console. - Next.js config helper:
import { withDevtoolsSsrBridge } from '@bitbabit/devtools-ssr-bridge/next'. - Instrumentation:
export { register } from '@bitbabit/devtools-ssr-bridge/instrument'(see the package README for axios, middleware, and App Router config API). - Magento REST (SSR logs): the extension panel can read profiler data via
GET /rest/V1/devtools/ssr-logs/:ssrId(requires Magento module enabled, API key validation as documented, and a validssrId). Full setup steps and diagrams are in the npm package README.
If you use only the browser (no Next.js SSR), you do not need the npm package—headers from the extension are enough for Magento.
Reverse proxy & application servers (Nginx / Apache)
Magento must see real client scheme and client IP behind TLS terminators and proxies. The dev tools module also relies on custom headers reaching PHP (X-Debug-Api-Key, your configured Profiler Header Key e.g. X-Debug-Mode, and SSR correlation headers such as X-SSR-ID / X-SSR-Source). If your proxy or app server strips unknown headers, profiling and SSR logging will silently fail.
Nginx (reverse proxy to PHP-FPM or to an upstream app server):
# Standard forwarding — required for HTTPS detection, cookies, and IP proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Host $host; # Developer Tools: ensure these pass through (names must match admin + extension config) # (If you already forward all request headers, you may omit the following lines.) proxy_set_header X-Debug-Api-Key $http_x_debug_api_key; proxy_set_header X-Debug-Mode $http_x_debug_mode; proxy_set_header X-SSR-ID $http_x_ssr_id; proxy_set_header X-SSR-Source $http_x_ssr_source; # If you use custom header names with underscores, nginx ignores them unless: underscores_in_headers on;
Apache (httpd / mod_proxy):
# Preserve client host and forward TLS hint to Magento ProxyPreserveHost On RequestHeader set X-Forwarded-Proto "expr=%{REQUEST_SCHEME}s" # Optional: forward original client IP if behind another proxy RequestHeader set X-Forwarded-For "%{REMOTE_ADDR}e" env=!X-Forwarded-For
mod_proxy forwards request headers to the backend by default; if you use RequestHeader unset or security modules that strip headers, allowlist the same debug headers as above.
Swoole / RoadRunner / FrankenPHP / other app servers: ensure the outer edge (Nginx/Apache) forwards the full header set to the worker; the PHP stack must receive the same headers as a direct browser request.
CDN / Varnish / Fastly: add equivalent pass-through rules so X-Debug-* and X-SSR-* are not stripped at the edge.
Programmatic Debug Logging
<?php use BitBabit\DeveloperTools\Helper\Debug; // Basic logging Debug::info('Processing order', ['order_id' => 123]); Debug::warning('Low stock detected', ['product_id' => 456]); Debug::error('Payment failed', ['error' => $exception->getMessage()]); // Variable dumping Debug::dump($complexArray, 'Order Data'); // Timer usage (legacy methods) Debug::startTimer('product-load'); // ... your code ... Debug::endTimer('product-load', 'Product loading completed');
API Integration
For AJAX requests, profiler data is automatically injected into JSON responses:
// AJAX response with profiler data { "data": { /* your response data */ }, "_profiler": { "database": { /* query information */ }, "performance": { /* timing data */ }, "memory": { /* memory usage */ } } }
Architecture
Core Components
Interfaces
ProfilerConfigInterface: Main configuration contract defining all settings and validation methods
Models
ProfilerConfig: Configuration implementation with scope integrationDebugInfo: Singleton for collecting debug messages
Services
ComprehensiveProfilerService: Main profiling engine collecting all dataApiKeyCookieManagerService: Secure API key management with cookie support
Console Commands
EnableCommand: Enable profiler via CLIDisableCommand: Disable profiler via CLIStatusCommand: Show current profiler statusGenerateApiKeyCommand: API key generation and management
Observers & Plugins
ResponseObserver: Injects profiler data into responsesHttpLaunchPlugin: Initializes profiling for each request
Frontend Components
profiler-widget.js: Interactive JavaScript toolbarprofiler-widget.css: Responsive styling
Data Flow
- Request Initialization:
HttpLaunchPluginchecks if profiling should be enabled - Data Collection:
ComprehensiveProfilerServicegathers metrics throughout request - Response Injection:
ResponseObserveradds profiler data to output - Frontend Display: JavaScript widget renders interactive toolbar
Security Features
- API Key Authentication: Secure access control
- Timing-Safe Comparison: Prevents timing attacks
- Developer Mode Restriction: Production safety
- Cookie Security:
Securewhen HTTPS;SameSite=Lax. The API key cookie is not HttpOnly (so browser extensions / JS can read it—treat XSS on the storefront as a higher risk while the cookie is set)
Data Structure
Profiler Data Schema
{
"overview": {
"status": "good|warning|error",
"total_queries": 25,
"total_time": "1.234s"
},
"database": {
"total_queries": 25,
"total_time_formatted": "145.67ms",
"slow_query_threshold": "100ms",
"queries": [
{
"query": "SELECT * FROM catalog_product_entity WHERE ...",
"time": 45.67,
"time_formatted": "45.67ms",
"type": "SELECT",
"is_slow": false,
"params": ["value1", "value2"]
}
],
"queries_by_type": {
"SELECT": 20,
"INSERT": 3,
"UPDATE": 2
}
},
"performance": {
"application_time": "1.234s",
"bootstrap_time": "0.123s",
"php_version": "8.3.0",
"magento_mode": "developer",
"server_load": [0.5, 0.7, 0.9],
"opcache": {
"enabled": true,
"hit_rate": 95.5,
"memory_usage": {
"used_memory": 67108864,
"free_memory": 33554432,
"wasted_memory": 1048576
}
}
},
"memory": {
"current_usage": 16777216,
"current_usage_formatted": "16.0 MB",
"peak_usage": 20971520,
"peak_usage_formatted": "20.0 MB",
"real_usage_formatted": "18.5 MB",
"limit": "512M"
},
"request": {
"method": "GET",
"uri": "/catalog/product/view/id/123",
"url": "https://example.com/catalog/product/view/id/123",
"ip": "192.168.1.100",
"content_type": "text/html",
"user_agent": "Mozilla/5.0...",
"headers": {
"Host": "example.com",
"X-Debug-Mode": "1"
},
"parameters": {
"GET": {"id": "123"},
"POST": {},
"FILES": {}
},
"session": {
"session_id": "abc123",
"customer_id": null
}
},
"environment": {
"php_version": "8.3.0",
"server_software": "nginx/1.20.0",
"operating_system": "Linux",
"max_execution_time": 30,
"timezone": "UTC",
"locale": "en_US.UTF-8",
"extensions": ["json", "mysqli", "gd", "curl"]
},
"metadata": {
"generated_at": "2024-01-15 10:30:45",
"request_id": "req_123456789",
"profiler_version": "1.2.0",
"memory_limit_exceeded": false,
"timestamp": 1705315845
},
"debug_info": {
"messages": [
{
"message": "Order processing started",
"level": "info",
"context": {"order_id": 123},
"timestamp": 1705315845.123
}
]
},
"timers": {
"product-load": {
"duration": 45.67,
"duration_formatted": "45.67ms",
"started_at": "10:30:45.123",
"ended_at": "10:30:45.169"
}
}
}
Frontend Interface
Toolbar Panels
- Database Queries: SQL query analysis with parameters and timing
- Performance: Execution times, server load, OPcache status
- Memory: Current, peak, and real memory usage statistics
- Request: HTTP request details, headers, parameters, session
- Environment: PHP info, server details, extensions
- OPcache: Cache statistics and memory usage
- Debug: Custom debug messages with context data
Interactive Features
- Collapsible panels for organized data viewing
- Multi-request tracking for AJAX monitoring
- Real-time updates without page refresh
- JSON tree visualization for complex data
- Responsive design for mobile debugging
- Request selector to switch between tracked requests
Browser Extension Support
Chrome Extension Integration
// manifest.json permissions "permissions": [ "webRequest", "webRequestBlocking", "*://*/*" ] // Background script example chrome.webRequest.onBeforeSendHeaders.addListener( function(details) { details.requestHeaders.push({ name: 'X-Debug-Mode', value: '1' }); details.requestHeaders.push({ name: 'X-Debug-Api-Key', value: localStorage.getItem('debug_api_key') }); return {requestHeaders: details.requestHeaders}; }, {urls: ["*://*/*"]}, ["blocking", "requestHeaders"] );
Performance Considerations
Memory Management
- Automatic profiler disable when memory limit exceeded
- Configurable memory thresholds
- Efficient data structure usage
- Storage cleanup on page refresh
Storage Options
- IndexedDB: Primary storage (highest capacity)
- localStorage: Fallback option
- Cookies: Minimal fallback for basic functionality
Query Optimization
- Minimal performance overhead
- Optional profiling activation
- Selective data collection
- Efficient query parameter handling
Security Considerations
API Key Security
- Cryptographically secure key generation
- Timing-safe string comparison
- Secure cookie attributes when HTTPS is used
- Prefer the
X-Debug-Api-Keyheader overapi_keyquery parameters (query strings are often logged)
SSR log REST (/V1/devtools/ssr-logs/{ssrId})
- Web API routes use
anonymousso browser tools can call Magento without a customer session; authorization is enforced inSsrLogRepositoryviavalidateApiKey(). - If Enable API Key Validation is off, anyone who can reach the storefront and knows or guesses an
X-SSR-IDmay read or clear those cache entries—keep validation on outside trusted local dev.
Access Control
- Developer mode restrictions
- API key authentication
- Request header validation
Data Privacy
- Session details in profiler output are minimized (no full session dump)
- Request headers like
Authorization,Cookie, andX-Debug-Api-Keyare redacted in collected profiler data - GET/POST parameters whose names suggest secrets (e.g.
password,token) are redacted in profiler output - Avoid passing the API key in query strings when possible (URLs often appear in logs and referrers)
- Memory usage limits to prevent resource exhaustion
Troubleshooting
Common Issues
Toolbar Not Appearing
- Check if module is enabled:
bin/magento module:status BitBabit_DeveloperTools - Verify API key configuration
- Ensure correct headers are sent
- Check browser console for JavaScript errors
Performance Issues
- Increase memory limits
- Disable in production environments
- Reduce slow query threshold
- Monitor server resources
API Key Problems
- Regenerate API key:
bin/magento bitbabit:devtools:generate-api-key --regenerate - Clear browser storage
- Verify header transmission
- Check admin configuration
Debug Mode
Enable debug logging in the JavaScript widget:
// In browser console DevProfiler.isDebugEnabled = true;
Log Files
Check Magento logs for profiler-related issues:
var/log/developer_tools.logvar/log/system.logvar/log/exception.log
Development
Extending the Module
Adding Custom Collectors
<?php // Custom data collector class CustomDataCollector { public function collect(): array { return [ 'custom_metric' => $this->calculateMetric(), 'additional_data' => $this->gatherData() ]; } }
Frontend Customization
// Extend the profiler widget class ExtendedProfilerWidget extends ProfilerWidget { getCustomPanel(data) { return `<div class="custom-panel">${data}</div>`; } }
Testing
Run the included PHPUnit tests:
cd DeveloperTools
../../../vendor/bin/phpunit
Test coverage includes:
- Configuration management
- Console commands
- API key generation
- Debug info collection
License
This project is licensed under the MIT License - see the LICENSE file for details.
Contributing
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Commit your changes:
git commit -m 'Add amazing feature' - Push to the branch:
git push origin feature/amazing-feature - Open a Pull Request
Support
- Documentation: This README and inline code comments
- Issues: GitHub Issues tracker
- Email: babitkumar6@gmail.com
Changelog
v1.2.0
- Initial public release
- Complete profiling suite
- API key authentication
- Interactive web interface
- Console command integration
- Comprehensive test coverage
⚠️ Important: This module is designed for development environments. While it includes security features, it should be thoroughly tested before any production use.