const next = require("next"); const { createServer } = require("http"); const appInsights = require("applicationinsights"); const initAppInsights = (instrumentationKey) => { if (!instrumentationKey) { console.log("App Insights not configured."); return false; } appInsights .setup(instrumentationKey) .setAutoCollectConsole(true, true) .setSendLiveMetrics(true) .start(); console.log("App Insights enabled."); return true; }; const startServer = async (config) => { const serverOptions = { dev: config.env === "development", dir: ".", quiet: false, }; const app = next(serverOptions); await app.prepare(); // prepare BEFORE starting the server const handleNextRequests = app.getRequestHandler(); const srv = createServer((req, res) => { if (config.useAppInsights) { appInsights.defaultClient.trackNodeHttpRequest({ request: req, response: res, }); } handleNextRequests(req, res); }); await new Promise((resolve, reject) => { srv.on("error", reject); srv.on("listening", () => resolve()); srv.listen(config.port, config.hostname); }); // Graceful shutdown handling process.on("SIGTERM", () => { console.log("Received SIGTERM, shutting down gracefully..."); srv.close(() => { console.log("Server closed."); process.exit(0); }); }); return app; }; // App configuration const startTime = Date.now(); const serverConfig = { hostname: "0.0.0.0", // Required for Azure App Service port: parseInt(process.env.PORT, 10) || 3000, env: process.env.APP_ENV || process.env.NODE_ENV || "production", useAppInsights: initAppInsights( process.env.NEXT_PUBLIC_APPINSIGHTS_INSTRUMENTATIONKEY ), }; startServer(serverConfig) .then(() => { console.log( `Server ready on http://${serverConfig.hostname}:${serverConfig.port} [${serverConfig.env}]` ); if (serverConfig.useAppInsights) { const duration = Date.now() - startTime; appInsights.defaultClient.trackMetric({ name: "Server Startup Time", value: duration, }); } }) .catch((err) => { console.error("Server failed to start:", err); process.exit(1); });