Stackbits
Utilities > Express Server

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

1
npm i express cors express-rate-limit

Express Server.js Template

1
import express from 'express';
2
import cors from 'cors';
3
import rateLimit from 'express-rate-limit';
4
5
import './config/logging'; // ? Custom logging setup, refer to the logging guide -> https://stackbits.dev/docs/customlogger
6
7
const PORT = process.env.PORT || 3000; // Use environment variable for flexibility
8
9
const app = express();
10
11
// Middleware Configuration
12
13
// Enable CORS for specific origins
14
app.use(
15
cors({
16
origin: ['http://localhost:3000'], // Adjust based on frontend deployment
17
credentials: true,
18
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], // Explicitly allow methods
19
})
20
);
21
22
// Rate limiting to prevent abuse
23
const limiter = rateLimit({
24
windowMs: 60 * 1000, // 1-minute window
25
limit: 100, // Max 100 requests per window
26
standardHeaders: 'draft-7', // Use the latest draft headers
27
legacyHeaders: false, // Disable deprecated headers
28
message: { error: 'Too many requests from this IP, please try again later.' }, // Consistent error format
29
});
30
app.use(limiter);
31
32
// Parsing middleware
33
app.use(express.json({ limit: '20mb' })); // Set a reasonable body size limit
34
app.use(express.urlencoded({ extended: false })); // Enable URL-encoded data parsing
35
36
// Additional security headers
37
app.use((req, res, next) => {
38
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
39
res.header('Access-Control-Allow-Credentials', 'true');
40
next();
41
});
42
43
// * Define API Routes here
44
// Example: app.use('/api/users', userRoutes);
45
46
// Start the server
47
app.listen(PORT, () => {
48
console.info(`✅ Server is running on http://localhost:${PORT}`);
49
});

⭐️ Got a question or feedback?
Feel free to reach out!