How to Add Audit Logs to Express.js

TL;DR: Add Trailbase audit logging to your Express.js API. Use middleware for automatic request logging or manual tracking for specific business events.

Step 1: Install the SDK

npm install @trailbase/sdk

Step 2: Initialize the Client

const { TrailbaseClient } = require('@trailbase/sdk');

const trailbase = new TrailbaseClient({
  apiKey: process.env.TRAILBASE_API_KEY,
  region: 'us-east-1',
});

For Express, you can use middleware for blanket request logging or call trailbase.track() manually for specific business events. The middleware approach captures all API calls automatically.

Step 3: Track Audit Events

// Middleware for automatic audit logging
app.use((req, res, next) => {
  res.on('finish', () => {
    trailbase.track(`${req.method.toLowerCase()}.${req.path}`, {
      actor: req.user?.id,
      metadata: { statusCode: res.statusCode, ip: req.ip },
    });
  });
  next();
});

// Or track specific events manually
app.post('/api/users/:id/role', async (req, res) => {
  await trailbase.track('user.role.update', {
    actor: req.user.id,
    target: req.params.id,
    metadata: { newRole: req.body.role },
  });
  // ... your logic
});

Step 4: Query Audit Logs

app.get('/api/audit', async (req, res) => {
  const events = await trailbase.search({
    actor: req.query.userId,
    from: req.query.from,
    to: req.query.to,
  });
  res.json(events);
});

Other Integrations

Next.jsTypeScriptFastifyTypeScriptNestJSTypeScript

Ready to Add Audit Logs to Express.js?

Join the waitlist for early access. Five-minute setup, no infrastructure changes.

Get Early Access