Transparency at Scale: Implementing Activity Logs and Audit Trails in Next.js
Karl Gusta
Instructor & Founder
As your SaaS moves into the B2B and Enterprise space, your customers will start asking a critical question: "Who changed this?" In a multi-tenant environment where dozens of users might have access to the same projects, transparency is not just a feature; it is a security requirement.
An Activity Log (or Audit Trail) provides a chronological record of all significant actions taken within an organization. It helps admins troubleshoot mistakes, monitor for suspicious behavior, and maintain accountability. In this lesson, we will implement a scalable logging system that tracks user actions without slowing down your application's primary performance.
The Problem: The "Black Box" Workspace
In a basic SaaS, actions happen silently. A project is deleted, a member is removed, or a billing plan is changed, and there is no record of who performed the action or why.
This lack of visibility leads to:
- Accountability Issues: Users blaming each other for deleted data or configuration errors.
- Security Blind Spots: Not knowing if a disgruntled employee or a compromised account is exporting sensitive data.
- Support Burden: Your team spending hours manually checking database logs to answer a customer's "what happened" question.
- Compliance Failures: Missing the "Audit Trail" requirement needed for SOC2, HIPAA, or GDPR compliance.
A SaaS without an activity log feels "amateur" to a corporate buyer. An audit trail turns your tool into a professional system of record.

The Shift: Asynchronous Event Logging
The secret to a high-performance audit trail in Next.js is ensuring that logging never blocks the user experience.
- Fire and Forget: When a user performs an action (like updating a project), we trigger the log creation in the background. We don't make the user wait for the log to be written before showing them a "Success" message.
- Standardized Event Schema: We use a consistent structure for every log entry: Actor (Who), Action (What), Entity (Where), and Timestamp (When).
- Retention Policies: We don't keep logs forever. We implement simple logic to archive or delete logs older than 30 or 90 days to keep the database lean.
By treating activity logs as a side-effect of your business logic, you gain total visibility with zero performance cost.
Deep Dive: Building the Audit Trail System
To build a professional logging system, we focus on the Activity Schema, the Logging Utility, and the Dashboard Feed.
1. The Activity Log Schema
Each log entry must be self-contained. Even if a user is deleted later, the log should still record their name at the time of the action.
typescript// models/ActivityLog.ts { _id: ObjectId("..."), orgId: ObjectId("org_abc"), // Scoped to the organization actor: { userId: ObjectId("user_123"), name: "John Doe", email: "john@example.com" }, action: "project.deleted", entity: { type: "project", id: ObjectId("proj_789"), name: "Marketing Campaign Q4" }, ipAddress: "192.168.1.1", createdAt: ISODate("2026-01-10T10:00:00Z") }
2. The Global Logging Utility
Instead of writing database code every time we want to log something, we create a centralized helper function. This keeps our Server Actions clean and readable.
typescript// lib/activity.ts export async function recordActivity({ orgId, actor, action, entity }) { const client = await clientPromise; const db = client.db(); // We don't 'await' this if we want it to be non-blocking db.collection('activity_logs').insertOne({ orgId, actor, action, entity, createdAt: new Date(), }); }
3. Rendering the Activity Feed
On the Organization Settings page, we provide a "Recent Activity" feed. We use MongoDB's sorting to show the most recent actions first and implement simple pagination.
Key Benefits and Learning Outcomes
- Enterprise Trust: You can confidently sell to larger companies that require audit logs for their internal compliance.
- Reduced Churn: Admins feel more in control of their workspace, leading to higher long-term satisfaction.
- Simplified Debugging: Your support team can check the activity log to see exactly what a user did before reporting a "bug."
- Enhanced Security: You can easily spot patterns of unusual activity, such as a user deleting 100 records in a single minute.
Common Mistakes
- Logging Too Much: Don't log every mouse click or page view. That is what PostHog is for. Only log significant state changes (Create, Update, Delete, Settings changes).
- Missing orgId: If you forget to include the
orgId, an admin might see activity from a completely different company—a catastrophic security breach. - Storing Sensitive Changes: If a user changes their password or an API key, log that the change happened, but never log the actual password or key itself.

Pro Tips and Best Practices
Use Human-Readable Descriptions: Instead of showing "action: user_invite_created", show "John Doe invited Sarah Smith to the team." This makes the log useful for non-technical managers.
Implement "Export to CSV": Enterprise customers love reports. Providing a button to export the last 30 days of activity to a CSV file is a "wow" feature that takes very little effort to build.
Leverage MongoDB TTL Indexes: Use a Time-To-Live (TTL) index in MongoDB to automatically delete log entries after a certain period (e.g., 90 days). This ensures your database doesn't grow infinitely with old data.
How This Fits Into the Zero to SaaS Journey
Activity logs are the "final polish" of a professional SaaS. In the Zero to SaaS curriculum, we implement this once your Multi-Tenancy logic is in place.
By adding an audit trail, you are signaling to your users that your platform is stable, secure, and ready for serious business. You are moving from a "side project" mindset to a "software company" mindset.
Real-World Example: A Cloud Infrastructure SaaS
- Action: An admin changes the firewall settings for a production server.
- Logging: The system records: "Admin 'Mike' updated Firewall Rules for 'Server-01' at 2:00 PM."
- Outcome: When the server goes down at 2:05 PM, the rest of the team can check the log, see exactly what Mike changed, and revert it instantly.
This level of transparency saves hours of downtime and prevents internal conflict.
Action Plan and What to Build Next
- Create the
activity_logscollection in your MongoDB database. - Build the
recordActivityhelper in your/libdirectory. - Add logging to your 3 most critical actions (e.g., Delete Project, Invite Member, Change Plan).
- Create an "Activity" tab in your Organization settings to display the feed.
You have now mastered the most advanced architectural patterns for a modern SaaS. Your application is secure, scalable, transparent, and ready for the enterprise market. What is the final step? Ensuring your code remains clean as you continue to innovate. Check out our Advanced Testing and Quality Assurance guide to learn how to keep your app bug-free at scale.
Build the product that pros use. The Zero to SaaS Course teaches you the features that move the needle for high-paying customers. Join us and learn how to build for the big leagues. Let's ship your enterprise-ready SaaS today.