1 import express, { type Request, Response, NextFunction } from "express";
2 import { registerRoutes } from "./routes";
3 import { setupVite, serveStatic, log } from "./vite";
4 import { seedDatabase } from "./seed-data";
5 import { seedGuides } from "./seed-guides";
6 import { setupAuth } from "./auth";
7
8 const app = express();
9 app.use(express.json());
10 app.use(express.urlencoded({ extended: false }));
11 app.use("/uploads", express.static("uploads"));
12
13 setupAuth(app);
14
15 app.use((req, res, next) => {
16 const start = Date.now();
17 const path = req.path;
18 let capturedJsonResponse: Record<string, any> | undefined = undefined;
19
20 const originalResJson = res.json;
21 res.json = function (bodyJson, ...args) {
22 capturedJsonResponse = bodyJson;
23 return originalResJson.apply(res, [bodyJson, ...args]);
24 };
25
26 res.on("finish", () => {
27 const duration = Date.now() - start;
28 if (path.startsWith("/api")) {
29 let logLine = `${req.method} ${path} ${res.statusCode} in ${duration}ms`;
30 if (capturedJsonResponse) {
31 logLine += ` :: ${JSON.stringify(capturedJsonResponse)}`;
32 }
33
34 if (logLine.length > 80) {
35 logLine = logLine.slice(0, 79) + "…";
36 }
37
38 log(logLine);
39 }
40 });
41
42 next();
43 });
44
45 (async () => {
46 const server = await registerRoutes(app);
47
48 // Seed database in background after server starts (non-blocking)
49 setImmediate(async () => {
50 try {
51 await seedDatabase();
52 await seedGuides();
53 } catch (error) {
54 console.error("Error seeding database:", error);
55 }
56 });
57
58 app.use((err: any, _req: Request, res: Response, _next: NextFunction) => {
59 const status = err.status || err.statusCode || 500;
60 const message = err.message || "Internal Server Error";
61
62 res.status(status).json({ message });
63 throw err;
64 });
65
66 // importantly only setup vite in development and after
67 // setting up all the other routes so the catch-all route
68 // doesn't interfere with the other routes
69 if (app.get("env") === "development") {
70 await setupVite(app, server);
71 } else {
72 serveStatic(app);
73 }
74
75 // ALWAYS serve the app on the port specified in the environment variable PORT
76 // Other ports are firewalled. Default to 5000 if not specified.
77 // this serves both the API and the client.
78 // It is the only port that is not firewalled.
79 const port = parseInt(process.env.PORT || '5000', 10);
80 server.listen({
81 port,
82 host: '0.0.0.0', // Important for deployment - allows external connections
83 reusePort: true,
84 }, () => {
85 log(`serving on port ${port}`);
86 });
87 })();