Header Ads

Learn how to integrate ChatGPT API with Angular and Node.js using a secure backend, OpenAI API key protection, Angular service, and chat UI.

 How to Integrate ChatGPT API with Angular and Node.js: A Complete Step-by-Step Guide

Integrating ChatGPT into your Angular application opens up many possibilities, including AI-powered chatbots, smart search, intelligent assistants, and content generation tools. In this step-by-step tutorial, you will learn how to connect Angular with the OpenAI ChatGPT API using a secure Node.js backend.

This guide uses a backend server because your OpenAI API key should never be placed directly inside Angular code. Angular code runs in the browser, which means users can inspect it. A Node.js backend keeps your API key private and sends only the final AI response back to Angular.


Prerequisites

Before starting, make sure you have the following ready:

  • Angular installed on your system
  • Node.js and npm installed
  • An OpenAI API key from platform.openai.com
  • Basic knowledge of Angular components and services


Step 1: Create a New Angular Project

ng new angular-chatgpt

cd angular-chatgpt

ng serve

After running the project, open http://localhost:4200 in your browser and confirm that the Angular application is working.


Step 2: Create a Node.js Backend

Now create a backend folder. This backend will receive messages from Angular and call the OpenAI API securely.

mkdir backend

cd backend

npm init -y

npm install express cors dotenv openai


Step 3: Store the OpenAI API Key Securely

Create a .env file inside the backend folder and add your API key there. Do not add this file to GitHub.

OPENAI_API_KEY=YOUR_OPENAI_API_KEY_HERE

PORT=3000


Step 4: Create the Express API

Create a server.js file inside the backend folder and add the following code.

import express from 'express';

import cors from 'cors';

import dotenv from 'dotenv';

import OpenAI from 'openai';


dotenv.config();

const app = express();

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


app.use(cors({ origin: 'http://localhost:4200' }));

app.use(express.json());


app.post('/api/chat', async (req, res) => {

  try {

    const { message } = req.body;

    const response = await client.responses.create({

      model: 'gpt-4.1-mini',

      input: message

    });

    res.json({ reply: response.output_text });

  } catch (error) {

    res.status(500).json({ error: 'Unable to generate response' });

  }

});


app.listen(3000, () => console.log('Server running on port 3000'));


Step 5: Create the Angular Chat Service

import { Injectable } from '@angular/core';

import { HttpClient } from '@angular/common/http';


@Injectable({ providedIn: 'root' })

export class ChatService {

  private apiUrl = 'http://localhost:3000/api/chat';

  constructor(private http: HttpClient) {}

  sendMessage(message: string) {

    return this.http.post<{ reply: string }>(this.apiUrl, { message });

  }

}


Key Capabilities of This Integration

  • Secure OpenAI API key handling through Node.js
  • Reusable Angular service for chat requests
  • Simple structure for Ionic Angular apps
  • Easy extension for chat history and streaming responses


Conclusion

Integrating ChatGPT with Angular is simple when you use the correct architecture. Angular should handle the user interface, while Node.js should protect the OpenAI API key and communicate with the OpenAI API.

From here, you can improve the project by adding conversation history, user login, streaming responses, rate limiting, and deployment support. You can also use the same backend approach in Ionic mobile applications.

Post a Comment

0 Comments