How to Integrate Next.js for healthcare with Vercel AI SDK for startups
Connecting Next.js for healthcare with Vercel AI SDK gives you a practical pattern for building regulated AI workflows without turning your app into a pile of ad hoc prompts. The useful part is simple: Next.js handles the healthcare-facing product surface, while Vercel AI SDK can orchestrate model calls, streaming, and tool use behind the scenes for agent-driven experiences.
For startups, this combo is what lets you ship things like intake copilots, prior-auth assistants, and patient support agents with a clean separation between UI, API routes, and AI logic.
Prerequisites
- •Node.js 18+ installed
- •A Next.js app already created
- •
aiand@vercel/aidependencies installed in your project - •Access to a model provider supported by Vercel AI SDK
- •A backend service or API layer for healthcare data access
- •Environment variables configured:
- •
OPENAI_API_KEYor provider-specific key - •Any healthcare system credentials you need
- •
- •Basic familiarity with:
- •Next.js App Router
- •Route Handlers
- •Server Actions or API routes
Integration Steps
- •
Install the SDKs and create the app route structure
Start by installing the packages and creating a dedicated route for your agent endpoint.
import os import subprocess def install_deps(): subprocess.run([ "npm", "install", "ai", "@vercel/ai", "zod" ], check=True) if __name__ == "__main__": install_deps() print("Dependencies installed")In your Next.js app, create a route like:
- •
app/api/agent/route.ts - •
app/api/healthcare/patient-summary/route.ts
- •
- •
Expose healthcare data through a server-side endpoint
Keep protected data access on the server. Your agent should never call patient systems directly from the browser.
from typing import Dict, Any import requests HEALTHCARE_API_BASE = "https://api.your-health-system.example" def fetch_patient_summary(patient_id: str, token: str) -> Dict[str, Any]: url = f"{HEALTHCARE_API_BASE}/patients/{patient_id}/summary" headers = { "Authorization": f"Bearer {token}", "Accept": "application/json", } response = requests.get(url, headers=headers, timeout=15) response.raise_for_status() return response.json() if __name__ == "__main__": summary = fetch_patient_summary("patient_123", "service-token") print(summary)In Next.js, this maps to a protected route handler that your AI tool can call internally.
- •
Wire Vercel AI SDK into an agent route
Use Vercel AI SDK’s server helpers to stream responses and define tools. In practice, this is where your assistant decides when to call healthcare APIs.
from dataclasses import dataclass from typing import Any, Dict @dataclass class ToolCall: name: str args: Dict[str, Any] def build_agent_prompt(patient_context: Dict[str, Any]) -> str: return ( "You are a healthcare operations assistant. " "Use only approved tools. " f"Patient context: {patient_context}" ) def handle_tool_call(tool_call: ToolCall) -> Dict[str, Any]: if tool_call.name == "get_patient_summary": return {"status": "ok", "data": {"patient_id": tool_call.args["patient_id"]}} return {"status": "error", "message": "Unknown tool"} - •
Define a typed tool contract between the agent and healthcare service
The cleanest integration pattern is: Vercel AI SDK handles the conversation loop; your backend tool functions handle PHI-safe retrieval.
from pydantic import BaseModel, Field from typing import Literal class PatientSummaryArgs(BaseModel): patient_id: str = Field(..., min_length=1) class AgentToolRequest(BaseModel): name: Literal["get_patient_summary"] arguments: PatientSummaryArgs def validate_tool_request(payload: dict) -> AgentToolRequest: return AgentToolRequest.model_validate(payload) def get_patient_summary(patient_id: str) -> dict: # Replace with internal service call or FHIR adapter. return { "patient_id": patient_id, "last_visit": "2026-04-12", "risk_flags": ["hypertension"], } - •
Connect the route handler to model execution and tool execution
This is where Next.js receives the request and Vercel AI SDK streams the result back to the client. The key method you’ll use on the JS side is
streamText(), with tools attached to it.import json def simulate_agent_turn(user_message: str) -> dict: if "summary" in user_message.lower(): tool_request = validate_tool_request({ "name": "get_patient_summary", "arguments": {"patient_id": "patient_123"}, }) data = get_patient_summary(tool_request.arguments.patient_id) return { "response": f"Patient summary loaded for {data['patient_id']}. Last visit: {data['last_visit']}.", "tool_result": data, } return {"response": f"Received: {user_message}", "tool_result": None} if __name__ == "__main__": print(json.dumps(simulate_agent_turn("Show me the patient summary"), indent=2))
Testing the Integration
Run a simple end-to-end check against your agent endpoint logic before wiring it into the UI.
def test_agent_flow():
result = simulate_agent_turn("Get me the patient summary for follow-up")
assert result["tool_result"] is not None
assert result["tool_result"]["patient_id"] == "patient_123"
print("Integration OK")
print(result["response"])
if __name__ == "__main__":
test_agent_flow()
Expected output:
Integration OK
Patient summary loaded for patient_123. Last visit: 2026-04-12.
Real-World Use Cases
- •
Intake copilot
- •Collect symptoms, insurance details, and appointment intent in a guided chat flow.
- •Route structured outputs into your scheduling or triage backend.
- •
Prior authorization assistant
- •Pull patient history and supporting documentation from internal systems.
- •Draft payer-ready summaries using approved model prompts and tools.
- •
Care navigation agent
- •Answer questions about next steps after discharge.
- •Surface follow-up tasks like labs, referrals, and medication reminders based on system data.
The production pattern here is straightforward: keep PHI access server-side, keep tool contracts typed, and let Vercel AI SDK manage model interaction while Next.js owns delivery and auth. That separation is what keeps an agent system maintainable once real users start hitting it.
Keep learning
- •The complete AI Agents Roadmap — my full 8-step breakdown
- •Free: The AI Agent Starter Kit — PDF checklist + starter code
- •Work with me — I build AI for banks and insurance companies
By Cyprian Aarons, AI Consultant at Topiax.
Want the complete 8-step roadmap?
Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.
Get the Starter Kit