Cloud Sync API is a lightweight Node.js + MySQL backend for syncing offline device data with a central server.
It provides a universal sync protocol with separate endpoints for:
- Push local changes to the server
- Pull data from server tables
- Check sync service/database status
This project is designed for multi-device systems (for example POS, inventory, or field apps) where each client can:
- Collect data locally while offline
- Push batched changes when online
- Pull fresh server state by table
Security note: table names are protected by an ALLOWED_TABLES allowlist to prevent SQL injection through dynamic table interpolation.
- Node.js
- Express
- MySQL (
mysql2/promise) - dotenv
npm installCopy sample.env to .env and set real values:
DB_HOST=localhost
DB_USER=root
DB_PASS=your_password
DB_NAME=your_database_name
ALLOWED_TABLES=sales,products,customers,item_sales,product_stocknode server.jsDefault port is 4000 unless PORT is set.
GET /healthExample response:
{
"status": "Sync API running"
}Base URL examples:
http://localhost:4000/synchttp://localhost:4000/sync/pushhttp://localhost:4000/sync/pullhttp://localhost:4000/sync/status
Endpoint:
POST /sync/pushBackward compatibility endpoint:
POST /syncDescription:
- Accepts a batch of operations (
insert,update,delete) - Executes them in a single database transaction
- Rejects operations targeting tables not listed in
ALLOWED_TABLES
Request body example:
{
"device_id": "shop_01",
"operations": [
{
"table": "sales",
"action": "insert",
"data": {
"id": "123",
"customer_id": "C001",
"total": 1000
}
},
{
"table": "product_stock",
"action": "update",
"data": {
"id": "P001",
"quantity": 20
}
}
]
}Success response example:
{
"success": true
}Common error responses:
{
"success": false,
"error": "Invalid table"
}{
"success": false,
"error": "Sync failed"
}Endpoint:
POST /sync/pullDescription:
- Pulls rows from selected allowed tables
- If
tablesis omitted, all allowed tables are queried limitdefaults to1000and is capped at5000
Request body example:
{
"tables": ["sales", "product_stock"],
"limit": 500
}Success response example:
{
"success": true,
"data": {
"sales": [],
"product_stock": []
},
"limit": 500
}Common error responses:
{
"success": false,
"error": "Invalid table"
}{
"success": false,
"error": "No tables configured"
}{
"success": false,
"error": "Pull sync failed"
}Endpoint:
GET /sync/statusDescription:
- Verifies database availability
- Returns sync service status and active allowed table list
Success response example:
{
"success": true,
"status": "ok",
"allowed_tables": [
"sales",
"products",
"customers",
"item_sales",
"product_stock"
]
}Failure response example:
{
"success": false,
"status": "error",
"error": "Database unavailable"
}device_idis accepted in push payloads and reserved for auditing/tracking workflows.- Ensure all client-side
tablevalues match names inALLOWED_TABLESexactly.