middleware

php
<?php

declare(strict_types=1);

namespace App\Security;

PHP Login Rate Limiting with a Sliding-Window Throttle Middleware

php rate-limiting middleware
by codesnips 3 tabs
ruby
class SlidingWindowLimiter
  Result = Struct.new(:allowed, :count, :limit, :window_ms, keyword_init: true)

  SCRIPT = <<~LUA.freeze
    local key = KEYS[1]
    local now = tonumber(ARGV[1])

Rate Limiting with Redis + Increment Expiry

rails redis reliability
by codesnips 3 tabs
rust
use dashmap::DashMap;
use std::time::Instant;

pub struct TokenBucket {
    tokens: f64,
    last_refill: Instant,

Token-Bucket Rate Limiter Middleware for Axum Using DashMap

axum rust rate-limiting
by codesnips 3 tabs
javascript
class ApiError extends Error {
  constructor(statusCode, message, code) {
    super(message);
    this.name = 'ApiError';
    this.statusCode = statusCode;
    this.code = code || null;

Centralized Async Error Handling in Express With asyncHandler and Error Middleware

express nodejs error-handling
by codesnips 4 tabs
go
package logctx

import (
	"context"
	"log/slog"
)

Request-Scoped Structured Logging with slog and Context in Go

go logging slog
by codesnips 3 tabs
typescript
import { randomBytes } from 'crypto';
import { Request, Response, NextFunction } from 'express';

interface CspOptions {
  reportOnly?: boolean;
  reportUri?: string;

Content Security Policy headers (defense-in-depth)

security express csp
by codesnips 3 tabs
typescript
import { z } from "zod";

const coerceNumber = z.preprocess((v) => {
  if (v === "" || v === undefined) return undefined;
  if (typeof v !== "string") return v;
  const n = Number(v);

API input coercion for query params (Zod preprocess)

typescript validation api
by codesnips 3 tabs
go
package authtransport

import (
	"errors"
	"net/http"
)

Injecting Auth Headers via a Custom http.RoundTripper Decorator in Go

go http middleware
by codesnips 3 tabs