Skip to main content
Servers Are UpVirtual Datacenter
Virtual Datacenter
Pricing
Sign inBrowse plans
Servers Are UpVirtual Datacenter
Virtual Datacenter
Pricing
Sign inBrowse plans

Loading…

Servers Are UpEncrypted Multi-Provider VDC

Your Encrypted Multi-Provider Virtual Datacenter: run high-RAM Dallas Private Vault workloads ($0 Cloudflare HTTPS egress), connect AWS/Azure/GCP/on-prem free from 1 node, or expand to global Partner Edge nodes—unified over WireGuard, Browser Console, and 200-tool MCP.

Customer Portal & Services

Client DashboardMulti-Provider VDCMy ServersBYOC & HybridBrowser ConsoleBillingAPI Keys & MCPSupport
SLA with service creditsDallas Private VaultBYOC Free -> $99/mo6 Edge Regions (Soon)

Make room for your next idea

Explore the capacity, apps and access options that fit your workload. Check current availability and your total before you buy.

Sign up freeView Pricing

Products

  • Linux VPS
  • Windows VPS
  • Cloud & SaaS Services
  • Cloud Storage (Azure)
  • Virtual Datacenter
  • AI & Agent Hosting
  • Containers
  • Instant Apps
  • Software Platforms
  • Network builder
  • Game Servers
  • Free Game Servers
  • Pricing

Resources

  • Free Network Tools
  • 2026 Pricing Benchmark
  • Live SVG Badges
  • Latency & Speed Test
  • Guides & Tutorials
  • Documentation
  • API Reference
  • MCP Server
  • CLI & SDKs
  • OpenAPI & llms.txt
  • Use Cases
  • Free Migration
  • Uptime & Reliability
  • Datacenter
  • System Status
  • Network
  • Provider Comparisons Hub
  • Compare Providers

Company

  • About Us
  • Enterprise
  • Security Architecture
  • Trust Center
  • Blog
  • FAQ
  • Compliance
  • Startup Program
  • Open-Source Sponsorship
  • Press & Media Kit
  • Referral Program
  • Help Center
  • Contact Us
© Servers Are Up
TermsPrivacySLARefund PolicyDPAAcceptable Use
Service information
Docs
  • Documentation Hub
  • Technical Knowledge Library
    Runbooks & 187 Blueprints
  • Choose a Product
    VMs, Containers & Cloud
  • First Linux Server
    SSH, Firewall & Apps
  • Windows Server 2025
    BYOL & Remote Desktop
  • Remote Access
  • Troubleshooting
  • FAQ
  • All Product Guides
    33 Step-by-Step Guides
  • Cloud & SaaS Catalog
    139 Cloud & SaaS Offerings
  • Azure Cloud Storage
    Hot/Cool/Archive & WORM
  • Resource Manager & RBAC
    Groups, Tags & Locks
  • ARM/TF & Cloud Blueprints
    42-Type IaC & State
  • OCI Container Registry
    SBOM, CVE & Signing
  • Multi-Model Cloud DB
    JSONB, SQL & pgvector
  • Cloud Identity & ZTNA
    OIDC, SCIM & PIM
  • Per-Environment Tenant Suite
    Isolated Auth, SIEM & MCP
  • Secrets & KMS
    Secrets & Envelope Keys
  • Cloud SIEM, SOAR & DLP
    Posture & Threat Response
  • Data Lineage & DSPM
    Classification, EASM & DKE
  • API Gateway & Cloud DNS
    Edge WAF & DNS Zones
  • Serverless, Workflows & IoT
    Functions, Queues & DAGs
  • SaaS, Governance & Vault
    Budgets & Off-Host GRS
  • Linux Systems & Kernel
    SSH, UFW, sysctl & OOM
  • Self-Hosted Apps & Stacks
    Caddy, Nextcloud & Auth
  • Build Web Apps with AI
  • Next.js and React
  • TypeScript and Node.js
  • npm and Tooling
  • Data and APIs
  • Deploy and Operate
  • Tutorials
  • Infrastructure
  • Automation & Regions
  • API Overview
  • API v1 Reference
    Endpoints & 26 Scopes
  • MCP Server
    200 AI Agent Tools
  • Swagger / OpenAPI 3.1
  • API Playground
  • Versioning & Sunset
  • API Token Security
    Authentication & Tokens
  • Instances API
    Compute Resources
  • Networking API
    Networks & Ports
  • Storage API Availability
    Volumes & Backups
  • Webhooks & Events
    Event Notifications
  • Rate Limits & Best Practices
    Throttling & Retries
  • sau CLI Reference
    200 Commands (v0.3)
  • Browser Web CLI
  • SDKs
  • Infrastructure as Code
    Terraform & Ansible
  • Code Examples
  • CLI & SDK Guides
  • Security Guides
  • Security at a Glance
  • Zero Trust Architecture
  • Live Trust Center
  • Compliance
Need help?

Loading documentation...

Documentation/ai web apps

Add a first AI feature to a Next.js app

Stream a model's answer into a Next.js 16 page through your own API route, with the key kept on the server, a length limit and a Stop button.

Intermediate
25 min
Updated 2026-10-27

Deploy Ready-to-Run Infrastructure in Seconds

Linux VMs from $6/mo · Pooled Virtual Datacenters from $12/mo · Use code WELCOME20 for 20% off your first order.

Browse ServersView Pricing

Commands checked on 2026-10-27 with Next.js 16, Node.js 24, openai 7.32.

What you will have at the end

A page where a visitor types a question and reads the answer as the model writes it. The browser talks only to your own route; the route holds the provider's key on the server, refuses a question that is empty or too long, caps the length of the answer, and stops the model when the visitor presses Stop or closes the page.

Before you start

  • A Next.js 16 app with the App Router and its pages in app/, such as the example made in step 2 of Run a Next.js app as a systemd service on Ubuntu. The commands use its folder, ~/nextapp. If your app keeps its pages in src/app instead, put the two files below under src/ too.
  • An account with a model provider that offers an OpenAI-compatible API: OpenAI itself, another provider, or your own model server with a /v1/chat/completions address. You need an API key, the API's base address and a model name, written here as YOUR_API_KEY, YOUR_BASE_URL (for OpenAI, https://api.openai.com/v1) and YOUR_MODEL.

Steps

1. Install the SDK and give the server its settings

The official openai package talks to any API of that shape. The three settings go in .env.local, which Next.js reads on your machine and Git ignores.

cd ~/nextapp
npm install openai@7.32.0
printf 'AI_BASE_URL=%s\nAI_MODEL=%s\n' 'YOUR_BASE_URL' 'YOUR_MODEL' >> .env.local
printf 'AI_API_KEY=%s\n' 'YOUR_API_KEY' >> .env.local

None of the three names starts with NEXT_PUBLIC_, so none of them reaches the browser. On a server, put the same lines in the app's environment file, as in Keep secrets out of code, logs and images.

2. Write the route that asks the model

The route checks the question first, then asks for a streamed answer and passes the text on as it arrives. request.signal ends the model's work when the browser goes away, and cancel() does the same when the visitor stops reading.

mkdir -p app/api/answer
cat > app/api/answer/route.ts <<'EOF'
import OpenAI from "openai";
import type { NextRequest } from "next/server";

const MAX_QUESTION = 2000;

export async function POST(request: NextRequest) {
  const body = await request.json().catch(() => null);
  const question = typeof body?.question === "string" ? body.question.trim() : "";
  if (!question || question.length > MAX_QUESTION) {
    return Response.json({ error: `Ask a question of 1 to ${MAX_QUESTION} characters.` }, { status: 400 });
  }

  const client = new OpenAI({ apiKey: process.env.AI_API_KEY, baseURL: process.env.AI_BASE_URL });
  let stream;
  try {
    stream = await client.chat.completions.create(
      {
        model: process.env.AI_MODEL ?? "",
        messages: [
          { role: "system", content: "Answer in a few short sentences." },
          { role: "user", content: question },
        ],
        max_tokens: 1000,
        stream: true,
      },
      { signal: request.signal },
    );
  } catch (error) {
    console.error(JSON.stringify({ event: "model_request_failed", status: (error as { status?: number }).status ?? null }));
    return Response.json({ error: "The model did not answer. Try again in a moment." }, { status: 502 });
  }

  const encoder = new TextEncoder();
  const answer = new ReadableStream({
    async start(controller) {
      try {
        for await (const chunk of stream) {
          const text = chunk.choices[0]?.delta?.content;
          if (text) controller.enqueue(encoder.encode(text));
        }
      } catch (error) {
        if ((error as Error).name !== "AbortError") console.error(JSON.stringify({ event: "model_stream_failed" }));
      } finally {
        controller.close();
      }
    },
    cancel() {
      stream.controller.abort();
    },
  });
  return new Response(answer, {
    headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store", "X-Accel-Buffering": "no" },
  });
}
EOF

max_tokens caps the length, and so the cost, of every answer. X-Accel-Buffering: no tells an Nginx in front of the app to pass each part on at once.

3. Write the page that shows the answer as it arrives

The page reads the response body piece by piece and adds each piece to the answer. Stop aborts the request, which ends the model's work through the route.

mkdir -p app/ask
cat > app/ask/page.tsx <<'EOF'
"use client";

import { useRef, useState, type FormEvent } from "react";

export default function AskPage() {
  const [question, setQuestion] = useState("");
  const [answer, setAnswer] = useState("");
  const [answering, setAnswering] = useState(false);
  const request = useRef<AbortController | null>(null);

  async function ask(event: FormEvent) {
    event.preventDefault();
    request.current = new AbortController();
    setAnswer("");
    setAnswering(true);
    try {
      const response = await fetch("/api/answer", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ question }),
        signal: request.current.signal,
      });
      if (!response.ok || !response.body) {
        const body = await response.json().catch(() => ({}));
        setAnswer(body.error ?? "Something went wrong. Try again.");
        return;
      }
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      for (;;) {
        const { done, value } = await reader.read();
        if (done) break;
        setAnswer((text) => text + decoder.decode(value, { stream: true }));
      }
    } catch (error) {
      if ((error as Error).name !== "AbortError") setAnswer("The answer stopped. Try again.");
    } finally {
      setAnswering(false);
    }
  }

  return (
    <main style={{ maxWidth: 640, margin: "2rem auto", padding: "0 1rem" }}>
      <form onSubmit={ask}>
        <label htmlFor="question">Your question</label>
        <textarea id="question" value={question} maxLength={2000} rows={3}
          onChange={(event) => setQuestion(event.target.value)} style={{ display: "block", width: "100%" }} />
        <button type="submit" disabled={answering || !question.trim()}>Ask</button>
        <button type="button" onClick={() => request.current?.abort()} disabled={!answering}>Stop</button>
      </form>
      <p aria-live="polite" style={{ whiteSpace: "pre-wrap" }}>{answer}</p>
    </main>
  );
}
EOF

aria-live="polite" lets a screen reader announce the answer as it grows.

4. Start the app

npm run dev

Open http://localhost:3000/ask, ask a question, and watch the answer appear a few words at a time. Leave it running for the checks.

If the app runs on a server, reach it from your computer through an SSH tunnel, ssh -L 3000:localhost:3000 you@your-server, and open the same address there. The development server sends its scripts only to localhost, so a page opened at the server's own address shows but never answers.

Check that it works

In a second terminal, ask the route with no question, then with a real one, and time each piece of the answer:

curl -s -w ' %{http_code}\n' -H 'Content-Type: application/json' -d '{"question":""}' http://localhost:3000/api/answer
node --input-type=module -e '
const t0 = Date.now(); let parts = 0, first = 0, text = "";
const res = await fetch("http://localhost:3000/api/answer", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ question: "In one sentence, what is a hypervisor?" }) });
const reader = res.body.getReader(), decoder = new TextDecoder();
for (;;) { const { done, value } = await reader.read(); if (done) break; parts++; if (!first) first = Date.now() - t0; text += decoder.decode(value, { stream: true }); }
console.log(res.status, res.headers.get("content-type"), "parts", parts, "first after", first, "ms, all after", Date.now() - t0, "ms");
console.log(text);
'

The first line prints {"error":"Ask a question of 1 to 2000 characters."} 400. The second prints 200 text/plain; charset=utf-8, a number of parts above 1, the first part well before the last, and then the answer. A model that thinks before it answers, as reasoning models do, sends nothing for that time, so the first part can take some seconds.

What can go wrong

  • The route answers 502 and the log shows "status":401. The provider refused the key. Check AI_API_KEY in .env.local, and restart npm run dev after any change to it: Next.js reads the file when it starts.
  • The log shows "status":404. The model name or the base address is wrong. Most providers list their models at YOUR_BASE_URL/models.
  • The whole answer arrives at once, at the end. Something between the browser and the app holds the response until it is complete. Behind Nginx, the X-Accel-Buffering: no header handles it; for another proxy, turn off response buffering for this route.
  • The answer stops in the middle of a sentence. It reached max_tokens. Raise it, or ask for a shorter answer in the system message.
  • Stop does nothing. The page sends no signal: check that request.current is set before fetch starts, as in step 3.

Good practice

  • Keep the key on the server and call the provider only from your own route; never from the browser.
  • Limit what a visitor can send and what the model can write, and limit how often one visitor can ask, so one person cannot spend your budget.
  • Log that a request failed and its status, never the question or the answer, which can hold personal data.
  • Tell visitors that answers come from a model and can be wrong.
  • Keep the model's name in a setting, as here, so you can change model without changing code.

Where to go next

  • Keep secrets out of code, logs and images
  • Close the OWASP Top 10 risks in a Next.js app
  • Run a Next.js app as a systemd service on Ubuntu

Related Articles

Choose a model for your app by measuring it

Read more

Run Dify, Flowise, and Langflow workflows cleanly in Docker

Read more

Build zero-trust input and output guardrails for AI apps

Read more

Frequently Asked Questions

What does the Add a first AI feature to a Next.js app documentation guide cover?
Stream a model's answer into a Next.js 16 page through your own API route, with the key kept on the server, a length limit and a Stop button. It is rated intermediate difficulty (25 min) and applies to Servers Are Up infrastructure and workflows.
Can I manage or automate these steps through the Servers Are Up dashboard, REST API v1, or MCP server?
Yes. Every Servers Are Up server includes browser-based SSH, WebRDP, and VNC console access in the dashboard, plus programmatic control via the REST API v1 (/api/v1) and hosted Model Context Protocol server (/api/mcp/v1) using a scoped Personal Access Token.

Need hands-on help with Add a first AI feature to a Next.js app?

Every Servers Are Up virtual machine and container includes an integrated HTML5 browser-based SSH, RDP, and VNC console in your dashboard, default-off inbound firewall rules with per-IP allow-lists, and full programmatic control via REST API v1 and Model Context Protocol (MCP). Explore our Virtual Datacenter Plans or reach out to Servers Are Up Support.

Was this article helpful?

On this page

What you will have at the endBefore you startSteps1. Install the SDK and give the server its settings2. Write the route that asks the model3. Write the page that shows the answer as it arrives4. Start the appCheck that it worksWhat can go wrongGood practiceWhere to go next
Need Live Commands?

Open Aria in Wide Engineering Mode for distro-specific commands, compose tweaks, and isolated environment troubleshooting.

Knowledge Library