Weave 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

Mongodb Session Laravel Package

jenssegers/mongodb-session

MongoDB session driver for Laravel. Store user sessions in MongoDB instead of files or databases, using Laravel’s session API. Ideal for distributed apps that need scalable, persistent session storage alongside jenssegers/laravel-mongodb.

View on GitHub
Deep Wiki
Context7

Getting Started

  1. Confirm the target is Laravel ≤ 8. The package declares support for Laravel 4–8 only. If you're on 9+, stop — check whether mongodb/laravel-mongodb v4+ already ships a session handler and use that instead.
  2. Install the prerequisites first, not last. You need ext-mongodb, mongodb/mongodb, and jenssegers/laravel-mongodb wired up with a working mongodb connection in config/database.php. Prove that connection with a quick DB::connection('mongodb')->getMongoDB()->listCollections() before touching sessions.
  3. Install the driver:
    composer require jenssegers/mongodb-session
    
    On Laravel 5.5+ the service provider is auto-discovered; below that, register it manually in config/app.php.
  4. Flip the driver in config/session.php:
    'driver'     => env('SESSION_DRIVER', 'mongo'),
    'connection' => env('SESSION_CONNECTION', 'mongodb'),
    'collection' => env('SESSION_COLLECTION', 'sessions'),
    
    The package uses these keys to bind its handler via Session::extend().
  5. First use case — verify, don't assume. Log in, then in mongosh:
    db.sessions.find().limit(1).pretty()
    
    You should see _id equal to the Laravel session ID, a payload blob, and a last_activity timestamp. Then confirm flash data survives a redirect — that's the real smoke test, because flash writes are the first thing lost when the handler is subtly broken.

Where to look first: the handler class in vendor/jenssegers/mongodb-session/src (it's ~100–200 lines). Read it end to end before relying on it — it tells you exactly how read/write/gc/destroy map to Mongo operations, which read preference you inherit, and whether SessionUpdateTimestampHandlerInterface is implemented.

Implementation Patterns

Env-driven driver switching for cutover. Never hardcode 'driver' => 'mongo'. Use SESSION_DRIVER so the switch is a config/env change plus php artisan config:cache — deploy-free, and rollback is reverting one variable. Session data is ephemeral, so flipping the driver invalidates live sessions and forces a global re-login; schedule that deliberately.

Isolate sessions on their own connection/collection. Point SESSION_CONNECTION at a dedicated database or cluster rather than sharing the app's hot collection. Session traffic is small, uniform, and write-heavy — you don't want it competing with domain query latency, and a separate DB makes backup/restore scope obvious.

Create the TTL index explicitly. Don't rely on Laravel's lottery GC alone in a multi-node deployment:

db.sessions.createIndex({ last_activity: 1 }, { expireAfterSeconds: 7200 })

Match expireAfterSeconds to config('session.lifetime') * 60. Ship this as a one-off Artisan command or migration so it's reproducible per environment, not a manual step someone remembers.

Test on the array driver, not Mongo. Unit and feature tests should stay on SESSION_DRIVER=array. Reserve Mongo-backed sessions for an integration test that exercises the actual write path — one test that logs in, flashes, and reads back is enough.

Debugging pattern for "user randomly got logged out." Query the session doc by ID from the cookie and inspect last_activity and payload. If the doc is missing, it's TTL/GC or a failed write. If it exists but the user is logged out, it's usually a read that hit a secondary (stale) — check the connection's readPreference.

Vendor/fork as a first-class pattern. At ~100–200 lines, vendoring this handler in-house is a legitimate de-risk. That gives you control over locking, TTL, and the validateId/updateTimestamp behavior — and removes the single-maintainer dependency from your critical path.

Rollback plan as a pattern. Keep the old session store mounted and untouched for the rollback window. Returning to file or redis is a config revert; don't delete anything for at least 24 hours.

Gotchas and Tips

  • Laravel 9+ is not supported. Period. The declared ceiling is Laravel 8 (PHP 7.x era). On anything newer, plan for a fork or a different package — and before that, check if the handler already ships inside mongodb/laravel-mongodb, which would make this package redundant.
  • Deprecated dependency chain. This ties you to jenssegers/laravel-mongodb, the ancestor of the MongoDB-maintained mongodb/laravel-mongodb v4+. Adopting this pins you to an abandoned lineage.
  • No session locking. Like Laravel's file and database drivers, it's last-write-wins. Concurrent requests from one browser (parallel XHR, multiple tabs) race on the session document. The symptom is not an error — it's intermittent lost flash data, dropped cart mutations, or surprise logouts. The hardest class of bug to diagnose in production.
  • Read preference and write concern are yours to set, not the package's. Use readPreference: primary and w: majority (journaled) for the session connection. Get it wrong and you ship random logouts on primary election.
  • Check SessionUpdateTimestampHandlerInterface. If the handler doesn't implement validateId and updateTimestamp, Auth::logoutOtherDevices and Laravel's session-blocking behave incorrectly. Read the class; don't infer from docs.
  • Pick one GC strategy. Either the lottery (session.lottery) or a TTL index — running both means duplicated work and confusing metrics. TTL is the more predictable option.
  • PHP 8.1 deprecation noise. If you're pinned to 8.1 on an old Laravel, expect deprecation notices from the ODM lineage to pollute logs. Silence narrowly, don't suppress globally.
  • Connection pool sizing. Every PHP-FPM worker holds a Mongo connection. Check maxPoolSize on the cluster against worker_count × pool_size before you canary — sessions amplify connection count because the driver opens one on the first request of each worker.
  • Don't confuse session encryption with session security. session.encrypt works, but it's payload-level only; it doesn't change your Mongo access controls. Treat the session collection as sensitive data (auth IDs, CSRF tokens) for backup and access policy.
  • _id is the session ID. Useful for ops debugging — grep a cookie value against db.sessions.findOne({_id: "<id>"}).
  • Extension point if you need customization: the handler is bound via Session::extend() in the package's provider. Subclass or re-bind your own handler rather than patching vendor files — that's the clean seam.
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.
mrnewport/laravel-plaid
mrnewport/laravel-repo
mrnewport/laravel-docsign
mrnewport/laravel-stow
mrnewport/laravel-flow
mrnewport/laravel-priceable
mrnewport/laravel-nestedterms
fredmeng/laravel-apidoc-generator
itstructure/laravel-multilingual-tools
pdustdar/elasticsearch
markupai/php-sdk
rlacerda83/lumem-microservice-shipment
uni-method/symfony-lib
tacticmedia/scim-server-bundle
neika-ai/symfony-bundle
mattleads/agent-publishing-bundle
glavweb/framework-bundle
glavweb/extra-bundle
glavweb/api-bundle
glavweb/admin-bundle