Back to roadmaps openai Course

Installing and Initializing the OpenAI Node.js SDK

Let us install the official OpenAI library and write our first request connection test.


1. Installing the SDK Library

In your project root directory, install the official package:

# Install the OpenAI Node.js SDK package
npm install openai

2. Configuration Setup

Save your secret key to your .env configuration file:

# OpenAI credentials config
OPENAI_API_KEY="sk-proj-your-secret-api-key-string"

3. Initializing the API Client

Create a client module (for example, src/lib/openai.ts):

// src/lib/openai.ts
import OpenAI from "openai";

const apiKey = process.env.OPENAI_API_KEY;

if (!apiKey) {
  throw new Error("Missing OPENAI_API_KEY environment configuration");
}

// Export configured client instance
export const openai = new OpenAI({
  apiKey: apiKey,
  // If you route requests via a custom proxy server, configure:
  // baseURL: "https://your-custom-gateway-proxy.com/v1",
});

4. Connection Test Script

Write a quick test runner to verify that the client connects and authenticates:

import { openai } from "./src/lib/openai";

async function runTest() {
  try {
    const response = await openai.models.list();
    console.log("Connection successful! Available models count:", response.data.length);
  } catch (err: any) {
    console.error("Connection failed. Check your API key:", err.message);
  }
}

runTest();
Published on Last updated: