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.
- 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
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
Copy .env.example to .env and configure:
cp .env.example .envAdd your OpenAI API key:
OPENAI_API_KEY=sk-proj-your-actual-openai-api-key-here
NODE_ENV=production# Install dependencies
npm install
# Start development server
npm run dev
# Server runs on http://localhost:3001# Install Netlify CLI
npm install -g netlify-cli
# Login to Netlify
netlify login
# Deploy
netlify deploy --prod- Push code to GitHub repository
- Connect repository to Netlify
- Set environment variables in Netlify dashboard
- Deploy automatically
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"
}POST /api/openai/audio/transcriptions
POST /api/openai/audio/speech
GET /api/health
- 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
Update your React frontend to use the proxy instead of direct OpenAI calls:
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),
});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
}),
});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
The backend includes user tracking for OpenAI requests:
- Each request includes a
userfield for identification - Logs token usage for monitoring
- Ready for database integration for detailed analytics
Update the authenticateRequest middleware in routes/openai.js to verify your JWT tokens.
Extend the routes to log requests to your database for usage analytics.
Modify rate limiting rules in server.js based on your needs.
- CORS Errors: Add your frontend domain to
corsOptions.origin - Rate Limit Exceeded: Adjust limits or implement user-based limiting
- OpenAI Quota: Monitor usage in OpenAI dashboard
- Netlify Timeout: Functions have 10s timeout for free tier
| 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 |
For issues related to StudyStreak integration, check the main frontend repository documentation.