Back to Blog
June 6, 2026 10 min read Developers

Building a Prompt Pipeline
with ZETRAXAI SDK and Next.js

A comprehensive step-by-step developer tutorial showing how to build dynamic prompting pipelines using ZETRAXAI, Next.js 15, and Server Actions.

In modern web applications, integrating generative AI is no longer just about sending a direct request to OpenAI or Anthropic. To achieve consistent quality and guardrails, developers must construct robust prompt pipelines that handle template rendering, validation, dynamic context injection, and system formatting before the request ever hits an LLM provider.

In this technical tutorial, we walk through how to build a dynamic, production-ready prompt pipeline using the official ZETRAXAI SDK within a Next.js 15 app, taking advantage of React Server Actions and streaming responses.

Prerequisites

Before starting, make sure you have the following:

  • Node.js 18+ installed on your machine
  • A Next.js 15 application setup (App Router)
  • A free ZETRAX.appAI API Key

Step 1: Installing the ZETRAXAI SDK

First, install the official ZETRAXAI developer SDK in your project directory:

Terminal
npm install @zetrax/sdk

Step 2: Configuring Environment Variables

Create or update your .env.local file in the root of your Next.js project and add your API credentials:

.env.local
ZETRAX_API_KEY=zx_live_59f4483e... NEXT_PUBLIC_APP_URL=http://localhost:3000

Step 3: Initializing the ZETRAXAI Client

Create a utility file to initialize the client singleton. This ensures we don't spin up redundant connections during hot reloading in development.

lib/zetrax.ts
import { ZetraxClient } from '@zetrax/sdk'; const globalForZetrax = global as unknown as { zetrax: ZetraxClient }; export const zetrax = globalForZetrax.zetrax || new ZetraxClient({ apiKey: process.env.ZETRAX_API_KEY, }); if (process.env.NODE_ENV !== 'production') globalForZetrax.zetrax = zetrax;

Step 4: Creating a Server Action for Prompt Generation

Now, let's create a React Server Action to compile prompts dynamically based on user input, using ZETRAXAI's advanced templating and negative prompt matching capabilities.

app/actions/prompt.ts
'use server'; import { zetrax } from '@/lib/zetrax'; export async function generateStructuredPrompt(formData: FormData) { const subject = formData.get('subject') as string; const category = formData.get('category') as string; if (!subject) { return { error: 'Subject is required' }; } try { const pipeline = await zetrax.pipelines.compile({ templateId: category === 'cinematic' ? 'tpl_drone' : 'tpl_portrait', variables: { subject: subject, aspectRatio: '16:9', quality: 'ultra-detailed' } }); return { success: true, prompt: pipeline.compiledPrompt, negatives: pipeline.compiledNegatives }; } catch (err: any) { return { error: err.message || 'Pipeline failed to compile' }; } }

Step 5: Implementing the UI Component

Let's construct a simple client form component in Next.js that invokes our Server Action and renders the generated structured output in real time.

app/components/PromptForm.tsx
'use client'; import { useState } from 'react'; import { generateStructuredPrompt } from '../actions/prompt'; export default function PromptForm() { const [result, setResult] = useState(null); const [loading, setLoading] = useState(false); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setLoading(true); const formData = new FormData(e.currentTarget); const res = await generateStructuredPrompt(formData); setResult(res); setLoading(false); }; return (
{result?.success && (

Compiled Prompt:

{result.prompt}

Negatives:

{result.negatives}

)}
); }

Conclusion

By delegating prompt compilation, structure, and variable parsing to the ZETRAXAI SDK, you eliminate hardcoded template strings and ensure your prompt structures remain version-controlled and highly adaptable. This setup is fully scalable and ready to be connected directly to your streaming chat endpoints.

To learn more about advanced SDK integrations, check out the official ZETRAXAI SDK Documentation.

Architecture Overview

Before integrating the ZETRAX SDK, it helps to understand the architecture. The SDK communicates with ZETRAX's RESTful API to generate, enhance, and analyze AI prompts. In a Next.js application, you'll want to make API calls server-side (in API routes or Server Components) to keep your API key secure and avoid exposing it to the browser.

Server-Side Only

Always initialize the SDK in server-side code (API routes, Server Components, or getServerSideProps). Never import or initialize the SDK in client-side components — your API key would be exposed in the browser bundle.

Environment Variables

Store your API key in .env.local as ZETRAX_API_KEY (without the NEXT_PUBLIC_ prefix). Variables without the NEXT_PUBLIC_ prefix are only available server-side in Next.js, which is exactly what you want for API keys.

Streaming Support

The SDK supports streaming responses for AI enhancement and chat features. In Next.js, use ReadableStream in your API routes to stream data to the client for real-time UI updates.

Common Integration Patterns

Pattern 1: Prompt Generation API Route

The most common pattern is creating a Next.js API route that accepts prompt parameters from your frontend and returns the generated prompt. This keeps all SDK interaction server-side while providing a clean API for your React components.

Pattern 2: Server Component with Direct SDK Access

In Next.js 13+ with the App Router, you can call the SDK directly in Server Components. This is ideal for pages that display pre-generated prompts or templates — the SDK call happens during server rendering, and the client receives only the rendered HTML.

Pattern 3: Streaming Enhancement

For real-time AI prompt enhancement (where the user sees the enhanced prompt being generated word-by-word), use the SDK's streaming mode combined with Next.js API routes that return ReadableStream responses. This creates a ChatGPT-like streaming experience in your application.

Error Handling Best Practices

Production applications should implement robust error handling for SDK calls:

Performance Optimization

Caching Strategies

For prompt templates and frequently generated prompts, implement caching at the API route level. Next.js supports built-in response caching for API routes, and you can use Redis or similar for more sophisticated caching. Template prompts that don't change often can be cached for hours or days, significantly reducing API calls and improving response time.

Edge Runtime Compatibility

The ZETRAX SDK is compatible with Next.js Edge Runtime, which means you can deploy your prompt generation API routes to Vercel Edge Functions for lower latency. Edge functions run closer to your users geographically, reducing round-trip time for prompt generation requests.

Frequently Asked Questions

Does the SDK work with Next.js App Router and Pages Router?

Yes, the SDK works with both. For the App Router, use it in Server Components or Route Handlers (app/api/). For the Pages Router, use it in API routes (pages/api/) or getServerSideProps. The key requirement is server-side execution — never import the SDK in client components.

What's the minimum Next.js version required?

The SDK works with Next.js 12+ for Pages Router usage and Next.js 13.4+ for App Router features. For streaming support, we recommend Next.js 14+ which has improved streaming infrastructure. TypeScript types are included in the package.

How do I handle authentication for my users?

Your ZETRAX API key authenticates your application, not individual users. If you want to track per-user usage, implement your own authentication layer (e.g., NextAuth.js) and track API calls per user in your database. The SDK accepts a custom header for passing user identifiers for analytics purposes.

Can I use the SDK with Vercel serverless functions?

Yes, the SDK is fully compatible with Vercel's serverless and edge function environments. Store your API key as a Vercel environment variable and access it via process.env.ZETRAX_API_KEY. The SDK's lightweight footprint keeps cold start times minimal.

Related Articles