Apa itu API Proxy?
API Proxy adalah fitur yang memungkinkan Node.js server meneruskan request ke PHP API controllers. Ini memberikan satu pintu masuk (gateway) untuk semua API, baik yang diproses oleh Node.js maupun PHP.
- Satu endpoint untuk semua API (Node.js + PHP)
- Mudah tambahkan middleware (auth, rate limit, caching)
- Scalable untuk microservices
- CORS handling terpusat
Cara Kerja Proxy
Request ke Node.js dengan prefix /nx/ akan otomatis di-forward ke PHP API dengan prefix /api/:
Client Request:
http://localhost:3000/nx/test
↓
Node.js Proxy:
Rewrite: /nx/test → /api/test
↓
PHP backend (sesuai PHP_SERVER / .nxdom-php-port), contoh built-in:
http://127.0.0.1:8000/api/test
↓
PHP Controller:
controllers/Api/TestController.php
↓
Response:
JSON data kembali ke clientEndpoint Mapping
| Client Request | Node.js Proxy | PHP Server | Controller |
|---|---|---|---|
GET /nx/test |
→ | GET /api/test |
TestController.php |
POST /nx/auth/login |
→ | POST /api/auth/login |
GoogleAuthController.php |
GET /nx/docs |
→ | GET /api/docs |
DocsController.php |
GET /nx/user/profile |
→ | GET /api/user/profile |
UserController.php |
Konfigurasi Proxy
Proxy dikonfigurasi di server.js:
const { createProxyMiddleware } = require('http-proxy-middleware');
// PHP_SERVER = resolvePhpServer(): .nxdom-php-port (opsional) → env PHP_SERVER → default :8000
// NXDOM_IGNORE_PHP_PORT_FILE=1 mengabaikan file port
const PHP_SERVER = resolvePhpServer();
app.use('/nx', createProxyMiddleware({
target: PHP_SERVER,
changeOrigin: true,
pathRewrite: { '^/nx': '/api' },
onProxyReq: (proxyReq, req, res) => { /* body JSON untuk PUT/POST */ }
}));Environment & CLI Windows
nxdom node (bat) menyetel NXDOM_IGNORE_PHP_PORT_FILE=1 dan PHP_SERVER=http://127.0.0.1. nxdom node dev memakai PHP_SERVER=http://127.0.0.1:8080. Tanpa itu, urutan sama seperti di resolvePhpServer().
Variabel PHP_SERVER dan NXDOM_IGNORE_PHP_PORT_FILE dibaca dari environment proses (PowerShell, nxdom.bat, PM2, systemd). File .env tidak dimuat otomatis oleh server.js bawaan — export/set env sebelum menjalankan Node jika tidak memakai nxdom node.
# Target origin PHP untuk proxy /nx → /api
PHP_SERVER=http://127.0.0.1:8000
# Apache di port 80
# PHP_SERVER=http://127.0.0.1
# Abaikan .nxdom-php-port (paksa pakai PHP_SERVER atau default)
NXDOM_IGNORE_PHP_PORT_FILE=1Contoh Penggunaan
Akses Langsung vs Proxy
1. Akses Langsung ke PHP
// Request langsung ke PHP server
fetch('http://localhost/api/test')
.then(res => res.json())
.then(data => console.log(data));Karakteristik:
- ✅ Langsung ke PHP, tidak melalui Node.js
- ✅ Lebih cepat (tidak ada overhead proxy)
- ❌ Tidak ada middleware Node.js (auth, rate limit, dll)
- ❌ Tidak ada centralized logging
2. Akses via Node.js Proxy
// Request via Node.js proxy ke PHP
fetch('http://localhost:3000/nx/test')
.then(res => res.json())
.then(data => console.log(data));Karakteristik:
- ✅ Melalui Node.js, lalu di-forward ke PHP
- ✅ Dapat tambahkan middleware (auth, rate limit, caching)
- ✅ Centralized logging & monitoring
- ✅ CORS handling otomatis
- ⚠️ Sedikit overhead (proxy layer)
Kapan Menggunakan Proxy?
| Scenario | Rekomendasi | Alasan |
|---|---|---|
| API publik untuk client apps | ✅ Gunakan Proxy | Perlu auth, rate limit, CORS |
| Internal API antar services | ⚠️ Langsung ke PHP | Lebih cepat, tidak perlu middleware |
| Mobile app API | ✅ Gunakan Proxy | Centralized logging & monitoring |
| Admin dashboard internal | ⚠️ Langsung ke PHP | Overhead tidak perlu |
| Third-party integrations | ✅ Gunakan Proxy | Rate limiting & error handling |
Contoh Lengkap
GET Request
// Test endpoint via proxy
async function testProxy() {
try {
const response = await fetch('http://localhost:3000/nx/test');
const data = await response.json();
console.log('Success:', data);
} catch (error) {
console.error('Error:', error);
}
}
testProxy();POST Request
// Login via proxy
async function login(email, password) {
const response = await fetch('http://localhost:3000/nx/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ email, password })
});
return await response.json();
}
login('user@example.com', 'password123')
.then(data => console.log('Login:', data));Dengan Headers
// Request dengan authentication token
async function getUserProfile(token) {
const response = await fetch('http://localhost:3000/nx/user/profile', {
headers: {
'Authorization': `Bearer $`,
'Content-Type': 'application/json'
}
});
return await response.json();
}
getUserProfile('your-jwt-token')
.then(data => console.log('Profile:', data));Menambahkan Middleware
Anda dapat menambahkan middleware di server.js sebelum proxy:
Rate Limiting
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 menit
max: 100 // max 100 requests per window
});
// Apply ke semua /nx/* routes
app.use('/nx', limiter);Authentication
// Middleware untuk check JWT token
function authenticateToken(req, res, next) {
const token = req.headers['authorization'];
if (!token) {
return res.status(401).json({ error: 'No token provided' });
}
// Verify token logic here
next();
}
// Apply ke routes yang perlu auth
app.use('/nx/user', authenticateToken);Request Logging
const morgan = require('morgan');
// Log semua requests
app.use(morgan('combined'));
// Custom logging
app.use((req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next();
});Perbedaan Akses Langsung vs Proxy
Akses Langsung ke PHP
Browser/Client
↓
http://localhost/api/test
↓
PHP Server (Apache/Nginx)
↓
.htaccess / routing
↓
controllers/Api/TestController.php
↓
Response JSONKapan menggunakan:
- Internal API calls (server-side)
- Admin dashboard (tidak perlu middleware)
- Performance critical (minimal latency)
Akses via Node.js Proxy
Browser/Client
↓
http://localhost:3000/nx/test
↓
Node.js Server (Express)
↓
Middleware (CORS, Auth, Rate Limit, etc)
↓
http-proxy-middleware
↓
Rewrite: /nx/test → /api/test
↓
http://localhost/api/test
↓
PHP Server
↓
controllers/Api/TestController.php
↓
Response JSON (via Node.js)
↓
ClientKapan menggunakan:
- Public API untuk mobile/web apps
- Third-party integrations
- Perlu authentication/authorization
- Perlu rate limiting
- Perlu centralized logging
- Cross-origin requests (CORS)
Konfigurasi lanjutan
Mengubah Prefix
Default prefix adalah /nx, tapi bisa diubah:
// Ubah dari /nx ke /api/php
app.use('/api/php', createProxyMiddleware({
target: PHP_SERVER,
changeOrigin: true,
pathRewrite: {
'^/api/php': '/api' // /api/php/test → /api/test
}
}));Multiple PHP Servers
Proxy ke beberapa PHP server berbeda:
// Server 1: Main API
app.use('/nx/v1', createProxyMiddleware({
target: 'http://localhost:8000',
changeOrigin: true,
pathRewrite: { '^/nx/v1': '/api' }
}));
// Server 2: Legacy API
app.use('/nx/legacy', createProxyMiddleware({
target: 'http://localhost:9000',
changeOrigin: true,
pathRewrite: { '^/nx/legacy': '/api' }
}));Custom Headers
app.use('/nx', createProxyMiddleware({
target: PHP_SERVER,
changeOrigin: true,
pathRewrite: { '^/nx': '/api' },
onProxyReq: (proxyReq, req, res) => {
// Tambahkan custom header
proxyReq.setHeader('X-Proxied-By', 'NexaUI-Node');
proxyReq.setHeader('X-Request-ID', generateRequestId());
}
}));Error Handling
PHP Server Offline
Error: connect ECONNREFUSED 127.0.0.1:80Solusi:
- PHP built-in + Node:
nxdom dev(disarankan). - Apache / PHP di :80: di Windows jalankan
nxdom node(proxy kehttp://127.0.0.1). - PHP di :8080:
nxdom node dev(Windows). - Selaraskan target dengan log saat Node start (
PHP (proxy /nx→): …) ataucurlke origin yang sama +/api/test.
CORS Error
Access to fetch at 'http://localhost:3000/nx/test' from origin
'http://localhost' has been blocked by CORS policySolusi: CORS sudah enabled di server.js dengan app.use(cors());
Jika masih error, tambahkan konfigurasi CORS spesifik:
const cors = require('cors');
app.use(cors({
origin: ['http://localhost', 'http://localhost:8000'],
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE']
}));Testing Proxy
Menggunakan curl
# GET request
curl http://localhost:3000/nx/test
# POST request
curl -X POST http://localhost:3000/nx/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"user@example.com","password":"pass123"}'
# Dengan header
curl http://localhost:3000/nx/user/profile \
-H "Authorization: Bearer your-token-here"Menggunakan Browser
Buka file test-non-blocking.html yang sudah disediakan untuk test interaktif:
http://localhost/test-non-blocking.htmlFile ini menyediakan buttons untuk test:
- Health Check (
/api/health) - Fast API (
/api/fast) - Slow API (
/api/slow) - PHP Proxy (
/nx/test) - Concurrent Requests (test non-blocking)
Performance Tips
- ✅ Gunakan
changeOrigin: trueuntuk virtual hosts - ✅ Enable compression di Node.js untuk response besar
- ✅ Implementasi caching untuk API yang jarang berubah
- ✅ Gunakan connection pooling untuk database
- ✅ Monitor dengan PM2 di production
Next Steps
- Pelajari Static Files untuk serving images/assets
- Setup Production Deployment dengan PM2
- Tambahkan authentication middleware
- Implementasi rate limiting
- Setup monitoring & logging