-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.js
More file actions
68 lines (55 loc) · 2.06 KB
/
Copy pathindex.js
File metadata and controls
68 lines (55 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const express = require("express");
const dotenvFlow = require("dotenv-flow");
const cors = require("cors");
const cookieParser = require("cookie-parser");
const dns = require("node:dns");
// dotenv-flow is used to manage environment variables across different environments
dotenvFlow.config();
const app = express();
const REACT_APP_URL = process.env.REACT_APP_URL;
const REACT_LOCAL_URL = process.env.REACT_LOCAL_URL;
const PORT = process.env.PORT || 5000;
const isProduction = process.env.NODE_ENV === "production";
if (!isProduction) {
// Override DNS servers to use Google's public DNS for better reliability in development
dns.setServers(["8.8.8.8", "8.8.4.4"]);
}
// CORS is configured to allow requests from the frontend url
// and to allow credentials (cookies) to be sent with requests
app.use(
cors({
origin: isProduction ? REACT_APP_URL : REACT_LOCAL_URL,
credentials: true,
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization"],
})
);
// allow us to parse cookies from the request, this is needed for session management
app.use(cookieParser());
// app will serve and receive data in a JSON format
app.use(express.json());
// trust first proxy for secure cookies in production
if (isProduction) {
app.set("trust proxy", 1);
}
// Handle routes for authentication and builds
const appRouter = require("./routes");
const { connectToMongoDB } = require("./database/connection");
const { baseRoot } = require("./controllers/authController");
// Await connection before handling any request
app.use(async (req, res, next) => {
try {
await connectToMongoDB();
next();
} catch (err) {
console.error("DB unavailable:", err.message);
return res.status(503).json({ errorMessage: "Database unavailable, try again" });
}
});
app.get("/", baseRoot);
app.use("/api", appRouter);
// Only start the HTTP server if this file was run directly with `node index.js`
if (require.main === module) {
app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));
}
module.exports = app;