Next.js API Routes
Relevant source files
The following files were used as context for generating this wiki page:
Next.js API Routes in the ZINC-Fusion-V15 project serve as the primary interface between the institutional-grade forecasting models and the frontend dashboard. These routes act as a high-performance orchestration layer that aggregates data from multiple PostgreSQL schemas (such as mkt, econ, forecasts, and analytics) to provide real-time market intelligence, multi-horizon forecasts, and procurement recommendations.
The API architecture follows a "force-dynamic" policy for mission-critical routes to ensure that users receive the most recent data available in the data warehouse. This layer is responsible for complex backend tasks including calculating real-time volatility stress, crush margin pressure, and cross-asset correlations before delivering the payload to the user interface.
Sources: frontend/src/app/api/zl/brief/route.ts:13-16, README.md:168-172, AGENTS.md:14-16
Architecture and Data Flow
The Next.js API routes are built using the App Router convention, located primarily within frontend/src/app/api/. These routes utilize the pg library for direct database queries instead of a traditional ORM like Prisma for runtime operations, ensuring low-latency access to the 12 distinct database schemas.
Request Orchestration
Each request typically follows a waterfall or parallel fetching pattern to gather the necessary components for a comprehensive brief. This includes:
- Price Fetching: Retrieving the "freshest" price by checking high-frequency tables (1m, 15m, 1h) and falling back to daily tables if necessary.
- Forecast Aggregation: Pulling multi-horizon predictions (1W, 1M, 3M, 6M) from the
forecasts.production_1dtable. - Driver Scoring: Calculating stress levels for core market drivers like VIX, Crush Margins, and FX rates using specialized service modules.
- Correlation Calculation: Performing real-time statistical analysis (e.g., Pearson correlation on log-returns) across different commodity futures.
The following diagram illustrates the data flow for a typical market brief request:
A visual representation of the internal API logic where multiple data sources are combined into a single institutional brief.
Sources: frontend/src/app/api/zl/brief/route.ts:88-100, frontend/src/app/api/zl/brief/route.ts:121-128, AGENTS.md:14-16
Standard API Configuration
API routes are configured with specific Vercel and Next.js directives to manage execution environment and performance.
Runtime Configuration
All production API routes must declare specific exports to control their behavior on the Vercel edge or Node.js runtime.
- Runtime:
nodejsis the default for complex data processing. - maxDuration: Controlled via
cubic.yamlrules, usually 30-60 seconds for standard routes and up to 300 seconds for Inngest-managed background jobs. - Dynamic Policy: Set to
force-dynamicto bypass static generation for real-time pricing.
| Parameter | Value/Default | Source File |
|---|---|---|
dynamic | force-dynamic | zl/brief/route.ts:18 |
maxDuration (Standard) | 30 - 60s | cubic.yaml:236 |
maxDuration (Inngest) | 300s | cubic.yaml:236 |
runtime | nodejs | cubic.yaml:235 |
Core API Logic: ZL Procurement Brief
The zl/brief route is a primary example of the project's complex API logic. It consolidates live prices, driver scores, and actionable recommendations.
Statistical Correlation Calculation
The API performs real-time correlation analysis on log-returns to avoid spurious correlations common in raw price levels. It uses a 64-day lookback to generate a 3-month rolling correlation against assets like Soybean Meal (ZM), Crude Oil (CL), and the VIX.
WITH zl AS (SELECT event_date, LN(close / NULLIF(LAG(close) OVER (ORDER BY event_date), 0)) as ret
FROM mkt.futures_1d WHERE symbol = 'ZL' ORDER BY event_date DESC LIMIT 64),
zm AS (SELECT event_date, LN(close / NULLIF(LAG(close) OVER (ORDER BY event_date), 0)) as ret
FROM mkt.futures_1d WHERE symbol = 'ZM' ORDER BY event_date DESC LIMIT 64)
SELECT CORR(zl.ret, zm.ret)::float8 as corr FROM zl JOIN zm ON zl.event_date = zm.event_date
Sources: frontend/src/app/api/zl/brief/route.ts:245-251
Data Integrity Guards
To maintain "institutional grade" accuracy, the API implements strict data integrity policies:
- No Fake Data: If model forecasts are unavailable, the API returns
nullplaceholders rather than synthetic values. - Freshness Checks: Data is compared against the current date; if indicators (like VIX or Crush) are older than 3 days, they are flagged as "stale" in the response.
- Validation: Input values are checked for
NaN,null, or zero before being processed in score calculations.
The sequence of data validation and normalization performed by the API routes to ensure data quality.
Sources: frontend/src/app/api/zl/brief/route.ts:169-182, cubic.yaml:209-216, frontend/src/app/api/zl/brief/route.ts:210-215
Dependency Management
The API routes depend on several key packages and internal libraries as defined in the project structure.
| Dependency | Purpose | Source |
|---|---|---|
pg | Direct PostgreSQL connection pooling for runtime queries. | package.json:71 |
inngest | Orchestrates background data ingestion and sync jobs. | package.json:49 |
next | Provides the App Router and API handling framework. | package.json:69 |
@/lib/db | Internal database utility for executing SQL. | zl/brief/route.ts:11 |
vix-service | Logic for calculating market stress from VIX levels. | zl/brief/route.ts:12 |
Sources: frontend/package.json, AGENTS.md:14-16
Conclusion
Next.js API routes in ZINC-Fusion-V15 are more than just simple CRUD endpoints; they are complex analytical services. By strictly adhering to "force-dynamic" data fetching, implementing real-time statistical calculations, and enforcing rigorous data integrity checks, these routes provide the reliable, real-time intelligence required for institutional-grade commodity procurement.
Sources: frontend/src/app/api/zl/brief/route.ts:446-455, README.md:12-25