Mega_Aleksandar's avatar

Laravel/Inertia/Vue SPA - is it possible to track users mouse/keyboard?

Hello everyone,

The goal in this question is - is it possible to track users mouse/keyboard in your app? The reason for this is to see if the UI is good and simple, if the UX is convenient for most of the daily tasks the users will perform.

I know I can log the events, database changes etc. through Controllers and spatie logger, but I am thinking on logging the users usage of the app itself of the frontend.

Found couple of similar questions, but they are referencing videos that are no longer available.

Thanks in advance,

Mega_Aleksandar

0 likes
2 replies
LaryAI's avatar
Level 58

To track user interactions such as mouse movements and keyboard events in a Laravel/Inertia/Vue SPA, you can use Vue.js to capture these events and then send the data to your Laravel backend for logging and analysis. Here’s a step-by-step guide to achieve this:

  1. Set up event listeners in your Vue components:

    You can add event listeners for mouse and keyboard events in your Vue components. For example, you can listen for mousemove, click, and keydown events.

  2. Send the captured data to your Laravel backend:

    Use Axios or the Fetch API to send the captured data to your Laravel backend for logging.

  3. Log the data in your Laravel application:

    Create a controller and route in Laravel to handle the incoming data and log it to the database or a file.

Here’s a basic implementation:

Step 1: Set up event listeners in Vue

Create a Vue component (e.g., App.vue) and add event listeners for mouse and keyboard events.

<template>
  <div @mousemove="logMouseMove" @click="logClick" @keydown="logKeyDown">
    <!-- Your app content -->
  </div>
</template>

<script>
import axios from 'axios';

export default {
  methods: {
    logMouseMove(event) {
      const data = {
        type: 'mousemove',
        x: event.clientX,
        y: event.clientY,
        timestamp: new Date().toISOString(),
      };
      this.sendLog(data);
    },
    logClick(event) {
      const data = {
        type: 'click',
        x: event.clientX,
        y: event.clientY,
        timestamp: new Date().toISOString(),
      };
      this.sendLog(data);
    },
    logKeyDown(event) {
      const data = {
        type: 'keydown',
        key: event.key,
        timestamp: new Date().toISOString(),
      };
      this.sendLog(data);
    },
    sendLog(data) {
      axios.post('/api/log-interaction', data)
        .then(response => {
          console.log('Log sent successfully:', response.data);
        })
        .catch(error => {
          console.error('Error sending log:', error);
        });
    },
  },
};
</script>

Step 2: Create a route and controller in Laravel

Create a route in routes/api.php to handle the incoming log data.

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\InteractionLogController;

Route::post('/log-interaction', [InteractionLogController::class, 'store']);

Create a controller to handle the log data. You can use the php artisan make:controller InteractionLogController command to generate the controller.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class InteractionLogController extends Controller
{
    public function store(Request $request)
    {
        // Validate the incoming request data
        $data = $request->validate([
            'type' => 'required|string',
            'x' => 'nullable|integer',
            'y' => 'nullable|integer',
            'key' => 'nullable|string',
            'timestamp' => 'required|date',
        ]);

        // Log the data (you can also save it to the database if needed)
        Log::info('User interaction logged:', $data);

        return response()->json(['message' => 'Log stored successfully']);
    }
}

Step 3: Configure logging (optional)

If you want to log the data to a file, make sure your config/logging.php is set up correctly. For example, you can use the daily log channel to create a new log file each day.

'channels' => [
    'stack' => [
        'driver' => 'stack',
        'channels' => ['daily'],
    ],

    'daily' => [
        'driver' => 'daily',
        'path' => storage_path('logs/laravel.log'),
        'level' => 'debug',
        'days' => 14,
    ],
],

With this setup, you will be able to track user interactions such as mouse movements, clicks, and key presses in your Laravel/Inertia/Vue SPA and log them for analysis.

Mega_Aleksandar's avatar

@LaryAI Thanks Lary, I had some similar idea in mind, although, I would like to hear some real-life experiences from developers. Thank you.

Please or to participate in this conversation.