Code Snippets Background
Copy & Paste

Code Snippets &
Prompt Lab

Production-tested React hooks, AI engineering prompts, utility functions, and design patterns. Every snippet is battle-tested in real projects. Copy, paste, ship.

12+

Snippets

5

Categories

7+

Languages

100%

Copy Ready

Explore Snippets

Production-tested hooks, prompts, and utility functions.

bash

Stop all tasks in an ECS cluster via AWS CLI

A bash one‑liner that lists every task in a given ECS cluster (handling pagination) and stops them safely with the AWS CLI.

awsecs
snippet.bash
#!/usr/bin/env bash
set -euo pipefail

CLUSTER="${1:-}"
if [[ -z "$CLUSTER" ]]; then echo "Usage: $0 <cluster-name>"; exit 1; fi

NEXT_TOKEN="null"
while :; do
  if [[ "$NEXT_TOKEN" == "null" ]]; then
    RESP=$(aws ecs list-tasks --cluster "$CLUSTER" --output json)
  else
    RESP=$(aws ecs list-tasks --cluster "$CLUSTER" --starting-token "$NEXT_TOKEN" --output json)
  fi

  TASKS=$(echo "$RESP" | jq -r '.taskArns[]?')
  for TASK_ARN in $TASKS; do
    echo "Stopping $TASK_ARN"
    aws ecs stop-task --cluster "$CLUSTER" --task "$TASK_ARN" --output json >/dev/null
  done

  NEXT_TOKEN=$(echo "$RESP" | jq -r '.nextToken // empty')
  [[ -z "$NEXT_TOKEN" ]] && break
done

echo "All tasks stopped."
go

Read Excel file row‑by‑row in Go with excelize

Shows how to stream an .xlsx file row by row using the official excelize library, safe for large files.

goexcelfile-io
snippet.go
package main

import (
    "fmt"
    "log"

    "github.com/xuri/excelize/v2"
)

func main() {
    f, err := excelize.OpenFile("data.xlsx")
    if err != nil {
        log.Fatalf("cannot open file: %v", err)
    }
    defer func() {
        if cerr := f.Close(); cerr != nil {
            log.Printf("close error: %v", cerr)
        }
    }()

    sheet := f.GetSheetName(0) // first sheet
    rows, err := f.Rows(sheet)
    if err != nil {
        log.Fatalf("cannot get rows iterator: %v", err)
    }
    defer rows.Close()

    rowNum := 0
    for rows.Next() {
        rowNum++
        cols, err := rows.Columns()
        if err != nil {
            log.Printf("error reading row %d: %v", rowNum, err)
            continue
        }
        fmt.Printf("Row %d: %v\n", rowNum, cols)
    }
    if err = rows.Error(); err != nil {
        log.Fatalf("iteration error: %v", err)
    }
}
go

Read Excel rows efficiently in Go with excelize streaming

Shows how to open an .xlsx file and stream each row using excelize/v2, ideal for large files.

goexcel
snippet.go
package main

import (
    "fmt"
    "log"
    "github.com/xuri/excelize/v2"
)

func main() {
    f, err := excelize.OpenFile("data.xlsx")
    if err != nil {
        log.Fatalf("failed to open file: %v", err)
    }
    defer func() {
        if err := f.Close(); err != nil {
            log.Printf("failed to close file: %v", err)
        }
    }()

    // Use streaming to avoid loading the whole sheet into memory
    rows, err := f.Rows("Sheet1")
    if err != nil {
        log.Fatalf("failed to get rows: %v", err)
    }
    defer rows.Close()

    rowIdx := 0
    for rows.Next() {
        rowIdx++
        cols, err := rows.Columns()
        if err != nil {
            log.Printf("row %d read error: %v", rowIdx, err)
            continue
        }
        fmt.Printf("Row %d: %v\n", rowIdx, cols)
        // Process columns here, e.g., parse ints, dates, etc.
    }
    if err = rows.Error(); err != nil {
        log.Fatalf("streaming error: %v", err)
    }
}
json

Enforce case‑consistent imports to fix TS type‑checking on Linux vs macOS

Turn on strict casing and linting so the same TypeScript code compiles without errors on case‑sensitive Linux and case‑insensitive macOS.

typescriptcross‑platform
snippet.json
// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "commonjs",
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "noEmit": true,
    "baseUrl": "src",
    "paths": {
      "@/*": ["*"]
    }
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules"]
}

// package.json (scripts section)
{
  "scripts": {
    "typecheck": "tsc --noEmit",
    "lint:case": "eslint src/**/*.ts"
  }
}

// .eslintrc.js (adds import‑path case check)
module.exports = {
  parser: '@typescript-eslint/parser',
  plugins: ['@typescript-eslint', 'import'],
  extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended'],
  rules: {
    'import/no-unresolved': 'error'
  },
  settings: {
    'import/resolver': {
      typescript: {}
    }
  }
};
python

FastAPI async SQLAlchemy session dependency

Provides a clean async DB session dependency for FastAPI using SQLAlchemy 2.0, eliminating manual session cleanup.

fastapisqlalchemyasync
snippet.python
from fastapi import FastAPI, Depends
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine, async_sessionmaker, AsyncSession
from sqlalchemy.orm import declarative_base

DATABASE_URL = 'postgresql+asyncpg://user:password@localhost/dbname'

engine: AsyncEngine = create_async_engine(DATABASE_URL, echo=False, future=True)
AsyncSessionLocal = async_sessionmaker(bind=engine, expire_on_commit=False, class_=AsyncSession)
Base = declarative_base()

async def get_db() -> AsyncSession:
    async with AsyncSessionLocal() as session:
        try:
            yield session
        finally:
            await session.close()

app = FastAPI()

@app.get('/items/{item_id}')
async def read_item(item_id: int, db: AsyncSession = Depends(get_db)):
    result = await db.execute('SELECT * FROM items WHERE id = :id', {'id': item_id})
    item = result.fetchone()
    if not item:
        return {'error': 'Item not found'}
    return dict(item)
bash

Bash script to rotate AWS IAM access keys safely

Automates creating a new IAM access key, validates it, updates the local AWS credentials file, and deletes the old key with full error handling.

bashawssecurity
snippet.bash
#!/usr/bin/env bash\nset -euo pipefail\n\n# Config\nUSER_NAME=\"${1:-}\"   # IAM user passed as first argument\nPROFILE=\"${2:-default}\"   # AWS CLI profile (optional)\nREGION=\"${3:-us-east-1}\"   # Region (optional)\n\nlog(){ echo \"[$(date +'%Y-%m-%dT%H:%M:%S%z')] $*\"; }\n\nusage(){\n  echo \"Usage: $0 <iam-user-name> [aws-profile] [region]\"\n  exit 1\n}\n\nif [[ -z \"$USER_NAME\" ]]; then usage; fi\n\n# Helper to get current access key IDs for the user\nlist_keys(){\n  aws iam list-access-keys --user-name \"$USER_NAME\" --profile \"$PROFILE\" --output json |\n    jq -r '.AccessKeyMetadata[].AccessKeyId'\n}\n\n# Create new access key\nlog \"Creating new access key for $USER_NAME\"\nNEW_KEY_JSON=$(aws iam create-access-key --user-name \"$USER_NAME\" --profile \"$PROFILE\" --output json)\nNEW_ACCESS_KEY_ID=$(echo \"$NEW_KEY_JSON\" | jq -r '.AccessKey.AccessKeyId')\nNEW_SECRET_ACCESS_KEY=$(echo \"$NEW_KEY_JSON\" | jq -r '.AccessKey.SecretAccessKey')\nlog \"New key ID: $NEW_ACCESS_KEY_ID\"\n\n# Test new credentials\nlog \"Validating new credentials\"\nAWS_ACCESS_KEY_ID=\"$NEW_ACCESS_KEY_ID\" AWS_SECRET_ACCESS_KEY=\"$NEW_SECRET_ACCESS_KEY\" aws sts get-caller-identity --profile \"$PROFILE\" --region \"$REGION\" >/dev/null\nlog \"New credentials are valid\"\n\n# Update local credentials file (~/.aws/credentials) for the profile\nCRED_FILE=\"$HOME/.aws/credentials\"\nlog \"Updating $CRED_FILE for profile $PROFILE\"\nif grep -q \"\\\\[${PROFILE}\\\\]\" \"$CRED_FILE\"; then\n  # Replace existing keys\n  sed -i.bak -E \"/\\\\[${PROFILE}\\\\]/,/^\\\\s*$/ {s/^aws_access_key_id\\\\s*=.*$/aws_access_key_id = $NEW_ACCESS_KEY_ID/; s/^aws_secret_access_key\\\\s*=.*$/aws_secret_access_key = $NEW_SECRET_ACCESS_KEY/}\" \"$CRED_FILE\"\nelse\n  # Append new profile section\n  echo -e \"\\n[${PROFILE}]\\naws_access_key_id = $NEW_ACCESS_KEY_ID\\naws_secret_access_key = $NEW_SECRET_ACCESS_KEY\" >> \"$CRED_FILE\"\nfi\nlog \"Credentials file updated\"\n\n# Delete old keys (all except the newly created one)\nlog \"Removing old access keys\"\nfor KEY_ID in $(list_keys); do\n  if [[ \"$KEY_ID\" != \"$NEW_ACCESS_KEY_ID\" ]]; then\n    log \"Deleting $KEY_ID\"\n    aws iam delete-access-key --user-name \"$USER_NAME\" --access-key-id \"$KEY_ID\" --profile \"$PROFILE\"\n  fi\n done\nlog \"Rotation complete for $USER_NAME\"\n\nexit 0
typescript

Express TypeScript Token Bucket Rate Limiter Middleware

A production‑ready middleware that enforces per‑IP request limits using a token‑bucket algorithm, fully typed for Express 6+.

typescriptexpressrate-limiter
snippet.ts
import { Request, Response, NextFunction } from 'express';

type RateLimiterOptions = {
  tokens: number; // max tokens in bucket
  refillRate: number; // tokens added per millisecond
};

class TokenBucket {
  private tokens: number;
  private lastRefill: number;

  constructor(private readonly capacity: number, private readonly refillRate: number) {
    this.tokens = capacity;
    this.lastRefill = Date.now();
  }

  private refill() {
    const now = Date.now();
    const elapsed = now - this.lastRefill;
    const added = elapsed * this.refillRate;
    this.tokens = Math.min(this.capacity, this.tokens + added);
    this.lastRefill = now;
  }

  tryRemove(count = 1): boolean {
    this.refill();
    if (this.tokens >= count) {
      this.tokens -= count;
      return true;
    }
    return false;
  }
}

export function rateLimiter(opts: RateLimiterOptions) {
  const buckets = new Map<string, TokenBucket>();
  const cleanupInterval = setInterval(() => {
    const now = Date.now();
    for (const [key, bucket] of buckets) {
      // If a bucket hasn't been touched for >1 minute, drop it
      if (now - (bucket as any).lastRefill > 60_000) {
        buckets.delete(key);
      }
    }
  }, 60_000);

  // Graceful shutdown cleanup
  process.on('SIGTERM', () => clearInterval(cleanupInterval));
  process.on('SIGINT', () => clearInterval(cleanupInterval));

  return (req: Request, res: Response, next: NextFunction) => {
    const key = req.ip;
    let bucket = buckets.get(key);
    if (!bucket) {
      bucket = new TokenBucket(opts.tokens, opts.refillRate);
      buckets.set(key, bucket);
    }

    if (bucket.tryRemove()) {
      next();
    } else {
      res.status(429).json({ error: 'Too Many Requests' });
    }
  };
}
bash

Robust Bash S3 Sync with Retries and Checksum Verification

A production‑ready Bash script that syncs a local folder to S3, verifies each upload with checksums, and automatically retries failures using exponential backoff.

bashaws-s3
snippet.bash
#!/usr/bin/env bash
set -euo pipefail

SRC_DIR="/path/to/source"
BUCKET="s3://my-bucket"
MAX_RETRIES=5
BASE_DELAY=2

log(){ echo "$(date +'%Y-%m-%d %H:%M:%S') $*"; }

retry(){ local n=0; local delay=$BASE_DELAY; while true; do "$@" && break || { ((n++>=MAX_RETRIES)) && { log "Failed after $n attempts"; return 1; }; log "Retry $n in $delay sec"; sleep $delay; delay=$((delay*2)); }; done; }

sync_file(){ local file=$1; local rel=${file#$SRC_DIR/}; local dest="$BUCKET/$rel"; retry aws s3 cp "$file" "$dest" --checksum; }

export -f retry sync_file log

find "$SRC_DIR" -type f | while read -r f; do
  sync_file "$f"
 done

log "Sync complete"
typescript

React useIntersectionObserver Hook with TypeScript

Detect when a DOM element enters the viewport for lazy‑loading or infinite scroll. Handles cleanup, optional freeze‑once‑visible, and graceful fallback when IntersectionObserver isn’t supported.

reacttypescripthookintersectionobserver
snippet.ts
import { useEffect, useState, useRef, MutableRefObject, useCallback } from 'react';

type IntersectionObserverOptions = {
  root?: Element | null;
  rootMargin?: string;
  threshold?: number | number[];
  freezeOnceVisible?: boolean;
};

/**
 * Returns a ref‑callback to attach to the target element and a boolean that
 * becomes true when the element is intersecting the viewport.
 */
export function useIntersectionObserver<T extends Element = Element>(
  options: IntersectionObserverOptions = {}
): [(node: T | null) => void, boolean] {
  const { root = null, rootMargin = '0px', threshold = 0, freezeOnceVisible = false } = options;
  const [isIntersecting, setIntersecting] = useState(false);
  const observer = useRef<IntersectionObserver | null>(null);

  const setNode = useCallback((node: T | null) => {
    if (observer.current) {
      observer.current.disconnect();
      observer.current = null;
    }
    if (!node) return;
    if (freezeOnceVisible && isIntersecting) return;

    const callback: IntersectionObserverCallback = ([entry]) => {
      setIntersecting(entry.isIntersecting);
    };

    if (typeof IntersectionObserver !== 'undefined') {
      observer.current = new IntersectionObserver(callback, { root, rootMargin, threshold });
      observer.current.observe(node);
    } else {
      // Fallback for browsers without IntersectionObserver support
      setIntersecting(true);
    }
  }, [root, rootMargin, threshold, freezeOnceVisible, isIntersecting]);

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      observer.current?.disconnect();
    };
  }, []);

  return [setNode, isIntersecting];
}
css

CSS Hide Scrollbar

A universal CSS class to hide the scrollbar while allowing scrolling.

cssuiux
snippet.css
.hide-scrollbar {
  /* IE and Edge */
  -ms-overflow-style: none;
  
  /* Firefox */
  scrollbar-width: none;
}

.hide-scrollbar::-webkit-scrollbar {
  /* Chrome, Safari and Opera */
  display: none;
}
bash

Vercel Ignore Build Step

Bash script to ignore Vercel builds if no relevant files have changed.

vercelbash
snippet.bash
#!/bin/bash

if git diff HEAD^ HEAD --quiet ./src; then
  echo "🛑 - Build cancelled"
  exit 0
else
  echo "✅ - Build can proceed"
  exit 1
fi
yaml

GitHub Actions Node.js CI

A fast GitHub Actions workflow for caching and testing Node.js applications.

github-actionscinodejs
snippet.yaml
name: Node.js CI

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
    - name: Use Node.js 18.x
      uses: actions/setup-node@v3
      with:
        node-version: 18.x
        cache: 'npm'
    - run: npm ci
    - run: npm run build
    - run: npm test

Stay Ahead of the Curve

Get our weekly digest of production blueprints, deep-dive benchmarks, and architectural audits delivered directly to your inbox.

Join 5,000+ engineers. No spam, ever.