Skip to content

Repository files navigation

OpenAI Proxy Backend

A secure Node.js backend that acts as a proxy for OpenAI API calls, designed to prevent API key exposure in frontend applications. Deployable on Netlify Functions.

πŸš€ Features

  • Secure API Key Management: Keeps OpenAI API keys server-side
  • Rate Limiting: Prevents abuse with configurable rate limits
  • CORS Protection: Configured for StudyStreak frontend domains
  • Authentication Ready: Middleware for token-based authentication
  • Multiple Endpoints: Chat completions, audio transcription, text-to-speech
  • Netlify Functions Compatible: Easy deployment on Netlify
  • Error Handling: Comprehensive error handling and logging

πŸ“ Project Structure

openai-proxy-backend/
β”œβ”€β”€ server.js                 # Express server for local development
β”œβ”€β”€ routes/
β”‚   └── openai.js             # OpenAI API routes
β”œβ”€β”€ netlify/
β”‚   └── functions/
β”‚       └── api.js            # Netlify Functions entry point
β”œβ”€β”€ package.json
β”œβ”€β”€ netlify.toml              # Netlify configuration
β”œβ”€β”€ .env.example              # Environment variables template
└── README.md

πŸ› οΈ Setup Instructions

1. Environment Variables

Copy .env.example to .env and configure:

cp .env.example .env

Add your OpenAI API key:

OPENAI_API_KEY=sk-proj-your-actual-openai-api-key-here
NODE_ENV=production

2. Local Development

# Install dependencies
npm install

# Start development server
npm run dev

# Server runs on http://localhost:3001

3. Deploy to Netlify

Option A: Netlify CLI (Recommended)

# Install Netlify CLI
npm install -g netlify-cli

# Login to Netlify
netlify login

# Deploy
netlify deploy --prod

Option B: Git Integration

  1. Push code to GitHub repository
  2. Connect repository to Netlify
  3. Set environment variables in Netlify dashboard
  4. Deploy automatically

πŸ”§ API Endpoints

Chat Completions (AI Assessment)

POST /api/openai/chat/completions

Headers:

Authorization: Bearer your-jwt-token
Content-Type: application/json

Body:

{
  "model": "gpt-3.5-turbo",
  "messages": [
    {
      "role": "system",
      "content": "You are an IELTS writing assessor..."
    },
    {
      "role": "user",
      "content": "Please assess this essay..."
    }
  ],
  "temperature": 0.7,
  "max_tokens": 1000,
  "user": "student_user_id"
}

Audio Transcription (Speaking Assessment)

POST /api/openai/audio/transcriptions

Text-to-Speech

POST /api/openai/audio/speech

Health Check

GET /api/health

πŸ” Security Features

  • Rate Limiting: 100 requests per 15 minutes per IP
  • CORS Protection: Only allowed domains can access
  • Helmet: Security headers protection
  • Authentication Middleware: Ready for JWT token verification
  • Input Validation: Validates all incoming requests
  • Error Sanitization: Prevents sensitive data leakage

πŸ”„ Frontend Integration

Update your React frontend to use the proxy instead of direct OpenAI calls:

Before (Exposed API Key):

const response = await fetch("https://api.openai.com/v1/chat/completions", {
  headers: {
    Authorization: `Bearer ${process.env.REACT_APP_OPEN_AI_SECRET}`, // EXPOSED!
    "Content-Type": "application/json",
  },
  method: "POST",
  body: JSON.stringify(gptBody),
});

After (Secure Proxy):

const response = await fetch("https://your-netlify-app.netlify.app/api/openai/chat/completions", {
  headers: {
    Authorization: `Bearer ${authData.accessToken}`, // Your auth token
    "Content-Type": "application/json",
  },
  method: "POST",
  body: JSON.stringify({
    ...gptBody,
    user: authData.userId // For tracking
  }),
});

πŸš€ Deployment URLs

After deploying to Netlify, your API will be available at:

https://your-app-name.netlify.app/api/openai/chat/completions
https://your-app-name.netlify.app/api/health

πŸ“Š Usage Tracking

The backend includes user tracking for OpenAI requests:

  • Each request includes a user field for identification
  • Logs token usage for monitoring
  • Ready for database integration for detailed analytics

πŸ”§ Customization

Add Authentication

Update the authenticateRequest middleware in routes/openai.js to verify your JWT tokens.

Add Database Logging

Extend the routes to log requests to your database for usage analytics.

Custom Rate Limits

Modify rate limiting rules in server.js based on your needs.

πŸ› Troubleshooting

Common Issues:

  1. CORS Errors: Add your frontend domain to corsOptions.origin
  2. Rate Limit Exceeded: Adjust limits or implement user-based limiting
  3. OpenAI Quota: Monitor usage in OpenAI dashboard
  4. Netlify Timeout: Functions have 10s timeout for free tier

πŸ“ Environment Variables

Variable Description Required
OPENAI_API_KEY Your OpenAI API key Yes
NODE_ENV Environment (development/production) No
JWT_SECRET JWT secret for authentication Optional
ALLOWED_ORIGINS Comma-separated CORS origins Optional

πŸ“ž Support

For issues related to StudyStreak integration, check the main frontend repository documentation.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages