Step-by-Step Guide to Deploying Your Next.js and Python AI Agent Projects to Vercel

Step-by-Step Guide to Deploying Your Next.js and Python AI Agent Projects to Vercel

Z
Zahid Hasan Tonmoy
November 19, 2026
13 min read
🇧🇩 বাংলায় পড়ুন
|
0 views
Audio Overview & Podcast
~1 min quick overview
0%

Step-by-Step Guide to Deploying Your Next.js and Python AI Agent Projects to Vercel

In our previous tutorial on adding semantic search to your AI agent with Supabase pgvector, we connected both our Next.js TypeScript backend and our Python FastAPI service to a live HNSW vector index. At this point in the series, our DevPulse triage agent is functionally complete on localhost:3000 and localhost:8000—it streams tokens in 300ms, queries vector documentation, probes live GitHub issues, persists JSONB history in Supabase, and enforces sliding-window rate limits. Yet an agent that only runs on your local development machine cannot help your team or showcase your engineering skills to clients.

To deploy a full-stack Next.js and Python FastAPI AI agent to Vercel without hitting 504 GATEWAY_TIMEOUT errors, dropped streams, or leaked API keys, you configure a vercel.json blueprint with explicit function execution budgets (maxDuration: 60), validate all required server environment variables using a startup Zod check, point database connections to Supabase's transaction pooler, and verify upstream connectivity through a dedicated /api/agent/health readiness endpoint. Following this deployment workflow takes your agent from a local prototype to a globally distributed production application with automatic preview branches for every Git pull request.

Today, in Post 30 of our 62-part series, we walk through the complete step-by-step process of deploying both the Next.js full-stack workspace (from Section B) and the Python FastAPI agent service (from Posts 27–29) to Vercel.

Why Deploying an AI Agent Is Different from Deploying a Standard Website

If you have deployed a static portfolio or a standard CRUD blog to Vercel before, git push origin main usually works on the first try with default settings. Multi-step AI agents, however, stress serverless infrastructure in four distinct ways that default configurations are not tuned for:

  1. Multi-Step Execution Duration (504 GATEWAY_TIMEOUT): A standard web route finishes in 80 milliseconds. When your agent runs a 4-step reasoning loop—calling searchKnowledgeBase (OpenAI embedding + Supabase RPC), inspectLiveGitHubIssue (external GitHub REST API), and streaming a 600-token technical answer from Claude 3.5 Sonnet—the total function execution time can easily reach 12 to 25 seconds. Without explicit maxDuration configuration, serverless functions terminate mid-sentence at the default 10-second mark.
  2. Node.js Runtime vs. Edge Runtime Mismatches: Next.js Middleware (src/middleware.ts) runs on the V8 Edge Runtime, whereas heavy orchestration libraries like LangChain.js (@langchain/core) and full SDK clients rely on standard Node.js runtime APIs. Mixing those runtimes accidentally causes cryptic deployment failures.
  3. Delayed Environment Variable Crashes: In a multi-step agent, OPENAI_API_KEY might only be called when the user triggers a vector search tool, and SUPABASE_SERVICE_ROLE_KEY might only be read inside the onFinish callback after the stream completes. If you forget to paste one key into the Vercel dashboard, your build succeeds, the homepage loads, and the app crashes silently only when a user triggers that specific code path.
  4. Serverless Database Connection Spikes: Unlike a single local Node.js process, Vercel spins up separate serverless isolates under concurrent traffic. Connecting directly to PostgreSQL port 5432 instead of using connection pooling can exhaust database connection slots during traffic bursts.

3D glassmorphism visualization of a Vercel cloud deployment routing requests through an Edge shield to Next.js and Python serverless chambers connected to Supabase
3D glassmorphism visualization of a Vercel cloud deployment routing requests through an Edge shield to Next.js and Python serverless chambers connected to Supabase

The Production Vercel Deployment Architecture

Before touching the Vercel dashboard or CLI, let us look at how a user request travels through Vercel's infrastructure once our code is deployed:

mermaid graph TD A[GitHub Repository Push] --> B[Vercel Build Pipeline: tsc + Zod Env Verification] B --> C[Vercel Global Edge Network] C -->|1. Perimeter Check| D[Edge Middleware: Upstash Redis Sliding Window] D -->|Allowed Request| E[Vercel Serverless Node.js Function: /api/chat maxDuration 60s] D -->|Python Microservice Route| F[Vercel Python ASGI Function: /api/v1/agent/stream] E --> G[External Cloud Services: Claude / OpenAI + GitHub API] F --> G E --> H[Supabase Supavisor Pooler + pgvector HNSW] F --> H Architecture Flow Summary: GitHub Push → Vercel Build Pipeline → Vercel Edge Network (Upstash Rate Limiter) → Serverless Node.js and Python Functions (maxDuration: 60s) → External LLM APIs & Supabase Connection Pooler.

Zahid's Engineering Perspective: The 10-Second Cutoff and the Silent onFinish Crash

When I deployed my personal portfolio (zahidhasantonmoy.vercel.app) and web apps like LocalDrop Pro and Alur-Bosta to Vercel, the default build pipeline handled everything effortlessly. When I pushed the first multi-step version of DevPulse to a live Vercel production URL, however, two production-only bugs surfaced within the first fifteen minutes of testing.

First, whenever I asked a simple single-turn question, the stream completed in 3 seconds. But the moment I tested our 3-step compound triage prompt (searching vector docs, inspecting a live GitHub issue, and drafting a ticket), the stream froze right after the second tool card at exactly 10.0 seconds and threw an HTTP 504 GATEWAY_TIMEOUT. I had set maxDuration in one test route earlier, but forgot to enforce it across our primary /api/chat and /api/agent/sse routes in vercel.json.

Second, during that same deployment, I noticed that refreshing the browser wiped out my chat history—even though the stream itself finished without showing an error in the UI! When I opened the Vercel Functions Logs tab, I saw that I had pasted SUPABASE_URL into the Vercel Environment Variables settings with a trailing space and had forgotten to check the Preview environment checkbox for SUPABASE_SERVICE_ROLE_KEY. Because our non-blocking persistence only ran inside onFinish at the very end of the stream, the missing variable failed silently in the background after the user had already received their answer. Building the fail-fast env-check.ts validator and /api/agent/health endpoint below ensured I never shipped a misconfigured environment again.

Step 1: Writing a Fail-Fast Environment Variable Validator (env-check.ts)

Never wait until Step 3 of a live user conversation to discover that an API key is missing or malformed in your Vercel project settings. Let us create src/lib/agent/env-check.ts using Zod to validate every required server secret in one place:

`typescript // src/lib/agent/env-check.ts import 'server-only'; import { z } from 'zod';

const serverEnvSchema = z.object({ OPENAI_API_KEY: z .string() .trim() .min(20, 'OPENAI_API_KEY is missing or invalid in Vercel environment.'), ANTHROPIC_API_KEY: z .string() .trim() .min(20, 'ANTHROPIC_API_KEY is missing or invalid in Vercel environment.'), SUPABASE_URL: z .string() .trim() .url('SUPABASE_URL must be a valid HTTPS URL.'), SUPABASE_SERVICE_ROLE_KEY: z .string() .trim() .min(30, 'SUPABASE_SERVICE_ROLE_KEY is missing in Vercel environment.'), UPSTASH_REDIS_REST_URL: z .string() .trim() .url('UPSTASH_REDIS_REST_URL must be a valid HTTPS URL.') .optional(), UPSTASH_REDIS_REST_TOKEN: z.string().trim().min(10).optional(), });

export type VerifiedServerEnv = z.infer;

let cachedEnv: VerifiedServerEnv | null = null;

export function getVerifiedServerEnv(): VerifiedServerEnv { if (cachedEnv) return cachedEnv;

const parsed = serverEnvSchema.safeParse({ OPENAI_API_KEY: process.env.OPENAI_API_KEY, ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY, SUPABASE_URL: process.env.SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY: process.env.SUPABASE_SERVICE_ROLE_KEY, UPSTASH_REDIS_REST_URL: process.env.UPSTASH_REDIS_REST_URL, UPSTASH_REDIS_REST_TOKEN: process.env.UPSTASH_REDIS_REST_TOKEN, });

if (!parsed.success) { const formattedErrors = parsed.error.issues .map((issue) => ${issue.path.join('.')}: ${issue.message}) .join(' | '); throw new Error(Production Environment Validation Failed: ${formattedErrors}); }

cachedEnv = parsed.data; return cachedEnv; } `

Notice how .trim() is applied to every single secret in serverEnvSchema. When copying and pasting API keys into the Vercel dashboard UI, accidental leading or trailing whitespace is one of the most common causes of 401 Unauthorized errors in production.

Step 2: Configuring vercel.json for Next.js Streaming Routes and Python FastAPI

Create a vercel.json file in the root of your Next.js repository. This configuration file tells Vercel's build system three critical things: how long your agent routes are allowed to run (maxDuration: 60), how much memory to allocate, and which anti-buffering headers to attach to streaming paths:

json { "$schema": "https://openapi.vercel.sh/vercel.json", "framework": "nextjs", "functions": { "src/app/api/chat/route.ts": { "maxDuration": 60, "memory": 1024 }, "src/app/api/agent/sse/route.ts": { "maxDuration": 60, "memory": 1024 }, "src/app/page.tsx": { "maxDuration": 60 } }, "headers": [ { "source": "/api/(chat|agent/sse)", "headers": [ { "key": "Cache-Control", "value": "no-cache, no-transform" }, { "key": "X-Accel-Buffering", "value": "no" } ] } ] }

Also make sure each of your streaming Route Handlers (src/app/api/chat/route.ts and src/app/api/agent/sse/route.ts) explicitly exports the Node.js runtime and dynamic rendering flags at the top of the file:

typescript // Top of src/app/api/chat/route.ts export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; export const maxDuration = 60;

What about our Python FastAPI agent from Posts 28 and 29? Vercel supports deploying FastAPI ASGI applications directly as serverless Python functions! In your devpulse-python-agent repository, ensure your requirements.txt lists your exact dependencies and add this vercel.json in the Python project root:

`python

vercel.json structure for the Python FastAPI repository

Place alongside main.py and requirements.txt

{ 'version': 2, 'builds': [ { 'src': 'main.py', 'use': '@vercel/python' } ], 'routes': [ { 'src': '/(.*)', 'dest': 'main.py' } ] } `

Step 3: Creating a Post-Deploy Production Readiness Probe (/api/agent/health)

After deploying an AI agent, you should never have to guess whether Supabase pgvector, Upstash Redis, and your LLM keys are properly connected in the live environment. Let us create src/app/api/agent/health/route.ts, a lightweight readiness endpoint that verifies your environment variables and tests database connectivity in a single GET call:

`typescript // src/app/api/agent/health/route.ts import { NextResponse } from 'next/server'; import { createClient } from '@supabase/supabase-js'; import { getVerifiedServerEnv } from '@/lib/agent/env-check';

export const runtime = 'nodejs'; export const dynamic = 'force-dynamic';

export async function GET() { const startTime = Date.now();

try { const env = getVerifiedServerEnv(); const supabase = createClient(env.SUPABASE_URL, env.SUPABASE_SERVICE_ROLE_KEY, { auth: { persistSession: false, autoRefreshToken: false }, });

const { count, error: dbError } = await supabase
  .from('documentation_chunks')
  .select('*', { count: 'exact', head: true });

if (dbError) {
  return NextResponse.json(
    {
      status: 'degraded',
      stage: 'supabase_pgvector_check',
      error: dbError.message,
      latencyMs: Date.now() - startTime,
    },
    { status: 503 }
  );
}

return NextResponse.json({
  status: 'healthy',
  region: process.env.VERCEL_REGION ?? 'local-dev',
  environment: process.env.VERCEL_ENV ?? 'development',
  vectorChunksCount: count ?? 0,
  redisConfigured: Boolean(env.UPSTASH_REDIS_REST_URL),
  latencyMs: Date.now() - startTime,
});

} catch (err) { const message = err instanceof Error ? err.message : 'Health check failed'; return NextResponse.json( { status: 'unhealthy', error: message, latencyMs: Date.now() - startTime, }, { status: 500 } ); } } `

Look at what this health endpoint checks in under 50 milliseconds:

  1. It runs getVerifiedServerEnv() to confirm that OPENAI_API_KEY, ANTHROPIC_API_KEY, SUPABASE_URL, and SUPABASE_SERVICE_ROLE_KEY are present and properly formatted.
  2. It performs a fast head: true count query on documentation_chunks to verify both database connectivity and that your seed-docs.py vector chunks from Post 29 are populated (vectorChunksCount > 0).
  3. It reports the active VERCEL_REGION (such as iad1 or sin1) so you can verify your compute region matches your Supabase database region.

Step 4: Step-by-Step Deployment via Vercel CLI and GitHub

Follow these exact five steps to ship your project cleanly from your terminal:

`bash

1. Run a local production build first to catch TypeScript or RSC boundary errors

npm run build

2. Install the Vercel CLI globally and link your project

npm install -g vercel vercel link

3. Add your production secrets (or paste them in Project Settings -> Environment Variables)

vercel env add OPENAI_API_KEY production vercel env add ANTHROPIC_API_KEY production vercel env add SUPABASE_URL production vercel env add SUPABASE_SERVICE_ROLE_KEY production vercel env add UPSTASH_REDIS_REST_URL production vercel env add UPSTASH_REDIS_REST_TOKEN production

4. Deploy to production

vercel --prod

5. Verify the live deployment health endpoint

curl -s https://your-project-name.vercel.app/api/agent/health `

Aligning Your Vercel Function Region with Supabase and Upstash

One critical optimization inside the Vercel Dashboard (Settings → Functions → Function Region) is matching your serverless execution region to your Supabase database region. Because a multi-step agent turn makes multiple roundtrips (Edge Middleware → Redis → Next.js Function → Supabase History Load → LLM → Supabase pgvector RPC → onFinish Insert), placing your Vercel functions in Washington D.C. (iad1) while your Supabase database sits in Singapore (ap-southeast-1) adds 250ms of cross-ocean latency to every single database call! Setting both Vercel Functions and Supabase to the same region (for example, Singapore sin1 for South/Southeast Asia traffic or iad1 for US East) cuts database roundtrip times from 250ms down to 4ms.

Dark frosted glass deployment diagnostic console displaying emerald health check rings, colocated region nodes, and a 60-second execution gauge
Dark frosted glass deployment diagnostic console displaying emerald health check rings, colocated region nodes, and a 60-second execution gauge

Common Mistakes When Deploying AI Agents to Vercel

Before sharing your live production link with users or clients, audit your deployment against these 4 common pitfalls:

  1. Skipping npm run build Locally Before Pushing to GitHub: npm run dev compiles pages lazily on demand and is forgiving of loose types. npm run build runs full TypeScript type checking (tsc) and enforces 'server-only' boundaries across every route. Always run npm run build locally before pushing.
  2. Setting export const runtime = 'edge' on Heavy Agent Orchestration Routes: While the Edge runtime is perfect for src/middleware.ts rate limiting, setting runtime = 'edge' on routes that use LangChain.js, Node.js crypto or fs utilities, or heavy SDKs causes build failures or strict code-size limit errors. Keep /api/chat on runtime = 'nodejs'.
  3. Forgetting to Enable Secrets for Both Production and Preview Environments: When you add an environment variable in the Vercel dashboard and only check the Production box, every pull-request Preview URL (*-git-feature.vercel.app) will deploy without that secret and crash during testing. Check both Production and Preview (or use separate staging API keys for Preview).
  4. Mismatched Compute and Database Regions: Leaving Vercel Functions on the default US East (iad1) region when your Supabase PostgreSQL instance and Upstash Redis store are hosted in Singapore or Frankfurt adds ratusan milliseconds of avoidable network overhead on every tool call.

Frequently Asked Questions

Can I deploy a multi-step AI agent on the free Vercel Hobby plan, or do I need Vercel Pro?

Yes, you can deploy and run this entire Next.js AI agent on the free Vercel Hobby plan! Vercel updated the Hobby plan limits to allow configuring maxDuration up to 60 seconds for Node.js Serverless Functions, which is plenty of time for a 5-step tool-calling agent loop. If you upgrade to Vercel Pro later, you can extend maxDuration up to 300 seconds (or 800 seconds with Fluid Compute).

Should I deploy my Python FastAPI agent on Vercel too, or host it on a separate VPS?

If your Python FastAPI agent primarily orchestrates LLM API calls, Pydantic validation, and Supabase pgvector RPCs that finish within 60 seconds, deploying it on Vercel as a Python Serverless Function works well with zero server maintenance. However, if your Python agent runs local PyTorch models, headless Playwright browsers, or 10-minute background jobs, you should host it in a Docker container on your own VPS—which is the exact setup we will build in the very next post (Post 31)!

Why did my Server Action (approveAndPersistTicket) time out until I added src/app/page.tsx to vercel.json?

In the Next.js App Router, 'use server' Server Actions invoked from a page component execute inside the serverless function bundle associated with that page segment (src/app/page.tsx). Including src/app/page.tsx alongside /api/chat/route.ts in vercel.json's functions map ensures both your Route Handlers and your Server Actions receive the full 60-second execution budget.

🟢 Available for Freelance & Contract Work

Need a High-Performance Web App or Custom AI Solution?

I help founders, businesses, and engineering teams build lightning-fast web applications, resilient backend architectures, and intelligent AI workflows. Have an idea in mind? Let’s bring it to life.

Fast MVP Launch (2–4 weeks)
AI Agent & LLM API Integration
100/100 Core Web Vitals & SEO
Production-Ready Clean Architecture

Found this article helpful?

Give some claps to support more in-depth engineering logs!

0 views
Z

Zahid Hasan Tonmoy

Author & Developer

MERN Full Stack Developer & AI Agent Developer based in Dhaka, Bangladesh. Writing about web development, React, PostgreSQL and my learning journey.

Related Articles

Stay Updated

Subscribe to get insights on full-stack architecture, AI agent engineering, and web development.