⚡ AutoSnippets PRO PL

JavaScript: Production Code Snippets

Node.js and JavaScript snippets: rate limiting, security, async handling.

Python JavaScript TypeScript Java C# C++ Go PHP Rust SQL

On this page:

6. JavaScript: Advanced Rate Limiter

Node.js

Middleware that protects endpoints from DDoS and brute-force attacks.

const rateLimit = require('express-rate-limit');

const apiLimiter = rateLimit({
    windowMs: 15 * 60 * 1000,
    max: 100,
    standardHeaders: true,
    legacyHeaders: false,
    message: { status: 429, error: "Zbyt wiele żądań, spróbuj później." }
});

When to use

Use it on public API endpoints to cap the number of requests from a single IP address within a given time window.

Common pitfalls

The default rate limiter works in process memory — with multiple server instances each counts limits separately; a shared store (e.g. Redis) is required.

7. JavaScript: Webhook Signature Verification

Node.js

Secure authorization of incoming requests using HMAC SHA256.

const crypto = require('crypto');

function verifyWebhookSignature(req, secretKey) {
    const signature = req.headers['x-hub-signature-256'];
    if (!signature) return false;
    const hmac = crypto.createHmac('sha256', secretKey);
    const digest = `sha256=${hmac.update(req.rawBody).digest('hex')}`;
    return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(digest));
}

When to use

Required when receiving webhooks from external services (Stripe, GitHub, Slack), to make sure the request really came from them.

Common pitfalls

Verification must operate on the raw request body — if the framework has already parsed the JSON, the signature won't match.

8. JavaScript: Task Queue with Concurrency

JavaScript

Controlling the number of concurrently running background operations.

class TaskQueue {
    constructor(concurrency = 2) {
        this.concurrency = concurrency;
        this.running = 0;
        this.queue = [];
    }
    add(task) {
        return new Promise((resolve, reject) => {
            this.queue.push({ task, resolve, reject });
            this.next();
        });
    }
    next() {
        if (this.running >= this.concurrency || this.queue.length === 0) return;
        this.running++;
        const { task, resolve, reject } = this.queue.shift();
        task().then(resolve).catch(reject).finally(() => { this.running--; this.next(); });
    }
}

When to use

Useful when you need to process many async tasks but can't run them all at once (e.g. API limits).

Common pitfalls

Not handling errors for a single task can block the entire queue — make sure a rejected promise doesn't stop subsequent tasks.

9. JavaScript: Secure Password Hashing

Node.js

Generating salted hashes and verifying them with bcrypt.

const bcrypt = require('bcrypt');

async function hashPassword(plainPassword) {
    return await bcrypt.hash(plainPassword, 10);
}

async function verifyPassword(plainPassword, hashed) {
    return await bcrypt.compare(plainPassword, hashed);
}

When to use

The foundation of any login system — never store passwords in plain text or even a plain MD5/SHA1 hash.

Common pitfalls

Too low a cost factor (round count) in bcrypt makes the hash quick to crack — 10-12 is a safe minimum in 2026.

10. JavaScript: Robust Fetch with Timeout

JavaScript

An HTTP client resilient to hanging microservices (AbortController).

async function robustFetch(url, options = {}, timeoutMs = 5000) {
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), timeoutMs);
    try {
        const res = await fetch(url, { ...options, signal: controller.signal });
        clearTimeout(timer);
        if (!res.ok) throw new Error(`HTTP error: ${res.status}`);
        return await res.json();
    } catch (err) {
        clearTimeout(timer);
        throw err;
    }
}

When to use

Useful anywhere you call an external API and want to avoid a hanging request blocking the rest of the app.

Common pitfalls

A timeout alone doesn't handle retries — for unstable connections, combine it with retry logic that uses backoff.

59. JavaScript: Debounce and Throttle

JavaScript

Two techniques for limiting how often a function fires, e.g. on scroll or text input.

function debounce(func, delay) {
    let timer;
    return function (...args) {
        clearTimeout(timer);
        timer = setTimeout(() => func.apply(this, args), delay);
    };
}

function throttle(func, limit) {
    let inThrottle;
    return function (...args) {
        if (!inThrottle) {
            func.apply(this, args);
            inThrottle = true;
            setTimeout(() => (inThrottle = false), limit);
        }
    };
}

const searchHandler = debounce((query) => console.log("Szukam:", query), 300);

When to use

Use debounce for a search field (waiting for the user to stop typing); use throttle for scroll or resize events (limiting frequency without waiting for the event to 'end').

Common pitfalls

Confusing debounce with throttle is a common mistake — debounce may never fire under continuous activity, while throttle guarantees execution at a fixed interval.

60. JavaScript: Custom EventEmitter

JavaScript

A simple publish-subscribe pattern implementation with no external libraries.

class EventEmitter {
    constructor() {
        this.events = {};
    }
    on(event, listener) {
        (this.events[event] ??= []).push(listener);
        return this;
    }
    emit(event, ...args) {
        (this.events[event] || []).forEach(listener => listener(...args));
    }
    off(event, listener) {
        this.events[event] = (this.events[event] || []).filter(l => l !== listener);
    }
}

const emitter = new EventEmitter();
emitter.on("userCreated", (user) => console.log("Nowy użytkownik:", user.name));

When to use

Useful for communication between independent application modules without importing each other directly.

Common pitfalls

Lacking an off() (unsubscribe) method leads to memory leaks in long-lived applications — always remove listeners you no longer need.

61. JavaScript: LRU Cache (Map-based)

JavaScript

A size-bounded cache that evicts the least recently used items.

class LRUCache {
    constructor(capacity) {
        this.capacity = capacity;
        this.cache = new Map();
    }
    get(key) {
        if (!this.cache.has(key)) return undefined;
        const value = this.cache.get(key);
        this.cache.delete(key);
        this.cache.set(key, value);
        return value;
    }
    put(key, value) {
        if (this.cache.has(key)) this.cache.delete(key);
        else if (this.cache.size >= this.capacity) {
            this.cache.delete(this.cache.keys().next().value);
        }
        this.cache.set(key, value);
    }
}

When to use

Use it when caching results of expensive operations in memory and you want to cap RAM usage at a fixed size.

Common pitfalls

JavaScript's Map preserves insertion order, which this implementation relies on — using a plain object ({}) instead of Map wouldn't give the same ordering guarantee.

62. JavaScript: WebSocket with Auto-Reconnect

JavaScript

A WebSocket client that automatically reconnects after a dropped connection.

function createResilientSocket(url, onMessage) {
    let socket;
    let reconnectDelay = 1000;

    function connect() {
        socket = new WebSocket(url);
        socket.onmessage = onMessage;
        socket.onopen = () => { reconnectDelay = 1000; };
        socket.onclose = () => {
            setTimeout(connect, reconnectDelay);
            reconnectDelay = Math.min(reconnectDelay * 2, 30000);
        };
    }

    connect();
    return { close: () => socket.close() };
}

When to use

Essential in real-time applications (chats, live notifications), where a brief connection loss shouldn't require a manual page refresh.

Common pitfalls

Without an upper bound on reconnectDelay (exponential backoff), a long outage could result in reconnect attempts every few minutes instead of a 30-second cap — as used in this example.

63. JavaScript: Simple In-Memory Pub/Sub

JavaScript

A lightweight publish-subscribe mechanism for communication between frontend components.

const PubSub = {
    topics: {},
    subscribe(topic, callback) {
        (this.topics[topic] ??= []).push(callback);
        return () => this.unsubscribe(topic, callback);
    },
    unsubscribe(topic, callback) {
        this.topics[topic] = (this.topics[topic] || []).filter(cb => cb !== callback);
    },
    publish(topic, data) {
        (this.topics[topic] || []).forEach(cb => cb(data));
    }
};

const unsubscribe = PubSub.subscribe("cartUpdated", (cart) => console.log(cart));

When to use

Useful in component-based frontend apps where two unrelated components need to react to the same events without a shared parent.

Common pitfalls

A subscription that returns an unsubscribe function (as in this example) is easy to overlook — not calling it on component unmount is a common cause of memory leaks in SPAs.

64. JavaScript: Deep Clone and Deep Merge

JavaScript

Deep copying and merging nested objects without mutating the originals.

function deepClone(obj) {
    if (obj === null || typeof obj !== "object") return obj;
    if (Array.isArray(obj)) return obj.map(deepClone);
    return Object.fromEntries(
        Object.entries(obj).map(([k, v]) => [k, deepClone(v)])
    );
}

function deepMerge(target, source) {
    const result = deepClone(target);
    for (const key in source) {
        if (source[key] instanceof Object && key in result) {
            result[key] = deepMerge(result[key], source[key]);
        } else {
            result[key] = source[key];
        }
    }
    return result;
}

When to use

Use it when merging configuration (e.g. defaults + user overrides) or updating state without mutating the original objects.

Common pitfalls

structuredClone(), available natively in modern browsers, does the same thing faster and more safely than a manual implementation — use it if you don't need to support older environments.

65. JavaScript: In-Memory Rate Limiter (Token Bucket)

JavaScript

A request limiter implementation with no external dependencies like Redis.

class TokenBucket {
    constructor(capacity, refillRate) {
        this.capacity = capacity;
        this.tokens = capacity;
        this.refillRate = refillRate;
        this.lastRefill = Date.now();
    }
    allow() {
        const now = Date.now();
        const elapsed = (now - this.lastRefill) / 1000;
        this.tokens = Math.min(this.capacity, this.tokens + elapsed * this.refillRate);
        this.lastRefill = now;
        if (this.tokens >= 1) {
            this.tokens -= 1;
            return true;
        }
        return false;
    }
}

const limiter = new TokenBucket(10, 2);
if (!limiter.allow()) console.log("Limit przekroczony");

When to use

Useful for simple, single-process Node.js apps where you don't want a Redis dependency just to limit requests.

Common pitfalls

This limiter keeps state in a single process's memory — with multiple app instances (load balancing), each counts limits separately, effectively multiplying the allowed limit.