Learn how to build a ChatGPT-inspired application with Aurelia 2, Node.js, and the OpenAI GPT-4o API.
This tutorial will guide you through creating a ChatGPT-like application using Aurelia 2 for the frontend, Node.js + Express for the backend, and OpenAI's GPT-4o API to generate responses. We'll demonstrate modern Aurelia 2 patterns, proper dependency injection, TypeScript types, error handling, and responsive design.
This application serves as an excellent foundation for building more complex AI-powered chat interfaces. You can extend it with additional features like conversation persistence, user authentication, file uploads, or integration with other AI services.
Next Steps:
Deploy your application to production using services like Vercel, Netlify, or AWS
Add user authentication and conversation history
Implement streaming responses for real-time text generation
Add support for image uploads and multimodal conversations
Create custom AI personalities or specialized assistants
const express = require('express');
const { OpenAI } = require('openai');
const cors = require('cors');
const bodyParser = require('body-parser');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 3001;
// Middleware
app.use(cors());
app.use(bodyParser.json({ limit: '10mb' }));
app.use(express.static('public'));
// OpenAI client initialization
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
// Validate environment variables
if (!process.env.OPENAI_API_KEY) {
console.error('Missing OPENAI_API_KEY environment variable');
process.exit(1);
}
// Chat endpoint with conversation history support
app.post('/api/chat', async (req, res) => {
const { messages, model = 'gpt-4o-mini' } = req.body;
// Validate request
if (!messages || !Array.isArray(messages) || messages.length === 0) {
return res.status(400).json({
error: 'Invalid request: messages array is required'
});
}
try {
const completion = await openai.chat.completions.create({
model,
messages,
max_tokens: 1000,
temperature: 0.7,
stream: false,
});
const reply = completion.choices[0]?.message?.content;
if (!reply) {
throw new Error('No response generated');
}
res.json({
reply,
usage: completion.usage,
model: completion.model
});
} catch (error) {
console.error('OpenAI API Error:', error);
if (error.status === 401) {
res.status(401).json({ error: 'Invalid API key' });
} else if (error.status === 429) {
res.status(429).json({ error: 'Rate limit exceeded. Please try again later.' });
} else if (error.status === 402) {
res.status(402).json({ error: 'Insufficient credits. Please check your OpenAI account.' });
} else {
res.status(500).json({ error: 'An error occurred while processing your request' });
}
}
});
// Health check endpoint
app.get('/api/health', (req, res) => {
res.json({ status: 'OK', timestamp: new Date().toISOString() });
});
app.listen(port, () => {
console.log(`🚀 Server is running on http://localhost:${port}`);
console.log(`📡 API endpoint: http://localhost:${port}/api/chat`);
});
# Required: Your OpenAI API key
OPENAI_API_KEY=your_openai_api_key_here
# Optional: Server port (defaults to 3001)
PORT=3001
# Optional: Node environment
NODE_ENV=development
{
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js",
"test": "echo \"Error: no test specified\" && exit 1"
}
}