PHPackages                             stanleykinkelaar/laravel-browser-sessions-lite - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. stanleykinkelaar/laravel-browser-sessions-lite

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

stanleykinkelaar/laravel-browser-sessions-lite
==============================================

A lightweight Laravel package for managing browser sessions with device detection and secure logout

0.0.2(5mo ago)00[2 PRs](https://github.com/stanleykinkelaar/laravel-browser-sessions-lite/pulls)MITPHPPHP ^8.2|^8.3|^8.4CI passing

Since Dec 5Pushed 3mo agoCompare

[ Source](https://github.com/stanleykinkelaar/laravel-browser-sessions-lite)[ Packagist](https://packagist.org/packages/stanleykinkelaar/laravel-browser-sessions-lite)[ Docs](https://github.com/stanleykinkelaar/laravel-browser-sessions-lite)[ GitHub Sponsors]()[ RSS](/packages/stanleykinkelaar-laravel-browser-sessions-lite/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (12)Versions (5)Used By (0)

🚀 Laravel Browser Sessions Lite
===============================

[](#-laravel-browser-sessions-lite)

[![Latest Version on Packagist](https://camo.githubusercontent.com/e265e32e5766a55607c3b6735ecc301b06f9ed8326ef2ac355a05d1bc2319856/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7374616e6c65796b696e6b656c6161722f6c61726176656c2d62726f777365722d73657373696f6e732d6c6974652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/stanleykinkelaar/laravel-browser-sessions-lite)[![GitHub Tests Action Status](https://camo.githubusercontent.com/8681b331ba9f4cd49b1f4b56a103b11df9cb22d0f314474bde226505cbb942e2/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7374616e6c65796b696e6b656c6161722f6c61726176656c2d62726f777365722d73657373696f6e732d6c6974652f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/stanleykinkelaar/laravel-browser-sessions-lite/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/32d975f61875e96a77d18ae8d92ce8e38935ca48a117954fd08ca2690f83a3fc/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7374616e6c65796b696e6b656c6161722f6c61726176656c2d62726f777365722d73657373696f6e732d6c6974652f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/stanleykinkelaar/laravel-browser-sessions-lite/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/66b6e2e0719c7598b6cebcf7061ceccd64ec567874f443763dfe2d983fa79df0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7374616e6c65796b696e6b656c6161722f6c61726176656c2d62726f777365722d73657373696f6e732d6c6974652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/stanleykinkelaar/laravel-browser-sessions-lite)

> **Ever wondered who's logged into your app right now?** 🤔 This lightweight Laravel package lets users see all their active browser sessions and securely log out suspicious ones—all without the bloat of heavy device detection libraries.

Perfect for apps that need Jetstream-style session management but want to keep it simple and fast.

---

✨ Features
----------

[](#-features)

- 📱 **No Device Detection Libraries** - Lightweight regex-based detection without heavy dependencies
- 🔒 **Secure by Default** - Password-verified logout prevents accidental lockouts
- 🎨 **Beautiful UI** - Jetstream-inspired Blade view with Tailwind CSS
- 🌐 **JSON API Ready** - Full REST API support for SPAs and mobile apps
- 🔍 **Smart Device Hints** - Lightweight regex-based detection (iOS, Android, browsers, OS)
- ⚡ **Modern Laravel** - Works seamlessly with Laravel 10, 11 &amp; 12
- 🧪 **Battle-Tested** - Comprehensive Pest test suite with 100% coverage
- 🎯 **Spatie Standards** - Built on `spatie/laravel-package-tools`

---

🎯 Use Cases
-----------

[](#-use-cases)

- **Security-conscious apps** - Let users monitor and manage their active sessions
- **Multi-device workflows** - Show users where they're logged in (phone, tablet, laptop)
- **Account hijacking prevention** - Users can quickly log out suspicious sessions
- **Jetstream alternative** - Get session management without Jetstream's full stack

---

📦 Requirements
--------------

[](#-requirements)

RequirementVersionPHP8.2+Laravel10.x, 11.x, 12.xSession Driver`database`---

🚀 Installation
--------------

[](#-installation)

### Step 1: Install via Composer

[](#step-1-install-via-composer)

```
composer require stanleykinkelaar/laravel-browser-sessions-lite
```

### Step 2: Configure Database Sessions

[](#step-2-configure-database-sessions)

This package requires Laravel's database session driver. Update your `.env`:

```
SESSION_DRIVER=database
```

Create the sessions table (if you haven't already):

```
php artisan session:table
php artisan migrate
```

### Step 3: Publish Assets (Optional)

[](#step-3-publish-assets-optional)

**Publish config file** to customize routes and middleware:

```
php artisan vendor:publish --tag="browser-sessions-lite-config"
```

**Publish views** to customize the UI:

```
php artisan vendor:publish --tag="browser-sessions-lite-views"
```

---

⚙️ Configuration
----------------

[](#️-configuration)

The config file (`config/browser-sessions-lite.php`) allows you to customize behavior:

```
return [
    /*
     * Middleware applied to browser sessions routes.
     * Default: ['web', 'auth']
     */
    'middleware' => ['web', 'auth'],

    /*
     * URI prefix for all routes.
     * Default: 'user' (results in /user/browser-sessions)
     */
    'prefix' => 'user',
];
```

**Pro tip:** Need admin-only access? Change middleware to `['web', 'auth', 'admin']`

---

🎨 Usage
-------

[](#-usage)

### Web UI (Blade)

[](#web-ui-blade)

The package automatically registers these routes:

MethodURIDescription`GET``/user/browser-sessions`View all sessions (Blade UI)`DELETE``/user/browser-sessions/others`Logout other sessionsSimply visit **`/user/browser-sessions`** in your browser to see the beautiful UI!

🎉 **That's it!** The view looks like this:

- ✅ List of all active sessions with device hints
- ✅ Current device highlighted with a badge
- ✅ IP addresses and "last active" timestamps
- ✅ Password-protected "Log Out Other Sessions" button
- ✅ Success/error flash messages
- ✅ Fully responsive (mobile-friendly)

---

### Programmatic Usage (PHP)

[](#programmatic-usage-php)

#### List Sessions for Current User

[](#list-sessions-for-current-user)

```
use StanleyKinkelaar\LaravelBrowserSessionsLite\Facades\LaravelBrowserSessionsLite;

$sessions = LaravelBrowserSessionsLite::listForCurrentUser();

foreach ($sessions as $session) {
    echo $session['device_hint'];     // "iOS Device", "Chrome Browser", etc.
    echo $session['ip_address'];       // "192.168.1.1"
    echo $session['is_current'];       // true/false
    echo $session['last_active_at'];   // Carbon instance
}
```

#### Logout Other Sessions (with password verification)

[](#logout-other-sessions-with-password-verification)

```
try {
    $deletedCount = LaravelBrowserSessionsLite::logoutOtherSessionsWithPassword('user-password');

    echo "✅ Logged out {$deletedCount} other sessions";
} catch (\Illuminate\Validation\ValidationException $e) {
    echo "❌ Invalid password";
}
```

#### Force Logout (admin use - skips password check)

[](#force-logout-admin-use---skips-password-check)

```
// Useful for admin panels or security automation
$deletedCount = LaravelBrowserSessionsLite::forceLogoutOthersForUser($userId, 'password');
```

#### Check for Multiple Sessions

[](#check-for-multiple-sessions)

```
if (LaravelBrowserSessionsLite::hasMultipleSessions()) {
    echo "⚠️ You have active sessions on other devices";
}

$count = LaravelBrowserSessionsLite::getActiveSessionCount();
echo "You have {$count} active sessions";
```

---

### JSON API Usage (for SPAs &amp; Mobile Apps)

[](#json-api-usage-for-spas--mobile-apps)

All routes support JSON responses when using `Accept: application/json` header.

#### List Sessions (JSON)

[](#list-sessions-json)

```
curl -X GET https://your-app.com/user/browser-sessions \
  -H "Accept: application/json" \
  -H "Authorization: Bearer {token}"
```

**Response:**

```
{
  "sessions": [
    {
      "id": "abc123xyz",
      "ip_address": "192.168.1.1",
      "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)...",
      "last_active_at": "2024-01-15 10:30:00",
      "is_current": true,
      "device_hint": "Chrome Browser"
    },
    {
      "id": "def456uvw",
      "ip_address": "192.168.1.50",
      "user_agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X)...",
      "last_active_at": "2024-01-14 18:22:00",
      "is_current": false,
      "device_hint": "iOS Device"
    }
  ],
  "count": 2
}
```

#### Logout Other Sessions (JSON)

[](#logout-other-sessions-json)

```
curl -X DELETE https://your-app.com/user/browser-sessions/others \
  -H "Accept: application/json" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer {token}" \
  -d '{"password": "user-password"}'
```

**Success Response:**

```
{
  "message": "Successfully logged out other browser sessions.",
  "deleted_count": 2
}
```

**Error Response (422):**

```
{
  "message": "The provided password is incorrect.",
  "errors": {
    "password": ["The provided password is incorrect."]
  }
}
```

---

🔍 Device Detection
------------------

[](#-device-detection)

The package uses **simple regex patterns** for device hints (no external libraries, zero bloat):

User Agent ContainsDevice Hint Shown`iPhone`, `iPad`, `iPod`**iOS Device** 📱`Android`**Android Device** 🤖`Edg`**Edge Browser** 🌐`Chrome`**Chrome Browser** 🌐`Firefox`**Firefox Browser** 🦊`Safari`**Safari Browser** 🧭`Windows`**Windows PC** 💻`Macintosh`, `Mac OS`**Mac Computer** 🍎`Linux`**Linux PC** 🐧**Note:** Detection order matters! Edge and Chrome are checked before Safari (since their UAs contain "Safari").

---

🎬 Example Integrations
----------------------

[](#-example-integrations)

### Integration 1: Laravel Blade Layout

[](#integration-1-laravel-blade-layout)

```

        Browser Sessions

            @include('browser-sessions-lite::browser-sessions')

```

### Integration 2: Vue/React SPA

[](#integration-2-vuereact-spa)

```
// composables/useBrowserSessions.js
import { ref } from 'vue';

export function useBrowserSessions() {
    const sessions = ref([]);
    const loading = ref(false);

    const fetchSessions = async () => {
        loading.value = true;
        const response = await fetch('/user/browser-sessions', {
            headers: {
                'Accept': 'application/json',
                'Authorization': `Bearer ${token}`
            }
        });
        const data = await response.json();
        sessions.value = data.sessions;
        loading.value = false;
    };

    const logoutOtherSessions = async (password) => {
        const response = await fetch('/user/browser-sessions/others', {
            method: 'DELETE',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify({ password })
        });

        if (response.ok) {
            await fetchSessions(); // Refresh list
            return await response.json();
        }

        throw new Error('Invalid password');
    };

    return { sessions, loading, fetchSessions, logoutOtherSessions };
}
```

### Integration 3: Livewire Component

[](#integration-3-livewire-component)

```
namespace App\Livewire;

use Livewire\Component;
use StanleyKinkelaar\LaravelBrowserSessionsLite\Facades\LaravelBrowserSessionsLite;

class BrowserSessions extends Component
{
    public $password = '';

    public function logoutOtherSessions()
    {
        $this->validate([
            'password' => 'required|current_password',
        ]);

        try {
            $count = LaravelBrowserSessionsLite::logoutOtherSessionsWithPassword($this->password);
            session()->flash('success', "Logged out {$count} sessions!");
            $this->password = '';
        } catch (\Exception $e) {
            $this->addError('password', 'Invalid password.');
        }
    }

    public function render()
    {
        return view('livewire.browser-sessions', [
            'sessions' => LaravelBrowserSessionsLite::listForCurrentUser(),
        ]);
    }
}
```

---

🤔 Why No Device Detection Libraries?
------------------------------------

[](#-why-no-device-detection-libraries)

This package **intentionally avoids** external device detection libraries like `jenssegers/agent` or `mobiledetect/mobiledetectlib` because:

✅ **Faster installation** - No heavy dependencies to download ✅ **Fewer conflicts** - Less chance of version mismatch issues ✅ **Smaller footprint** - Keeps your `vendor/` folder lean ✅ **Easier maintenance** - Simple regex patterns anyone can understand ✅ **Focused purpose** - Does one thing (session management) really well

**Need advanced device detection?** (browser versions, OS versions, device models, etc.) Consider using a dedicated package alongside this one. This package focuses on giving users *just enough* info to identify their devices—without the bloat.

---

🧪 Testing
---------

[](#-testing)

This package includes a **comprehensive Pest test suite** covering:

- ✅ Repository layer (session queries, device detection)
- ✅ Service layer (password verification, logout logic)
- ✅ Controller layer (HTTP requests, JSON responses)
- ✅ Integration tests (full flow from request to database)

### Run Tests

[](#run-tests)

```
# Run all tests
composer test

# Run with coverage report
composer test-coverage

# Run static analysis (PHPStan)
composer analyse

# Fix code style (Laravel Pint)
composer format
```

### Example Test Output

[](#example-test-output)

```
 PASS  Tests\Unit\SessionRepositoryTest
  ✓ can get sessions for a user
  ✓ can get the current session id
  ✓ can delete other sessions for a user
  ✓ correctly detects iOS devices
  ✓ correctly detects Android devices
  ✓ correctly detects Chrome browser

 PASS  Tests\Feature\BrowserSessionsControllerTest
  ✓ can view browser sessions page
  ✓ can logout other sessions with valid password
  ✓ cannot logout with invalid password
  ✓ returns json response when requested

Tests:  10 passed
Time:   0.42s
```

---

🛠️ How to Test in Your Package
------------------------------

[](#️-how-to-test-in-your-package)

Since this is a **Spatie-style Laravel package**, testing is set up using:

1. **Orchestra Testbench** - Simulates a Laravel app environment
2. **Pest PHP** - Modern testing framework
3. **In-memory SQLite** - Fast test database

### Running Tests During Development

[](#running-tests-during-development)

```
# From the package root directory:
cd /path/to/laravel-browser-sessions-lite

# Install dependencies
composer install

# Run tests
composer test

# Watch tests (with Pest --watch, if installed globally)
pest --watch
```

### Testing in a Real Laravel App

[](#testing-in-a-real-laravel-app)

Want to test this package in your actual Laravel app before release?

#### Option 1: Composer Local Path

[](#option-1-composer-local-path)

Add to your Laravel app's `composer.json`:

```
{
    "repositories": [
        {
            "type": "path",
            "url": "../laravel-browser-sessions-lite"
        }
    ],
    "require": {
        "stanleykinkelaar/laravel-browser-sessions-lite": "@dev"
    }
}
```

Then run:

```
composer update stanleykinkelaar/laravel-browser-sessions-lite
```

#### Option 2: Testbench Workbench (Spatie Style)

[](#option-2-testbench-workbench-spatie-style)

Use Orchestra Testbench's workbench feature:

```
cd laravel-browser-sessions-lite
composer run prepare
php vendor/bin/testbench serve
```

Visit `http://localhost:8000/user/browser-sessions` to test the UI!

---

📋 Architecture Overview
-----------------------

[](#-architecture-overview)

This package follows **Spatie conventions** and clean architecture:

```
src/
├── LaravelBrowserSessionsLiteServiceProvider.php  # Package registration
├── Http/
│   └── Controllers/
│       └── BrowserSessionsController.php          # Handles web + JSON requests
├── Services/
│   └── BrowserSessions.php                        # Business logic (logout, verification)
├── Repositories/
│   └── SessionRepository.php                      # Database queries + device hints
└── Facades/
    └── LaravelBrowserSessionsLite.php             # Facade for easy access

```

**Design principles:**

- ✅ **Repository pattern** - Separates database logic from business logic
- ✅ **Service layer** - Handles password verification and authentication
- ✅ **Single responsibility** - Each class does one thing well
- ✅ **Dependency injection** - Fully testable and mockable
- ✅ **Laravel conventions** - Feels native to Laravel

---

🔐 Security Best Practices
-------------------------

[](#-security-best-practices)

This package is designed with security in mind:

✅ **Password verification required** - Users must enter their password to log out other sessions ✅ **Laravel's `current_password` rule** - Uses built-in validation ✅ **Auth middleware by default** - Routes protected out of the box ✅ **CSRF protection** - Form submissions are CSRF-protected ✅ **Session rehashing** - Uses Laravel's `Auth::logoutOtherDevices()`

### Reporting Security Vulnerabilities

[](#reporting-security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

---

🤝 Contributing
--------------

[](#-contributing)

Contributions are welcome! Here's how you can help:

1. **Fork the repository**
2. **Create a feature branch** (`git checkout -b feature/amazing-feature`)
3. **Write tests** for your changes
4. **Run the test suite** (`composer test`)
5. **Fix code style** (`composer format`)
6. **Commit your changes** (`git commit -m 'Add amazing feature'`)
7. **Push to your branch** (`git push origin feature/amazing-feature`)
8. **Open a Pull Request**

Please see [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines.

---

📝 Changelog
-----------

[](#-changelog)

All notable changes are documented in [CHANGELOG.md](CHANGELOG.md).

---

📜 License
---------

[](#-license)

The MIT License (MIT). See [LICENSE.md](LICENSE.md) for details.

---

🙏 Credits
---------

[](#-credits)

- **[Stanley Kinkelaar](https://github.com/stanleykinkelaar)** - Creator &amp; Maintainer
- Inspired by Laravel Jetstream's session management
- Built on **[Spatie's Laravel Package Tools](https://github.com/spatie/laravel-package-tools)**
- All contributors listed in [contributors](../../contributors)

---

⭐ Show Your Support
-------------------

[](#-show-your-support)

If this package helped you, consider:

- ⭐ **Starring the repo** on GitHub
- 🐦 **Sharing it on Twitter**
- ☕ **Buying me a coffee** (coming soon!)

---

 **Made with ❤️ by [Stanley Kinkelaar](https://github.com/stanleykinkelaar)**
 Built for the Laravel community 🎉

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance76

Regular maintenance activity

Popularity0

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 85.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

159d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/f0ebfac8c01e0f2ad14ad848f8d1327ef74262a2f0a402c1b69b4e9040f8e531?d=identicon)[stanleykinkelaar](/maintainers/stanleykinkelaar)

---

Top Contributors

[![stanleykinkelaar](https://avatars.githubusercontent.com/u/14231377?v=4)](https://github.com/stanleykinkelaar "stanleykinkelaar (6 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")

---

Tags

laravelsecurityAuthenticationbrowser-sessionsDevice detectionsession-managementStanley Kinkelaar

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/stanleykinkelaar-laravel-browser-sessions-lite/health.svg)

```
[![Health](https://phpackages.com/badges/stanleykinkelaar-laravel-browser-sessions-lite/health.svg)](https://phpackages.com/packages/stanleykinkelaar-laravel-browser-sessions-lite)
```

###  Alternatives

[spatie/laravel-permission

Permission handling for Laravel 12 and up

12.9k89.8M1.0k](/packages/spatie-laravel-permission)[bezhansalleh/filament-shield

Filament support for `spatie/laravel-permission`.

2.8k2.9M88](/packages/bezhansalleh-filament-shield)[alajusticia/laravel-logins

Session management in Laravel apps, user notifications on new access, support for multiple separate remember tokens, IP geolocation, User-Agent parser

2011.0k](/packages/alajusticia-laravel-logins)[rinvex/laravel-authy

Rinvex Authy is a simple wrapper for Authy TOTP, the best rated Two-Factor Authentication service for consumers, simplest 2fa Rest API for developers and a strong authentication platform for the enterprise.

3376.7k1](/packages/rinvex-laravel-authy)[caresome/filament-auth-designer

Transform Filament's default auth pages into stunning, brand-ready experiences

3916.8k2](/packages/caresome-filament-auth-designer)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
