Skip to content

dax-side/multi-tenant-analytics-saas-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Multi-Tenant Analytics SaaS API

A multi-tenant SaaS platform where companies can track user events, build custom dashboards, and manage analytics data.

Features

  • Multi-Tenant Architecture: Isolated data per tenant
  • Event Tracking: REST API for tracking user events
  • GraphQL API: Flexible queries for analytics data
  • Authentication: JWT + OAuth (Google)
  • Role-Based Access Control: Owner, Admin, Member, Viewer roles
  • Real-time Dashboards: Customizable charts and reports

Tech Stack

  • Backend: Node.js, TypeScript, Express
  • Database: PostgreSQL with Prisma ORM
  • GraphQL: Apollo Server, Type-GraphQL
  • Authentication: Passport.js, JWT
  • Caching: Redis
  • Security: Helmet, CORS, Rate Limiting

Getting Started

Prerequisites

  • Node.js (v18+)
  • PostgreSQL
  • Redis (optional, for caching)

Installation

  1. Clone the repository

  2. Install dependencies:

    npm install
  3. Set up environment variables: Copy .env and update the values:

    DATABASE_URL="postgresql://username:password@localhost:5432/multi_tenant_analytics"
    JWT_SECRET="your-secret-key"
    GOOGLE_CLIENT_ID="your-google-client-id"
    GOOGLE_CLIENT_SECRET="your-google-client-secret"
    REDIS_URL="redis://localhost:6379"
  4. Set up the database:

    npx prisma migrate dev --name init
    npx prisma generate
  5. Build the project:

    npm run build
  6. Test the API:

    node test-api.js

    This will test all endpoints with sample data.

Authentication

The API uses JWT tokens with Google OAuth integration.

OAuth Setup

  1. Create a Google OAuth app at Google Cloud Console
  2. Set redirect URI to: http://localhost:3000/auth/google/callback
  3. Update .env with your credentials:
    GOOGLE_CLIENT_ID=your-client-id
    GOOGLE_CLIENT_SECRET=your-client-secret

Authentication Endpoints

  • GET /auth/google - Initiate Google OAuth
  • GET /auth/google/callback - OAuth callback
  • POST /auth/refresh - Refresh access token

Headers

Include these headers in requests:

Authorization: Bearer <access_token>
x-tenant-id: <tenant_id>

Event Tracking API

Track user events from your applications with simple REST endpoints and GraphQL mutations.

REST API

Track Single Event

POST /api/track
Content-Type: application/json
x-tenant-id: your-tenant-id

{
  "event": "user_signup",
  "properties": {
    "email": "[email protected]",
    "plan": "premium"
  },
  "userId": "user_123",
  "sessionId": "session_456",
  "timestamp": "2025-01-15T10:00:00Z",
  "projectId": "project_789"
}

Track Multiple Events

POST /api/track/bulk
Content-Type: application/json
x-tenant-id: your-tenant-id

{
  "events": [
    {
      "event": "page_view",
      "properties": { "page": "/dashboard" },
      "userId": "user_123"
    },
    {
      "event": "button_click",
      "properties": { "button": "export" },
      "userId": "user_123"
    }
  ],
  "projectId": "project_789"
}

GraphQL API

Access GraphQL playground at http://localhost:3000/graphql

Track Event

mutation {
  trackEvent(
    input: {
      name: "user_signup"
      properties: { "email": "[email protected]" }
      userId: "user_123"
    }
    projectId: "project_789"
  ) {
    id
    name
    timestamp
  }
}

Query Events

query {
  events(
    filter: {
      eventName: "user_signup"
      startDate: "2025-01-01T00:00:00Z"
      limit: 50
    }
  ) {
    id
    name
    properties
    userId
    timestamp
    project {
      name
    }
  }
}

Get Event Statistics

query {
  eventStats(days: 7) {
    totalEvents
    eventsByType
    period
  }
}

Advanced Event Analytics

query {
  eventAnalytics(period: "30d") {
    totalEvents
    uniqueUsers
    topEvents {
      event
      count
    }
    timeSeries {
      time
      events
    }
    period
    startDate
    endDate
  }
}

Event Aggregations

query {
  eventAggregations(groupBy: "name", filter: { startDate: "2025-01-01T00:00:00Z" }) {
    group
    count
    groupBy
  }
}

Project Management

query {
  projects {
    id
    name
    description
    eventCount
  }
}

mutation {
  createProject(input: { name: "My App", description: "Analytics for my app" }) {
    id
    name
  }
}

Dashboard Management

query {
  dashboards {
    id
    name
    description
    viewCount
    createdAt
  }
}

mutation {
  createDashboard(input: {
    name: "User Analytics Dashboard"
    description: "Track user behavior and engagement"
    charts: [
      {
        id: "chart1"
        type: "line"
        title: "Daily Active Users"
        dataSource: {
          queryType: "eventAnalytics"
          timeRange: "30d"
          filters: { eventName: "user_login" }
        }
        styling: {
          colors: ["#3B82F6", "#10B981"]
          showLegend: true
        }
      }
    ]
  }) {
    id
    name
    config
  }
}

mutation {
  recordDashboardView(dashboardId: "dashboard_id") {
    id
    viewedAt
  }
}

Dashboard Features

  • Custom Chart Configurations: Support for line, bar, pie, area charts
  • Flexible Data Sources: Connect to any analytics query
  • Real-time Updates: Dashboard changes are tracked
  • View Analytics: Track dashboard usage and popularity
  • Tenant Isolation: Each tenant has their own dashboards

Chart Types Supported

  • Line Charts: Time series data visualization
  • Bar Charts: Categorical data comparison
  • Pie Charts: Proportion visualization
  • Area Charts: Cumulative data trends

Data Source Integration

Charts can connect to:

  • eventAnalytics - Comprehensive analytics data
  • eventAggregations - Grouped event data
  • custom - Custom query results

Dashboard Configuration

Each dashboard contains:

  • Chart Array: Multiple charts per dashboard
  • Data Sources: Configurable queries and filters
  • Styling Options: Colors, legends, dimensions
  • Real-time Updates: Automatic refresh capabilities

Database Schema

See prisma/schema.prisma for the complete database schema including:

  • Tenants
  • Users
  • Projects
  • Events
  • Dashboards

Development

Scripts

  • npm run build - Compile TypeScript
  • npm run start - Start production server
  • npm run dev - Start development server with hot reload
  • npm run prisma:generate - Generate Prisma client
  • npm run prisma:migrate - Run database migrations
  • npm run prisma:studio - Open Prisma Studio

Project Structure

src/
├── index.ts          # Main entry point
├── resolvers/        # GraphQL resolvers
├── services/         # Business logic
├── middleware/       # Express middleware
├── auth/             # Authentication logic
└── utils/            # Utility functions

prisma/
├── schema.prisma     # Database schema
└── migrations/       # Database migrations

Deployment

Environment Variables

Make sure to set the following in production:

  • DATABASE_URL - PostgreSQL connection string
  • JWT_SECRET - Secret key for JWT
  • GOOGLE_CLIENT_ID - Google OAuth client ID
  • GOOGLE_CLIENT_SECRET - Google OAuth client secret
  • REDIS_URL - Redis connection string
  • PORT - Server port (default: 3000)

Production Build

npm run build
npm start

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Run tests
  5. Submit a pull request

License

ISC

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published