Skip to main content

Overview

The Retrieve Report endpoint fetches complete details for a single report, including full client and user information. This endpoint is useful for displaying report details, downloading PDFs, and accessing complete analytics data.

Endpoint

GET /api/reports/{id}

Authentication

Requires authentication via NextAuth.js session cookie. Users can only retrieve reports they own.

Path Parameters

id
string
required
The unique identifier (CUID) of the report to retrieve.

Response

Success Response (200 OK)

Returns a detailed report object with nested client and user information:
report
object
Complete report object with all fields

Error Responses

{
  "error": "Unauthorized"
}

Example Request

curl -X GET https://your-domain.com/api/reports/clxreport123456 \
  -H "Cookie: next-auth.session-token=..."

Example Response

{
  "id": "clxreport123456",
  "title": "Standard Report - Acme Corp (2024-01-01 to 2024-01-31)",
  "status": "COMPLETED",
  "data": {
    "clientName": "Acme Corp",
    "startDate": "2024-01-01",
    "endDate": "2024-01-31",
    "reportType": "standard",
    "generatedAt": "2024-02-01T10:25:15.123Z",
    "gscData": {
      "clicks": 12500,
      "impressions": 450000,
      "ctr": 0.0278,
      "position": 8.5,
      "topQueries": [
        {
          "query": "seo services",
          "clicks": 1250,
          "impressions": 45000,
          "ctr": 0.0278,
          "position": 5.2
        },
        {
          "query": "digital marketing agency",
          "clicks": 980,
          "impressions": 38000,
          "ctr": 0.0258,
          "position": 6.8
        }
      ],
      "dailyData": [
        {
          "date": "2024-01-01",
          "clicks": 400,
          "impressions": 15000,
          "ctr": 0.0267,
          "position": 8.7
        },
        {
          "date": "2024-01-02",
          "clicks": 425,
          "impressions": 15500,
          "ctr": 0.0274,
          "position": 8.4
        }
      ]
    },
    "ga4Data": {
      "users": 8500,
      "sessions": 12000,
      "bounceRate": 0.42,
      "conversions": 150,
      "newUsers": 5200,
      "engagementRate": 0.68,
      "avgSessionDuration": 185,
      "pagesPerSession": 3.2,
      "organicTraffic": 7200,
      "directTraffic": 2100,
      "referralTraffic": 1800,
      "socialTraffic": 900,
      "topLandingPages": [
        {
          "page": "/services",
          "sessions": 3200,
          "users": 2800,
          "bounceRate": 0.35,
          "conversions": 45
        },
        {
          "page": "/blog/seo-guide",
          "sessions": 2100,
          "users": 1950,
          "bounceRate": 0.28,
          "conversions": 18
        }
      ],
      "deviceBreakdown": {
        "mobile": 5100,
        "desktop": 2800,
        "tablet": 600
      }
    },
    "pageSpeedData": {
      "mobile": {
        "score": 78,
        "lcp": 2.4,
        "fid": 85,
        "cls": 0.08
      },
      "desktop": {
        "score": 92,
        "lcp": 1.2,
        "fid": 45,
        "cls": 0.03
      },
      "opportunities": [
        {
          "title": "Reduce unused JavaScript",
          "description": "Reduce unused JavaScript and defer loading scripts until they are required.",
          "displayValue": "Potential savings of 125 KiB"
        },
        {
          "title": "Properly size images",
          "description": "Serve images that are appropriately-sized to save cellular data and improve load time.",
          "displayValue": "Potential savings of 89 KiB"
        }
      ],
      "fetchedAt": "2024-02-01T10:25:18.000Z"
    },
    "insights": [
      {
        "id": "insight-1",
        "title": "Strong Search Visibility Growth",
        "description": "Your average search position improved by 15% this month, with particularly strong performance in long-tail keywords. The CTR increase of 12% indicates that your meta descriptions are resonating well with searchers.",
        "priority": "high",
        "category": "performance",
        "recommendations": [
          "Continue optimizing for long-tail keywords that are currently ranking in positions 6-10",
          "Create more content targeting related search queries to capture additional traffic",
          "Monitor and replicate the meta description patterns that are driving high CTR"
        ]
      },
      {
        "id": "insight-2",
        "title": "Mobile Performance Optimization Needed",
        "description": "Your mobile PageSpeed score of 78 is good, but there's room for improvement. The LCP of 2.4s is approaching the threshold, and mobile users represent 60% of your traffic.",
        "priority": "medium",
        "category": "technical",
        "recommendations": [
          "Reduce unused JavaScript to improve initial load time by ~125 KiB",
          "Properly size images for mobile viewports to save ~89 KiB",
          "Consider implementing lazy loading for below-the-fold images"
        ]
      }
    ],
    "agencyName": "Digital Marketing Pro",
    "agencyLogo": "https://blob-storage.com/logos/dmp-logo.png",
    "dataSourceInfo": {
      "hasGSC": true,
      "hasGA4": true,
      "hasPageSpeed": true,
      "pageSpeedFromRequest": true,
      "metricsCount": 15,
      "hasCustomFields": false,
      "selectedMetricsCount": 0,
      "aiInsightsAvailable": true
    }
  },
  "pdfUrl": "https://your-blob-storage.com/reports/acme-corp_standard_2024-01-01_2024-01-31_1706789123456.pdf",
  "pdfSize": 524288,
  "processingStartedAt": "2024-02-01T10:25:15.123Z",
  "processingCompletedAt": "2024-02-01T10:25:47.456Z",
  "generationTimeMs": 32333,
  "errorMessage": null,
  "createdAt": "2024-02-01T10:25:15.123Z",
  "updatedAt": "2024-02-01T10:25:47.456Z",
  "clientId": "clx1234567890",
  "userId": "clxuser123",
  "aiInsights": [
    {
      "id": "insight-1",
      "title": "Strong Search Visibility Growth",
      "description": "Your average search position improved by 15% this month.",
      "priority": "high",
      "category": "performance",
      "recommendations": [
        "Continue optimizing for long-tail keywords",
        "Create more content targeting related queries"
      ]
    },
    {
      "id": "insight-2",
      "title": "Mobile Performance Optimization Needed",
      "description": "Mobile PageSpeed score of 78 has room for improvement.",
      "priority": "medium",
      "category": "technical",
      "recommendations": [
        "Reduce unused JavaScript",
        "Properly size images for mobile"
      ]
    }
  ],
  "aiInsightsSource": "ai",
  "aiInsightsGeneratedAt": "2024-02-01T10:25:20.789Z",
  "aiTokensUsed": 2000,
  "aiCostUsd": 0.012,
  "aiError": null,
  "client": {
    "id": "clx1234567890",
    "name": "Acme Corp",
    "domain": "acmecorp.com",
    "contactEmail": "[email protected]",
    "contactName": "John Smith"
  },
  "user": {
    "id": "clxuser123",
    "name": "Jane Doe",
    "email": "[email protected]",
    "companyName": "Digital Marketing Pro",
    "primaryColor": "#3B82F6",
    "logo": "https://blob-storage.com/logos/dmp-logo.png"
  }
}

Use Cases

Display Report Details

Fetch complete report information for display on a report detail page, including all analytics data and AI insights.

Download PDF

Use the pdfUrl field to provide a download link or embed the PDF in an iframe.

Regenerate Report

Extract the data field to regenerate a report with the same configuration and parameters.

Performance Analysis

Analyze generationTimeMs, pdfSize, and AI cost metrics for optimization and billing.

Troubleshooting

Check status, errorMessage, and aiError fields to diagnose failed report generations.

Client Reporting

Combine report data with client and user information for comprehensive client dashboards.

Security

This endpoint implements ownership verification:
  1. Requires valid authentication session
  2. Verifies that the report belongs to the authenticated user
  3. Returns 404 if report doesn’t exist OR doesn’t belong to the user (preventing enumeration)

Data Persistence

All report data is stored in PostgreSQL with:
  • JSONB storage for flexible data field
  • Indexed queries on userId, clientId, and status
  • Cascade deletion when user or client is deleted
  • Automatic timestamps for createdAt and updatedAt

Delete Report

Endpoint

DELETE /api/reports/{id}

Description

Permanently deletes a report and updates the associated client’s report count.

Path Parameters

id
string
required
The unique identifier of the report to delete.

Response

{
  "success": true
}

Example Request

curl -X DELETE https://your-domain.com/api/reports/clxreport123456 \
  -H "Cookie: next-auth.session-token=..."

Behavior

  1. Verifies report exists and belongs to authenticated user
  2. Deletes the report record from database
  3. Decrements the client’s totalReportsGenerated count
  4. Does NOT delete the PDF file from Vercel Blob (manual cleanup required)
Note: Consider implementing blob storage cleanup in a background job for production use.

Build docs developers (and LLMs) love