Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Mousetracker Laravel Package

benmacha/mousetracker

Self-hosted mouse/click/scroll tracker for Symfony 5.4–7.x. Records mouse moves, clicks, scroll, keyboard, form-blur values, and DOM snapshots, storing sessions in your own DB for Mouseflow-style heatmaps and replay. No jQuery.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:

    composer require benmacha/mousetracker:^2.0
    

    For Symfony Flex, no additional bundle registration is needed. Otherwise, add to config/bundles.php:

    benmacha\mousetracker\TrackerBundle::class => ['all' => true],
    
  2. Configure routes (config/routes/mouse_tracker.yaml):

    mouse_tracker:
        resource: '@TrackerBundle/Resources/config/routes.yaml'
        prefix: /tracker
    
  3. Set up the database:

    php bin/console doctrine:schema:update --force
    

    (Or use migrations if preferred.)

  4. Publish assets:

    php bin/console assets:install --symlink public/
    
  5. Inject the tracker snippet in your base template (e.g., templates/base.html.twig):

    {{ mouse_tracker_service.build()|raw }}
    
  6. Expose the service as a Twig global (config/packages/twig.yaml):

    twig:
        globals:
            mouse_tracker_service: '@mouse_tracker'
    
  7. Secure the backend (config/packages/security.yaml):

    security:
        access_control:
            - { path: ^/tracker/back, roles: ROLE_ADMIN }
            - { path: ^/tracker, roles: PUBLIC_ACCESS }
    

First Use Case: Track User Interactions

Add the tracker snippet to any page where you want to record interactions. The tracker will automatically:

  • Capture mouse movements, clicks, and scrolls.
  • Record form field values (excluding passwords) on blur.
  • Batch and send data to /tracker/createClient and /tracker/addData.

Access the backend at /tracker/back to view session replays and heatmaps.


Implementation Patterns

Workflow: Integrating MouseTracker into a Laravel Project

Since mousetracker is a Symfony bundle, you’ll need to adapt it for Laravel. Here’s how:

1. Install and Configure

  • Install the package via Composer (as above).
  • Manually register the bundle in Laravel by creating a service provider (e.g., MouseTrackerServiceProvider):
    namespace App\Providers;
    
    use Illuminate\Support\ServiceProvider;
    use benmacha\mousetracker\TrackerBundle;
    
    class MouseTrackerServiceProvider extends ServiceProvider
    {
        public function register()
        {
            $this->app->register(TrackerBundle::class);
        }
    }
    
    Register the provider in config/app.php:
    'providers' => [
        // ...
        App\Providers\MouseTrackerServiceProvider::class,
    ],
    

2. Route Configuration

  • Publish the routes manually in Laravel’s routes/web.php:
    Route::prefix('tracker')->group(function () {
        require __DIR__.'/../vendor/benmacha/mousetracker/Resources/config/routes.yaml';
    });
    

3. Database Setup

  • Use Laravel’s migrations to create the required tables. Publish the bundle’s migrations:
    php artisan vendor:publish --provider="benmacha\mousetracker\TrackerBundle" --tag="migrations"
    
  • Run the migrations:
    php artisan migrate
    

4. Asset Handling

  • Publish the tracker JS file:
    php artisan vendor:publish --provider="benmacha\mousetracker\TrackerBundle" --tag="assets"
    
  • Include the JS file in your layout (e.g., resources/views/layouts/app.blade.php):
    <script src="{{ asset('vendor/mousetracker/js/tracker.js') }}"></script>
    

5. Twig Integration (if using Blade)

  • If your project uses Twig (e.g., via Laravel Pint or a custom setup), expose the mouse_tracker_service as a global:
    // In your service provider's boot method
    $this->app['twig']->addGlobal('mouse_tracker_service', $this->app->make('mouse_tracker'));
    
  • In your Blade templates, use @inject or manually render the tracker snippet:
    {!! $mouse_tracker_service->build() !!}
    

6. Configuration

  • Override the default config in config/mouse_tracker.php:
    return [
        'record_click' => true,
        'record_move' => true,
        'record_keyboard' => true,
        'percentage_recorded' => 100,
        'disable_mobile' => false,
        'ignore_ips' => [],
    ];
    

7. Security

  • Secure the /tracker/back routes using Laravel middleware (e.g., auth):
    Route::prefix('tracker/back')->middleware(['auth'])->group(function () {
        // Backend routes
    });
    

Common Patterns

Sampling Visitors

Use the percentage_recorded config to sample a subset of visitors (e.g., 10 for 10%):

mouse_tracker:
    percentage_recorded: 10

Ignoring Specific IPs

Exclude internal IPs or test environments:

mouse_tracker:
    ignore_ips: ['192.168.1.0/24', '127.0.0.1']

Dynamic Configuration

Override settings client-side via JavaScript:

<script>
    window.UST && (UST.settings.delay = 200); // Adjust batch delay
</script>

Extending the Backend

Customize the replay UI by overriding the Twig templates in resources/views/vendor/mousetracker/.


Gotchas and Tips

Pitfalls

  1. GDPR Compliance:

    • The /tracker/createClient and /tracker/addData endpoints are public by default. Ensure you:
      • Get explicit user consent before loading tracker.js.
      • Secure the backend routes (/tracker/back) with authentication.
      • Provide a way for users to opt out (e.g., via cookie consent).
  2. Mobile Tracking:

    • Mobile tracking is disabled by default (disable_mobile: false). Enable it only if needed, as mobile interactions may not translate well to heatmaps.
  3. Database Schema:

    • The bundle creates three tables: tracker__client, tracker__page, and tracker__data. Ensure your Laravel migrations handle these correctly, especially if you’re using a custom database connection.
  4. Asset Paths:

    • The tracker JS file is published to public/bundles/tracker/js/tracker.js. If you’re using Laravel Mix or Vite, ensure the path is correctly aliased in your build config.
  5. Symfony-Specific Features:

    • The bundle relies on Symfony’s AbstractController, #[Route] attributes, and ServiceEntityRepository. In Laravel, you’ll need to manually handle:
      • Route registration (as shown above).
      • Dependency injection (e.g., for repositories).
      • Configuration loading (e.g., Configuration class).
  6. Performance:

    • Tracking adds overhead. Test performance impact, especially on high-traffic pages. Consider:
      • Disabling tracking for logged-in users or specific routes.
      • Adjusting percentage_recorded to reduce load.
  7. Debugging:

    • Check the browser’s Network tab for requests to /tracker/createClient and /tracker/addData. Look for:
      • 404 errors (misconfigured routes).
      • CORS issues (if testing locally).
      • Payload validation errors (e.g., malformed JSON).

Tips

  1. Laravel-Specific Adjustments:

    • Replace Symfony’s asset() function with Laravel’s asset() helper in Twig templates:
      {{ asset('bundles/tracker/js/tracker.js') }}
      
    • If using Blade, manually render the JS file:
      <script src="{{ asset('vendor/mousetracker/js/tracker.js') }}"></script>
      
  2. Customizing the Tracker:

    • Override the tracker.js file by publishing it and modifying it:
      php artisan vendor:publish --provider="benmacha\mousetracker\TrackerBundle" --tag="assets"
      
    • Extend the UST object in your global JS to add custom events or filters.
  3. Data Retention:

    • Implement a cleanup job to purge old tracking data (e.g., older than 6 months). Example Laravel command:
      use App\Models\TrackerClient; // Replace with your entity model
      
      public function handle()
      {
          TrackerClient::where('created_at', '<=', now()->subMonths(6))->delete();
      }
      
  4. Testing:

    • Mock the tracker in PHPUnit by
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity