Express Server
This Express.js server setup includes CORS configuration, rate limiting for security, JSON parsing, and essential middleware for handling requests efficiently. It follows best practices for maintainability, security, and flexibility, making it easy to scale and integrate with a frontend application.
Install dependencies
1npm i express cors express-rate-limit
Express Server.js Template
1import express from 'express';2import cors from 'cors';3import rateLimit from 'express-rate-limit';45import './config/logging'; // ? Custom logging setup, refer to the logging guide -> https://stackbits.dev/docs/customlogger67const PORT = process.env.PORT || 3000; // Use environment variable for flexibility89const app = express();1011// Middleware Configuration1213// Enable CORS for specific origins14app.use(15cors({16origin: ['http://localhost:3000'], // Adjust based on frontend deployment17credentials: true,18methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], // Explicitly allow methods19})20);2122// Rate limiting to prevent abuse23const limiter = rateLimit({24windowMs: 60 * 1000, // 1-minute window25limit: 100, // Max 100 requests per window26standardHeaders: 'draft-7', // Use the latest draft headers27legacyHeaders: false, // Disable deprecated headers28message: { error: 'Too many requests from this IP, please try again later.' }, // Consistent error format29});30app.use(limiter);3132// Parsing middleware33app.use(express.json({ limit: '20mb' })); // Set a reasonable body size limit34app.use(express.urlencoded({ extended: false })); // Enable URL-encoded data parsing3536// Additional security headers37app.use((req, res, next) => {38res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');39res.header('Access-Control-Allow-Credentials', 'true');40next();41});4243// * Define API Routes here44// Example: app.use('/api/users', userRoutes);4546// Start the server47app.listen(PORT, () => {48console.info(`✅ Server is running on http://localhost:${PORT}`);49});
⭐️ Got a question or feedback?
Feel free to reach out!