n4nAI

Vercel AI SDK environment variables for n4n.ai API keys

Configure Vercel AI SDK with n4n.ai API keys using environment variables for local development and production deployments.

n4n Team4 min read841 words

Audio narration

Coming soon — every post will get a voice note here.

The Vercel AI SDK expects provider credentials in specific environment variable names, but n4n.ai uses an OpenAI-compatible endpoint that requires a different variable mapping. This guide walks through wiring the two together for local development, preview deployments, and production — without hardcoding secrets or fighting the SDK’s provider abstraction.

Step 1: Understand the variable mapping

The Vercel AI SDK’s OpenAI provider reads OPENAI_API_KEY by default. n4n.ai exposes an OpenAI-compatible endpoint at https://api.n4n.ai/v1 and expects your n4n.ai API key in the Authorization: Bearer header. You have two options: override the base URL on the provider instance, or set OPENAI_API_KEY to your n4n.ai key and OPENAI_BASE_URL to the n4n.ai endpoint. The second approach keeps your application code provider-agnostic and is the pattern we recommend.

# .env.local (local development)
OPENAI_API_KEY=n4n_your_api_key_here
OPENAI_BASE_URL=https://api.n4n.ai/v1

The SDK’s createOpenAI factory respects both variables automatically. No custom provider wrapper required.

Step 2: Create the API key in n4n.ai

Log into the n4n.ai dashboard and generate an API key scoped to the models your application needs. Keys are prefixed n4n_ and support per-model permissions. Copy the key immediately — you won’t see it again.

# Example key format (not a real key)
n4n_sk_live_abcdef1234567890abcdef1234567890

Store this in your password manager. Treat it like any production secret.

Step 3: Configure local development

Create .env.local at your project root. Next.js and Vite both load this file automatically and exclude it from git via their default .gitignore entries.

# .env.local
OPENAI_API_KEY=n4n_sk_live_abcdef1234567890abcdef1234567890
OPENAI_BASE_URL=https://api.n4n.ai/v1

If you’re using the App Router, restart the dev server after adding the file. The Pages Router picks up changes without a restart.

Verify the variables load by adding a temporary route:

// app/api/debug/route.ts (App Router)
import { NextResponse } from 'next/server'

export async function GET() {
  return NextResponse.json({
    hasKey: !!process.env.OPENAI_API_KEY,
    baseUrl: process.env.OPENAI_BASE_URL,
    keyPrefix: process.env.OPENAI_API_KEY?.slice(0, 4),
  })
}

Hit http://localhost:3000/api/debug and confirm the response shows your key prefix (n4n_) and the correct base URL.

Step 4: Initialize the provider in application code

Import createOpenAI from @ai-sdk/openai and call it without arguments. The factory reads OPENAI_API_KEY and OPENAI_BASE_URL from the environment.

// lib/ai/providers.ts
import { createOpenAI } from '@ai-sdk/openai'

export const openai = createOpenAI()
// Equivalent to:
// createOpenAI({
//   apiKey: process.env.OPENAI_API_KEY,
//   baseURL: process.env.OPENAI_BASE_URL,
// })

Use the exported instance throughout your application:

// app/api/chat/route.ts
import { streamText } from 'ai'
import { openai } from '@/lib/ai/providers'

export async function POST(req: Request) {
  const { messages } = await req.json()

  const result = await streamText({
    model: openai('gpt-4o-mini'),
    messages,
    temperature: 0.3,
  })

  return result.toDataStreamResponse()
}

The model string (gpt-4o-mini) maps directly to the n4n.ai model catalog. No alias mapping needed.

Step 5: Configure preview deployments on Vercel

Push your branch to GitHub. In the Vercel dashboard, open the project settings → Environment Variables. Add two variables for the Preview environment:

Name Value Environment
OPENAI_API_KEY n4n_sk_live_... Preview
OPENAI_BASE_URL https://api.n4n.ai/v1 Preview

Do not add these to Production yet. Preview deployments let you verify the integration end-to-end before promoting.

Trigger a new preview deployment. Once live, open the deployment URL and test your chat endpoint. The request should route through n4n.ai and return a streamed response.

Step 6: Promote to production

After verifying the preview deployment, add the same two variables to the Production environment in Vercel:

Name Value Environment
OPENAI_API_KEY n4n_sk_live_... Production
OPENAI_BASE_URL https://api.n4n.ai/v1 Production

Redeploy production (or push to main). The new deployment picks up the variables automatically.

Step 7: Verify production traffic reaches n4n.ai

n4n.ai returns provider cache-control hints in response headers. Check for x-n4n-provider and x-n4n-model in the response to confirm routing worked.

curl -i -X POST https://your-app.vercel.app/api/chat \
  -H "Content-Type: application/json" \
  -d '{"messages":[{"role":"user","content":"ping"}]}'

Look for headers like:

x-n4n-provider: anthropic
x-n4n-model: claude-3-5-sonnet-20241022
x-n4n-tokens-prompt: 12
x-n4n-tokens-completion: 4

These headers confirm the request traversed n4n.ai’s gateway and reached the upstream provider. If you see x-n4n-fallback: true, the primary provider was degraded and n4n.ai automatically failed over — a feature that works transparently without code changes.

Step 8: Handle missing variables at build time

The Vercel AI SDK throws at runtime if OPENAI_API_KEY is unset. Fail fast at build time instead by validating in a env.mjs file that your CI runs:

// scripts/validate-env.mjs
const required = ['OPENAI_API_KEY', 'OPENAI_BASE_URL']

for (const key of required) {
  if (!process.env[key]) {
    console.error(`Missing required environment variable: ${key}`)
    process.exit(1)
  }
}

console.log('All required environment variables present')

Add to package.json:

{
  "scripts": {
    "validate:env": "node scripts/validate-env.mjs",
    "build": "npm run validate:env && next build"
  }
}

Vercel runs npm run build during deployment, so missing variables fail the build before a broken deployment goes live.

Step 9: Rotate keys without downtime

n4n.ai supports multiple active API keys. Generate a new key in the dashboard, add it as OPENAI_API_KEY_NEXT in Vercel (Preview first, then Production), then deploy. Once the deployment is healthy, remove the old key from n4n.ai and rename the variable back to OPENAI_API_KEY.

# Vercel CLI example for rotation
vercel env add OPENAI_API_KEY_NEXT production
# Enter new key value
vercel --prod  # deploy with new key
# Verify, then:
vercel env rm OPENAI_API_KEY production
vercel env add OPENAI_API_KEY production
# Enter new key value again
vercel --prod

This pattern avoids any window where requests fail due to an invalid key.

Step 10: Debug common failure modes

Symptom Cause Fix
401 Unauthorized from /api/chat OPENAI_API_KEY not set or invalid Verify variable exists in Vercel dashboard for the correct environment; check key prefix is n4n_
ECONNREFUSED or timeout OPENAI_BASE_URL missing or wrong Ensure https://api.n4n.ai/v1 (with /v1) is set
Model not found error Model name doesn’t exist in n4n.ai catalog Use exact model ID from n4n.ai dashboard (e.g., gpt-4o-mini, not gpt-4o-mini-2024-07-18)
Streaming stops mid-response Upstream provider timeout n4n.ai handles retries; check x-n4n-fallback header for automatic failover

For local debugging, run with DEBUG=ai:* to see the SDK’s request/response logs:

DEBUG=ai:* npm run dev

Step 11: Optional — pin model versions via routing directives

n4n.ai honors client-side routing directives passed through the model parameter. Append @provider or @version to pin a specific upstream:

// Pin to Anthropic's Claude 3.5 Sonnet (specific version)
const result = await streamText({
  model: openai('claude-3-5-sonnet-20241022@anthropic'),
  messages,
})

// Or let n4n.ai choose the best available (default behavior)
const result = await streamText({
  model: openai('gpt-4o-mini'),
  messages,
})

This keeps model selection in your application code while n4n.ai handles provider availability and fallback.

Step 12: Monitor usage and costs

n4n.ai meters per-token usage and exposes it via the dashboard and API. The response headers x-n4n-tokens-prompt and x-n4n-tokens-completion let you build client-side usage dashboards without a separate tracking pipeline.

// app/api/chat/route.ts (extended)
import { streamText } from 'ai'
import { openai } from '@/lib/ai/providers'

export async function POST(req: Request) {
  const { messages } = await req.json()

  const result = await streamText({
    model: openai('gpt-4o-mini'),
    messages,
    onFinish: ({ usage, response }) => {
      // usage.promptTokens, usage.completionTokens available here
      // response.headers.get('x-n4n-tokens-prompt') also works
      console.log('Usage:', usage)
    },
  })

  return result.toDataStreamResponse()
}

Aggregate these in your observability stack (Datadog, Honeycomb, etc.) to correlate LLM costs with user sessions.

Summary

You now have a working Vercel AI SDK integration with n4n.ai using only environment variables — no custom providers, no hardcoded endpoints, no vendor lock-in. The variable mapping (OPENAI_API_KEY + OPENAI_BASE_URL) is the minimal contract between the SDK and any OpenAI-compatible gateway. n4n.ai adds automatic fallback, per-token metering, and 240+ models behind that same contract. Ship it.

Tagsvercel-ai-sdkn4n-aiapi-keysenvironment-variables

Written by

n4n Team

The team building n4n — a single OpenAI-compatible API in front of 240+ models, with automatic fallback, load balancing and pay-per-token metering.

More from n4n Team →

All vercel ai sdk getting started with n4n.ai posts →