A Hong Kong VPS with CN2 GIA routing is an excellent location for REST API backends serving Asia-Pacific mobile apps and web clients. This guide covers production deployment of a Node.js Express API with JWT authentication, rate limiting, input validation, PM2 cluster management, and Nginx reverse proxy — the complete stack that takes a Node.js API from development to production-ready.
Step 1: Install Node.js and Dependencies
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt install -y nodejs nginx certbot python3-certbot-nginx
node --version && npm --version
# Install PM2 globally
npm install -g pm2
Step 2: Project Structure and Dependencies
mkdir -p /var/www/api && cd /var/www/api
npm init -y
npm install express helmet cors express-rate-limit \
express-validator jsonwebtoken bcryptjs \
mysql2 redis ioredis dotenv morgan winston
Application Entry Point
cat > /var/www/api/src/app.js << 'EOF' const express = require('express'); const helmet = require('helmet'); const cors = require('cors'); const morgan = require('morgan'); const rateLimit = require('express-rate-limit'); const { logger } = require('./utils/logger'); const app = express(); // Security middleware app.use(helmet()); app.use(cors({ origin: process.env.ALLOWED_ORIGINS?.split(',') || '*', methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'], allowedHeaders: ['Content-Type', 'Authorization'] })); // Body parsing app.use(express.json({ limit: '10mb' })); app.use(express.urlencoded({ extended: true })); // Request logging app.use(morgan('combined', { stream: { write: msg => logger.info(msg.trim()) }
}));
// Global rate limiting
const globalLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 500,
standardHeaders: true,
legacyHeaders: false,
message: { error: 'Too many requests, please try again later.' }
});
app.use('/api/', globalLimiter);
// Strict limiter for auth endpoints
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 10,
message: { error: 'Too many login attempts, please try again later.' }
});
// Routes
app.use('/api/v1/auth', authLimiter, require('./routes/auth'));
app.use('/api/v1/users', require('./middleware/auth'), require('./routes/users'));
app.use('/api/v1/products', require('./routes/products'));
// Health check
app.get('/health', (req, res) => {
res.json({ status: 'healthy', timestamp: new Date().toISOString() });
});
// 404 handler
app.use((req, res) => {
res.status(404).json({ error: 'Endpoint not found' });
});
// Global error handler
app.use((err, req, res, next) => {
logger.error(err.stack);
res.status(err.status || 500).json({
error: process.env.NODE_ENV === 'production'
? 'Internal server error'
: err.message
});
});
module.exports = app;
EOF
JWT Authentication Middleware
mkdir -p /var/www/api/src/middleware
cat > /var/www/api/src/middleware/auth.js << 'EOF' const jwt = require('jsonwebtoken'); module.exports = (req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'No token provided' });
}
const token = authHeader.split(' ')[1];
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
} catch (err) {
if (err.name === 'TokenExpiredError') {
return res.status(401).json({ error: 'Token expired' });
}
return res.status(401).json({ error: 'Invalid token' });
}
};
EOF
Database Connection Pool
mkdir -p /var/www/api/src/config
cat > /var/www/api/src/config/database.js << 'EOF'
const mysql = require('mysql2/promise');
const pool = mysql.createPool({
host: process.env.DB_HOST || 'localhost',
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
connectionLimit: 20,
waitForConnections: true,
queueLimit: 0,
enableKeepAlive: true,
keepAliveInitialDelay: 0
});
module.exports = { pool };
EOF
Step 3: Environment Configuration
<code">cat > /var/www/api/.env << 'EOF' NODE_ENV=production PORT=3000 DB_HOST=localhost DB_USER=apiuser DB_PASSWORD=StrongDBPassword! DB_NAME=api_production REDIS_HOST=127.0.0.1 REDIS_PORT=6379 REDIS_PASSWORD=StrongRedisPassword! JWT_SECRET=GENERATE_64_CHAR_RANDOM_SECRET_HERE JWT_EXPIRES_IN=7d ALLOWED_ORIGINS=https://yourdomain.com,https://app.yourdomain.com EOF chmod 600 /var/www/api/.env # Generate JWT secret openssl rand -hex 32
Step 4: PM2 Configuration
<code">cat > /var/www/api/ecosystem.config.js << 'EOF'
module.exports = {
apps: [{
name: 'api',
script: './src/server.js',
instances: 'max',
exec_mode: 'cluster',
watch: false,
max_memory_restart: '512M',
env_production: {
NODE_ENV: 'production',
PORT: 3000
},
error_file: '/var/log/api/error.log',
out_file: '/var/log/api/out.log',
merge_logs: true,
time: true,
kill_timeout: 5000,
listen_timeout: 3000
}]
};
EOF
mkdir -p /var/log/api
pm2 start ecosystem.config.js --env production
pm2 save
pm2 startup systemd
Step 5: Nginx Reverse Proxy with API-Specific Config
<code">cat > /etc/nginx/sites-available/api << 'EOF'
# Upstream — all PM2 cluster workers on port 3000
upstream api_backend {
server 127.0.0.1:3000;
keepalive 64;
}
# Rate limiting zones (additional to app-level limiting)
limit_req_zone $binary_remote_addr zone=api_zone:10m rate=30r/s;
limit_req_zone $binary_remote_addr zone=auth_zone:10m rate=2r/s;
server {
listen 80;
server_name api.yourdomain.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name api.yourdomain.com;
ssl_certificate /etc/letsencrypt/live/api.yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/api.yourdomain.com/privkey.pem;
# API-appropriate body size (adjust for file upload APIs)
client_max_body_size 10m;
# Remove server identification
server_tokens off;
# Security headers for APIs
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header Content-Security-Policy "default-src 'none'" always;
# CORS preflight — handle at Nginx level for performance
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin $http_origin;
add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, PATCH, OPTIONS';
add_header Access-Control-Allow-Headers 'Authorization, Content-Type';
add_header Access-Control-Max-Age 86400;
return 204;
}
# Auth endpoints — stricter rate limiting
location /api/v1/auth/ {
limit_req zone=auth_zone burst=5 nodelay;
limit_req_status 429;
proxy_pass http://api_backend;
proxy_http_version 1.1;
proxy_set_header Connection '';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# All other API endpoints
location /api/ {
limit_req zone=api_zone burst=50 nodelay;
limit_req_status 429;
proxy_pass http://api_backend;
proxy_http_version 1.1;
proxy_set_header Connection '';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 30s;
}
# Health check — no rate limiting
location /health {
proxy_pass http://api_backend;
access_log off;
}
}
EOF
ln -s /etc/nginx/sites-available/api /etc/nginx/sites-enabled/
certbot --nginx -d api.yourdomain.com
nginx -t && systemctl reload nginx
Step 6: Input Validation with express-validator
<code">const { body, validationResult } = require('express-validator');
// Validation middleware
const validateUserRegistration = [
body('email')
.isEmail().normalizeEmail()
.withMessage('Valid email required'),
body('password')
.isLength({ min: 8 })
.matches(/^(?=.*[A-Z])(?=.*[0-9])/)
.withMessage('Password must be 8+ chars with uppercase and number'),
body('name')
.trim()
.isLength({ min: 2, max: 100 })
.escape()
.withMessage('Name must be 2-100 characters'),
// Validation result checker
(req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
next();
}
];
// Use in route
router.post('/register', validateUserRegistration, registerController);
Step 7: API Response Caching with Redis
<code">// Cache middleware for GET endpoints
const Redis = require('ioredis');
const redis = new Redis({
password: process.env.REDIS_PASSWORD
});
const cacheMiddleware = (ttlSeconds) => async (req, res, next) => {
if (req.method !== 'GET') return next();
const cacheKey = `api:${req.originalUrl}`;
try {
const cached = await redis.get(cacheKey);
if (cached) {
res.setHeader('X-Cache', 'HIT');
return res.json(JSON.parse(cached));
}
} catch (err) {
// Cache error — continue without cache
}
// Intercept response to cache it
const originalJson = res.json.bind(res);
res.json = async (data) => {
try {
await redis.setex(cacheKey, ttlSeconds, JSON.stringify(data));
} catch (err) { /* ignore */ }
res.setHeader('X-Cache', 'MISS');
return originalJson(data);
};
next();
};
// Use on product listing (cache for 5 minutes)
router.get('/products', cacheMiddleware(300), getProducts);
Step 8: Structured Logging with Winston
<code">mkdir -p /var/www/api/src/utils
cat > /var/www/api/src/utils/logger.js << 'EOF'
const winston = require('winston');
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.errors({ stack: true }),
winston.format.json()
),
defaultMeta: { service: 'api' },
transports: [
new winston.transports.File({
filename: '/var/log/api/error.log',
level: 'error',
maxsize: 10485760, // 10MB
maxFiles: 5
}),
new winston.transports.File({
filename: '/var/log/api/combined.log',
maxsize: 10485760,
maxFiles: 5
})
]
});
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.colorize({ all: true })
}));
}
module.exports = { logger };
EOF
Monitoring the API
<code"># PM2 real-time monitoring
pm2 monit
# API response time check
curl -o /dev/null -s -w "Time: %{time_total}s\nHTTP: %{http_code}\n" \
https://api.yourdomain.com/health
# Check API logs for errors
pm2 logs api --lines 50 --err
# Test from mainland China latency perspective:
# Use 17ce.com or ping.pe to verify CN2 GIA performance for API endpoint
Conclusion
A production Node.js REST API on a Hong Kong VPS with PM2 cluster mode, Nginx rate limiting, JWT authentication, Redis caching, and structured logging forms a robust backend for Asia-Pacific mobile and web applications. CN2 GIA routing delivers API response times of 30–60ms TTFB for mainland Chinese app users — critical for mobile app responsiveness where each 100ms adds perceivable lag.
Deploy your API: Browse Server.HK Hong Kong VPS plans — a 4 GB plan with 4 vCPU handles PM2 cluster mode serving hundreds of concurrent API requests.