Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To build an AI-powered web app with OpenAI and Node.js, send the browser’s request to a Node.js backend, call the OpenAI Responses API there using the official JavaScript SDK, then return the result to the browser. For a more dynamic interface, stream the response from your server and render text as it arrives. Keep the API key on the server; never embed it in browser code.

How do I build an AI-powered web app with OpenAI and Node.js?

The request should travel through your application server: the browser sends user input to your backend, the backend calls OpenAI, and the backend returns the generated output. This keeps the secret credential out of code delivered to users. OpenAI’s Developer quickstart identifies its official TypeScript and JavaScript SDK as suitable for server-side JavaScript environments such as Node.js, Deno, and Bun.

1. Configure the API key on the server

Create an API key in your OpenAI account and make it available to the Node.js process as an environment variable. The quickstart demonstrates exporting the key as an environment variable and using it to configure the server-side SDK client. Do not put the key in frontend JavaScript, HTML, a public repository, or a request sent directly from the browser.

2. Install the official SDK

In your Node.js project, install the package with:

npm install openai

Keep the SDK call in server-side code. A minimal Express route can accept a prompt, call the Responses API, and return the generated text:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
import express from "express";
import OpenAI from "openai";

const app = express();
app.use(express.json());

const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const model = process.env.OPENAI_MODEL;

app.post("/api/generate", async (req, res) => {
  const prompt = req.body?.prompt;

  if (typeof prompt !== "string" || prompt.trim() === "") {
    return res.status(400).json({ error: "Enter a prompt." });
  }

  if (!model) {
    return res.status(500).json({ error: "The server model is not configured." });
  }

  try {
    const response = await client.responses.create({
      model,
      input: prompt
    });

    return res.json({ text: response.output_text });
  } catch (error) {
    // Log useful operational details, but never log the API key.
    console.error("OpenAI request failed", error);
    return res.status(502).json({ error: "The AI request could not be completed." });
  }
});

app.listen(3000);

Set OPENAI_API_KEY and OPENAI_MODEL in the server’s environment. Treat the model as configuration rather than assuming a documentation example will remain available: check current model availability for your account before deployment. This example uses the Responses API’s client.responses.create(...) method; consult the current quickstart for up-to-date SDK usage.

3. Call your backend from the browser

The browser posts the user’s prompt to your application route and renders the returned text. It does not need an OpenAI credential.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
async function generate(prompt) {
  const response = await fetch("/api/generate", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ prompt })
  });

  const result = await response.json();
  if (!response.ok) {
    throw new Error(result.error || "The request failed.");
  }

  return result.text;
}

In the UI, show a pending state while the request is in progress, display the answer on success, and give the user a clear error if the backend rejects the input or the upstream request fails. Avoid returning raw server exceptions to the browser; log operational details server-side without exposing credentials.

How do I show an OpenAI response as it is generated?

A regular request returns its generated output in one response, so the UI waits for the full result before displaying it. Streaming lets the application process output while generation continues. OpenAI documents Responses API streaming over server-sent events (SSE); its streaming guide describes JavaScript events including text deltas, completion, and errors.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Stream from the Node.js route

For a streamed interface, your backend must keep the browser connection open, forward text as it arrives, and end or report failure when the stream finishes. The following illustrates the lifecycle using the SDK’s streamed Responses API. It forwards only text deltas as newline-delimited JSON; completion and error events are handled by the server rather than shown as answer text.

app.post("/api/generate-stream", async (req, res) => {
  const prompt = req.body?.prompt;

  if (typeof prompt !== "string" || prompt.trim() === "") {
    return res.status(400).json({ error: "Enter a prompt." });
  }
  if (!model) {
    return res.status(500).json({ error: "The server model is not configured." });
  }

  res.setHeader("Content-Type", "application/x-ndjson; charset=utf-8");
  res.setHeader("Cache-Control", "no-cache, no-transform");
  res.setHeader("X-Accel-Buffering", "no");

  try {
    const stream = await client.responses.create({
      model,
      input: prompt,
      stream: true
    });

    for await (const event of stream) {
      if (event.type === "response.output_text.delta") {
        res.write(JSON.stringify({ type: "delta", text: event.delta }) + "n");
      } else if (event.type === "response.completed") {
        res.write(JSON.stringify({ type: "completed" }) + "n");
      } else if (event.type === "error") {
        throw new Error("The OpenAI response stream reported an error.");
      }
    }
    res.end();
  } catch (error) {
    console.error("OpenAI stream failed", error);
    if (!res.headersSent) {
      return res.status(502).json({ error: "The AI request could not be completed." });
    }
    res.write(JSON.stringify({ type: "error", message: "The AI request could not be completed." }) + "n");
    res.end();
  }
});

This route uses newline-delimited JSON as its browser-facing transport; OpenAI’s upstream stream is SSE, and the server translates the events it needs into its own response format. In production, also handle client disconnects and ensure your hosting setup does not buffer the stream. If you choose to forward SSE directly instead, preserve event boundaries and parse event types rather than treating the stream as plain text.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Render deltas and distinguish stream states

The browser can read the response body incrementally. Append each delta to the displayed answer; treat completion as a state change, not as text. If the stream fails, stop the generating state and show an error without presenting the partial answer as complete.

async function generateStream(prompt, answerElement, setStatus) {
  setStatus("generating");
  answerElement.textContent = "";

  try {
    const response = await fetch("/api/generate-stream", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ prompt })
    });

    if (!response.ok || !response.body) {
      throw new Error("The AI request could not be started.");
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let pending = "";
    let completed = false;

    while (true) {
      const { value, done } = await reader.read();
      pending += decoder.decode(value || new Uint8Array(), { stream: !done });
      const lines = pending.split("n");
      pending = lines.pop() || "";

      for (const line of lines) {
        if (!line) continue;
        const event = JSON.parse(line);
        if (event.type === "delta") answerElement.textContent += event.text;
        if (event.type === "completed") completed = true;
        if (event.type === "error") throw new Error(event.message);
      }
      if (done) break;
    }

    if (!completed) throw new Error("The response ended before completion.");
    setStatus("complete");
  } catch (error) {
    setStatus("error");
    // Show a concise message in the UI; retain details only where appropriate.
  }
}

The states are an application design choice derived from the stream’s delta, completed, and error events: show “generating” before the first output, render partial text as deltas arrive, mark the answer complete only on completion, and provide an error state when the request or stream fails.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Should I use the Responses API or the Realtime API?

Use the API surface that matches the interaction. The API overview presents Responses for direct model requests and Realtime for low-latency sessions. Streaming a Responses API output makes text arrive incrementally, but it does not by itself turn a request into a persistent interactive session.

Need Responses API Realtime API
Typical interaction Direct model request, with either a complete response or streamed output. Low-latency session behavior.
Common fit Text generation and tool-enabled workflows; also supports multimodal input and stateful interactions. Interactive voice or audio experiences and other use cases requiring low-latency sessions.
UI pattern Wait for a result, or render incremental output from stream events. Build around an ongoing session rather than a single request/response exchange.
Implementation considerations A basic SDK request is the simpler starting point; streaming adds event and connection lifecycle handling. Choose when session behavior and latency requirements justify a session-oriented implementation.

For a conventional web form, assistant panel, or tool-enabled application, start with Responses and add streaming if showing partial text improves the experience. Choose Realtime when the product needs the low-latency session interaction described in the official documentation, such as interactive audio.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.