Market LiveNIFTY25,263.8-0.14%SENSEX82,192.3+0.34%Gold 24K ₹12,098.38/g down302.9Silver ₹146.46/g down5.43
InsightforGeeks
NodeJS

How to Use the OpenAI (ChatGPT) API in Node.js: A Practical Starter Guide

Sobin Mathew
28 Mar 2023
3 min read
Share:
How to Use the OpenAI (ChatGPT) API in Node.js: A Practical Starter Guide

If you want ChatGPT-style answers inside your own Node.js app, such as a support bot, a text summariser or a small internal tool, the quickest route is OpenAI's official API and its Node.js package. This guide walks through a minimal, safe setup you can extend.

What you need

  • Node.js 18 or newer
  • An OpenAI account with an API key (API usage is billed separately from a ChatGPT subscription)
  • A project folder with npm init -y already run

1. Install the official package

npm install openai

Use the official openai package rather than unofficial wrappers. Unofficial clients often scrape the ChatGPT website, break without warning and can get an account blocked.

2. Keep the API key out of your code

Put the key in an environment variable and never commit it to Git. On macOS or Linux:

export OPENAI_API_KEY="your-key-here"

In a real project, store it in a .env file that is listed in .gitignore, or in your host's secret manager.

3. Make your first request

Create ask.mjs:

import OpenAI from "openai";

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

const response = await client.chat.completions.create({
  model: "gpt-4o-mini", // choose a current model from OpenAI's model list
  messages: [
    { role: "system", content: "You are a concise assistant." },
    { role: "user", content: "Explain what an API rate limit is in two sentences." },
  ],
});

console.log(response.choices[0].message.content);

Run it with node ask.mjs. The system message sets behaviour, and the user message is the question. The answer is in choices[0].message.content.

4. Keep a conversation going

The API does not remember earlier requests. To hold a conversation, keep an array of messages and send the whole array each time, adding the assistant's reply and the next user message to it. Trim old messages once the history gets long, because you pay for every token you send.

5. Handle errors and limits

  • Wrap calls in try/catch. Network failures, invalid keys and rate limits (HTTP 429) all surface as errors.
  • On a 429 or a 5xx response, retry with exponential backoff instead of retrying instantly.
  • Set a maximum output length with max_tokens (or the newer equivalent in your SDK version) to cap cost.

6. Using it from a web app

Never call the API from browser code, because anyone could read your key. Create an Express (or Next.js) route that receives the user's text, calls OpenAI on the server and returns only the answer. Add per-user rate limiting so one visitor cannot run up your bill.

Checklist before going live

  • Key stored as a secret, never in the repository
  • Server-side calls only
  • Timeouts, retries and a spending limit configured in your OpenAI dashboard
  • A clear notice to users that answers are AI-generated and can be wrong

The official documentation at platform.openai.com lists current models, pricing and newer features such as streaming and structured output, so check it when you build further.

Tags:#openai#chatGPT#chatgpt for nodejs client#chatgpt for nodejs#chatGPT for npm #npm install chatGPT#ml#ai#gpt-3#gpt3#gpt4
Found this helpful? Share it with friends & colleagues
Share:
Sobin Mathew Verified Editorial Staff

Covering financial markets, commodity rates, and practical technology insights for India. Researched and fact-checked in accordance with our Editorial Policy.

Published on 28 March 2023General Information · Disclaimer

Recommended based on your reading interest

More in NodeJS