Skip to main content

Express.js / Node.js Integration Guide

Overview

This guide explains how to integrate the AmpliServ Backend SDK with your Express.js/Node.js application.

Prerequisites

  • Node.js 14 or higher
  • Express.js 4.x or 5.x
  • npm or yarn
  • AmpliServ SDK binary

Step 1: Install Dependencies

npm install winston uuid
# OR
yarn add winston uuid

Step 2: Configure Winston Logger

Create logger.js:

import winston from 'winston';
import { v4 as uuidv4 } from 'uuid';

// Create winston logger with JSON format
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json() // CRITICAL: JSON format for SDK
),
transports: [
new winston.transports.Console(),
new winston.transports.File({
filename: 'app.log', // SDK will read this file
format: winston.format.json()
})
]
});

// Helper to get correlation ID
logger.getCorrelationId = (req) => {
return req.headers['x-correlation-id'] ||
req.headers['x-request-id'] ||
uuidv4();
};

export default logger;

Step 3: Add Correlation ID Middleware

In your main server.js or app.js:

import express from 'express';
import logger from './logger.js';

const app = express();

// Correlation ID Middleware
app.use((req, res, next) => {
const correlationId = logger.getCorrelationId(req);

req.correlationId = correlationId;
res.setHeader('X-Correlation-ID', correlationId);

// Add to logger context
const childLogger = logger.child({ correlation_id: correlationId });
req.logger = childLogger;

// Log incoming request
childLogger.info({
message: `Incoming ${req.method} ${req.path}`,
method: req.method,
path: req.path,
ip: req.ip
});

// Track response time
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
const logLevel = res.statusCode >= 400 ? 'error' : 'info';

childLogger[logLevel]({
message: `${req.method} ${req.path} ${res.statusCode} - ${duration}ms`,
method: req.method,
path: req.path,
statusCode: res.statusCode,
duration
});
});

next();
});

// Error handling middleware (captures stack traces)
app.use((err, req, res, next) => {
req.logger.error({
message: err.message,
stack: err.stack, // Full stack trace captured here
correlation_id: req.correlationId
});

res.status(500).json({
message: 'Internal Server Error',
correlationId: req.correlationId
});
});

export default app;

Step 4: Add Test Endpoints

// Test endpoint for errors
app.get('/api/test/error', (req, res) => {
req.logger.info('Test error endpoint called');

try {
// Simulate deep error
function level3() {
throw new Error('This is a test error with deep stack trace!');
}

function level2() { level3(); }
function level1() { level2(); }

level1();
} catch (error) {
req.logger.error({
message: 'Test error occurred',
error: error.message,
stack: error.stack
});

res.status(500).json({ message: 'Error triggered', correlationId: req.correlationId });
}
});

// Test normal endpoint
app.get('/api/test/info', (req, res) => {
req.logger.info('Info endpoint called');
res.json({ message: 'Info logged successfully' });
});

// Test warning endpoint
app.get('/api/test/warn', (req, res) => {
req.logger.warn('Warning endpoint called - This is a warning');
res.json({ message: 'Warning logged' });
});

Step 5: Configure AmpliServ SDK

Create run-agent.bat (Windows) or run-agent.sh (Linux/Mac):

#!/bin/bash
export AMPLISERV_API_KEY="your-api-key-here"
export AMPLISERV_COLLECTOR_MODE="file"
export AMPLISERV_ENDPOINT="http://dev-backend.ampliserv.com/api/ingestion/v1/ingest"
export AMPLISERV_SERVICE_NAME="ingestion-service"
export AMPLISERV_ENV="development"
export AMPLISERV_LOG_PATH="./app.log"
export AMPLISERV_BATCH_SIZE="50"
export AMPLISERV_FLUSH_INTERVAL_SEC="5"
export AMPLISERV_INCIDENT_ENABLED="true"

./ampliserv-agent

Step 6: Update package.json

{
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
}
}

Step 7: Run the Integration

Terminal 1: Start Express Application

npm start

Terminal 2: Start AmpliServ SDK

./run-agent.sh

Terminal 3: Test

curl http://localhost:3000/api/test/info
curl http://localhost:3000/api/test/error

Sample JSON Log Output

{
"level": "error",
"message": "Test error occurred",
"correlation_id": "a1270278-7ef9-4e59-803e-e9862c257d73",
"error": "This is a test error with deep stack trace!",
"stack": "Error: This is a test error with deep stack trace!\n at level3 (/app/server.js:45:15)\n at level2 (/app/server.js:46:22)\n at level1 (/app/server.js:47:15)\n at /app/server.js:50:9",
"timestamp": "2026-03-23T10:30:45.123Z"
}

Verification Checklist

  • Express app starts without errors
  • app.log file is created
  • Logs are in JSON format
  • AmpliServ SDK shows "Starting AmpliServ Agent"
  • SDK displays "Mode: file"
  • Test endpoints produce logs
  • Stack traces are visible in logs