chore: document and standardize hosts/ports across apps

This commit is contained in:
2025-09-10 01:21:15 +05:30
parent 701ff61214
commit 70cfff90ce
13 changed files with 218 additions and 42 deletions

View File

@@ -1,6 +1,7 @@
HOST=localhost
NODE_ENV="development"
HOST=0.0.0.0
PORT=5000
FRONTEND_URL=http://localhost:3000
FRONTEND_URLS=http://localhost:3000,http://192.168.1.8:3000
JWT_SECRET = 'dentalsecret'
DB_HOST=localhost
DB_USER=postgres

View File

@@ -9,7 +9,11 @@ import dotenv from "dotenv";
import { startBackupCron } from "./cron/backupCheck";
dotenv.config();
const FRONTEND_URL = process.env.FRONTEND_URL;
const NODE_ENV = (
process.env.NODE_ENV ||
process.env.ENV ||
"development"
).toLowerCase();
const app = express();
@@ -17,9 +21,48 @@ app.use(express.json());
app.use(express.urlencoded({ extended: true })); // For form data
app.use(apiLogger);
// --- CORS handling (flexible for dev and strict for prod) ---
/**
* FRONTEND_URLS env value: comma-separated allowed origins
* Example: FRONTEND_URLS=http://localhost:3000,http://192.168.1.8:3000
*/
const rawFrontendUrls =
process.env.FRONTEND_URLS || process.env.FRONTEND_URL || "";
const FRONTEND_URLS = rawFrontendUrls
.split(",")
.map((s) => s.trim())
.filter(Boolean);
// helper to see if origin is allowed
function isOriginAllowed(origin?: string | null) {
if (!origin) return true; // allow non-browser clients (curl/postman)
if (NODE_ENV !== "production") {
// Dev mode: allow localhost origins automatically
if (
origin.startsWith("http://localhost") ||
origin.startsWith("http://127.0.0.1")
)
return true;
// allow explicit FRONTEND_URLS if provided
if (FRONTEND_URLS.includes(origin)) return true;
// optionally allow the server's LAN IP if FRONTEND_LAN_IP is provided
const lanIp = process.env.FRONTEND_LAN_IP;
if (lanIp && origin.startsWith(`http://${lanIp}`)) return true;
// fallback: deny if not matched
return false;
}
// production: strict whitelist — must match configured FRONTEND_URLS exactly
return FRONTEND_URLS.includes(origin);
}
app.use(
cors({
origin: FRONTEND_URL,
origin: (origin, cb) => {
if (isOriginAllowed(origin)) return cb(null, true);
cb(new Error(`CORS: Origin ${origin} not allowed`));
},
methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization"],
credentials: true,

View File

@@ -3,11 +3,18 @@ import dotenv from "dotenv";
dotenv.config();
const HOST = process.env.HOST;
const PORT = process.env.PORT;
const NODE_ENV = (
process.env.NODE_ENV ||
process.env.ENV ||
"development"
).toLowerCase();
const HOST = process.env.HOST || "0.0.0.0";
const PORT = Number(process.env.PORT) || 5000;
const server = app.listen(PORT, () => {
console.log(`✅ Server running at http://${HOST}:${PORT}`);
const server = app.listen(PORT, HOST, () => {
console.log(
`✅ Server running in ${NODE_ENV} mode at http://${HOST}:${PORT}`
);
});
// Handle startup errors