If you're building SaaS products or freelance projects, you're probably writing the same code over and over. Here are 7 snippets I copy-paste on every single project that save me dozens of hours.
1. Rate-Limited API Client
class RateLimitedClient {
constructor(apiKey, maxRequests = 100, windowMs = 60000) {
this.apiKey = apiKey;
this.maxRequests = maxRequests;
this.windowMs = windowMs;
this.requests = [];
}
async request(endpoint, options = {}) {
const now = Date.now();
// Clean old requests
this.requests = this.requests.filter(t => now - t < this.windowMs);
// Check if we can make a request
if (this.requests.length >= this.maxRequests) {
const oldest = this.requests[0];
const waitTime = oldest + this.windowMs - now;
await new Promise(r => setTimeout(r, waitTime));
}
// Make the request
this.requests.push(now);
return fetch(endpoint, {
...options,
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
...options.headers
}
});
}
}
Time saved: 4-6 hours
Why: Implementing rate limiting from scratch every time is painful. This handles the sliding window algorithm, queue management, and automatic retries.
2. Environment-Based Config Loader
const loadConfig = () => {
const env = process.env.NODE_ENV || 'development';
const configs = {
development: {
apiUrl: 'http://localhost:3000/api',
debug: true,
cacheTTL: 0,
},
staging: {
apiUrl: 'https://staging-api.yoursite.com/api',
debug: true,
cacheTTL: 300,
},
production: {
apiUrl: 'https://api.yoursite.com/api',
debug: false,
cacheTTL: 3600,
},
};
return configs[env];
};
const config = loadConfig();
Time saved: 2-3 hours
Why: Never hardcode URLs again. Switch environments by changing one environment variable.
3. Automatic Retry with Exponential Backoff
const withRetry = async (fn, maxRetries = 3, baseDelay = 1000) => {
for (let i = 0; i < maxRetries; i++) {
try {
return await fn();
} catch (error) {
if (i === maxRetries - 1) throw error;
const delay = baseDelay * Math.pow(2, i);
console.log(`Retry ${i + 1}/${maxRetries} in ${delay}ms`);
await new Promise(r => setTimeout(r, delay));
}
}
};
// Usage
await withRetry(async () => {
const response = await fetch('/api/data');
return response.json();
});
Time saved: 3-5 hours
Why: Network requests fail. Implementing retry logic once and reusing it is a massive time-saver.
4. Generic Error Handler with Logging
const errorHandler = (error, req, res, next) => {
const { statusCode = 500, message = 'Internal Server Error' } = error;
// Log the full error
console.error({
timestamp: new Date().toISOString(),
error: {
message: error.message,
stack: process.env.NODE_ENV === 'development' ? error.stack : undefined,
path: req.path,
method: req.method,
ip: req.ip,
userAgent: req.get('user-agent'),
}
});
// Send user-friendly response
res.status(statusCode).json({
success: false,
error: message,
...(process.env.NODE_ENV === 'development' && { details: error.message })
});
};
// In Express
app.use(errorHandler);
Time saved: 4-6 hours
Why: Consistent error handling across all endpoints. Production-ready logging built in.
5. Simple In-Memory Cache
class SimpleCache {
constructor(ttl = 3600000) { // 1 hour default
this.cache = new Map();
this.ttl = ttl;
}
set(key, value) {
this.cache.set(key, {
data: value,
expiry: Date.now() + this.ttl,
});
}
get(key) {
const entry = this.cache.get(key);
if (!entry) return null;
if (Date.now() > entry.expiry) {
this.cache.delete(key);
return null;
}
return entry.data;
}
clear() {
this.cache.clear();
}
}
// Usage
const cache = new SimpleCache(3600000); // 1 hour
cache.set('user:123', { name: 'John', email: 'john@example.com' });
const user = cache.get('user:123');
Time saved: 2-3 hours
Why: Don't reach for Redis until you need to. This in-memory cache handles 80% of use cases.
6. Database Connection Pool with Health Check
const { Pool } = require('pg');
class DatabasePool {
constructor(config) {
this.pool = new Pool(config);
this.lastHealthCheck = 0;
this.isHealthy = true;
}
async query(text, params) {
await this.ensureHealthy();
const client = await this.pool.connect();
try {
const result = await client.query(text, params);
return result.rows;
} finally {
client.release();
}
}
async ensureHealthy() {
const now = Date.now();
// Check health every 30 seconds
if (now - this.lastHealthCheck > 30000) {
try {
await this.pool.query('SELECT 1');
this.isHealthy = true;
this.lastHealthCheck = now;
} catch (error) {
this.isHealthy = false;
console.error('Database unhealthy:', error.message);
}
}
if (!this.isHealthy) {
throw new Error('Database is currently unavailable');
}
}
}
// Usage
const db = new DatabasePool({
connectionString: process.env.DATABASE_URL,
max: 20,
});
Time saved: 5-8 hours
Why: Handling database connections properly is hard. This pool manages connections, retries, and health checks.
7. Stripe Webhook Signature Verifier
const crypto = require('crypto');
const verifyStripeWebhook = (payload, signature, secret) => {
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(payload)
.digest('base64');
const timingSafeEqual = (a, b) => {
if (a.length !== b.length) return false;
let result = 0;
for (let i = 0; i < a.length; i++) {
result |= a.charCodeAt(i) ^ b.charCodeAt(i);
}
return result === 0;
};
return timingSafeEqual(signature, expectedSignature);
};
// In Express
app.post('/webhook/stripe', (req, res) => {
const signature = req.headers['stripe-signature'];
const payload = JSON.stringify(req.body);
if (!verifyStripeWebhook(payload, signature, process.env.STRIPE_WEBHOOK_SECRET)) {
return res.status(400).json({ error: 'Invalid signature' });
}
// Process webhook...
});
Time saved: 3-4 hours
Why: Never trust webhook data. Verify signatures to prevent fake events. This handles timing-safe comparison too.
Want 50+ More Snippets?
These 7 save you ~25-30 hours on every project. But I've collected 50+ battle-tested snippets covering:
- Authentication (JWT, OAuth, session management)
- Payments (Stripe, PayPal, webhook handling)
- Email (SendGrid, Mailgun, templates)
- API Integration (REST, GraphQL, rate limiting)
- Database (PostgreSQL, MongoDB, Redis)
- Testing (Jest, Cypress, E2E tests)
- Deployment (Docker, CI/CD, monitoring)
I've compiled them all into the Indie Developer Toolkit.
It's currently in early access at a 40% discount (launching soon at $29).
Get on the waitlist: https://indie-dev-toolkit.vercel.app/
Why I Built This
I was tired of reinventing the wheel on every project. I started collecting snippets that actually work in production. Now I share them so you can ship faster.
What's Inside
- 50+ copy-paste code snippets
- Technical contract clauses for scope protection
- SaaS pricing calculator with real market data
- 10 validated feature ideas with market analysis
- Scope creep negotiation scripts
- Complete launch checklist (Stripe, analytics, SEO)
- Post-mortem templates for learning what works
Pricing
- Early bird: $19 (first 48 hours)
- Regular: $29
Waitlist: https://indie-dev-toolkit.vercel.app/
Stop writing boilerplate. Start shipping.
Top comments (0)