npm install openai express
# Server environment: OPENAI_API_KEY, OPENAI_BASE_URL, OPENAI_MODEL
# Integrate with an existing app and its requireUserSession middleware.
import express from 'express';
import OpenAI from 'openai';
// Project integration: implement session validation before using this route.
// Reject unauthenticated requests; enforce per-user quotas and rate limits.
// For browser cookies, also enforce CSRF/origin checks.
import { requireUserSession } from './middleware/session.mjs';
for (const key of ['OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OPENAI_MODEL']) {
if (!process.env[key]) throw new Error(`Missing ${key}`);
}
const client = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
baseURL: process.env.OPENAI_BASE_URL,
timeout: 25000,
maxRetries: 0,
});
export const aiRouter = express.Router();
// Mount with app.use(aiRouter). This is YOUR route, not a gateway endpoint.
aiRouter.post('/api/ai/chat', requireUserSession, express.json({ limit: '16kb' }), async (req, res) => {
const prompt = req.body?.prompt;
if (typeof prompt !== 'string' || !prompt.trim() || prompt.length > 4000) {
return res.status(400).json({ error: 'Invalid prompt' });
}
try {
const result = await client.chat.completions.create({
model: process.env.OPENAI_MODEL,
messages: [{ role: 'user', content: prompt }],
max_tokens: 512,
});
res.set('Cache-Control', 'no-store');
return res.json({ text: result.choices[0]?.message?.content ?? '' });
} catch {
return res.status(502).json({ error: 'AI service unavailable' });
}
});