Skip to content

[Bug] [Production]: Enhance server.js with graceful shutdown, env validation, and improved error handling #88

Description

@zaibamachhaliya

Issue Description

Current server.js lacks critical features needed for a production-ready application.

Problems Found

1. No Graceful Shutdown

When server receives SIGINT/SIGTERM, database connections are not closed properly.
Risk: Connection leaks and data corruption.

2. No Environment Validation

Server starts without checking required environment variables.
Risk: Runtime errors when variables are missing.

3. Basic Health Check

Only returns "OK" status, doesn't verify database connectivity.
Risk: Can't monitor actual service health.

4. CORS Only for Development

No production CORS configuration.
Risk: Security issues in production.

5. Generic Error Handler

All errors return 500 with same message.
Risk: Poor debugging experience.

Proposed Solutions

1. Graceful Shutdown

const gracefulShutdown = async (signal) => {
  console.log(`Received ${signal}. Shutting down gracefully...`);
  
  // Close MongoDB
  await mongoose.connection.close();
  console.log('MongoDB connection closed');
  
  // Close Redis
  await redisClient.quit();
  console.log('Redis connection closed');
  
  // Close server
  server.close(() => {
    console.log('Server shut down successfully');
    process.exit(0);
  });
};

process.on('SIGINT', () => gracefulShutdown('SIGINT'));
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));

Metadata

Metadata

Labels

HardSSoC26bugSomething isn't workingdocumentationImprovements or additions to documentation

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions