Home

Snippets

Copy-ready code from my blog posts, each linked back to the article that explains it.

10 snippets

  • globals.css
    :root {
      /* ── background hierarchy ── */
      --bg-base:     #111318;
      --bg-surface:  #1a1d24;
      --bg-elevated: #21252e;
    
      /* ── text hierarchy ── */
      --text-primary:   #e4e6ea;
      --text-secondary: #a0a5ae;
      --text-tertiary:  #6b7280;
      --text-disabled:  #454952;
    
      /* ── semantic ── */
      --color-primary: #4a8f85;
      --color-success: #3d9970;
      --color-warning: #c79a3a;
      --color-danger:  #c0504d;
    }
  • globals.css
    .text-xs   { font-size: 11px; line-height: 1.5; }
    .text-sm   { font-size: 13px; line-height: 1.5; }
    .text-base { font-size: 15px; line-height: 1.6; }
    .text-md   { font-size: 17px; line-height: 1.5; }
    .text-lg   { font-size: 21px; line-height: 1.3; }
    .text-xl   { font-size: 26px; line-height: 1.2; }
    .text-2xl  { font-size: 32px; line-height: 1.15; }
  • Badge.tsx
    export function Badge({ children, variant = "default" }) {
      const styles = {
        default: "bg-[var(--color-primary-subtle)] text-[var(--color-primary)]",
        outline: "border border-[var(--border-default)] text-[var(--text-tertiary)]",
        muted: "bg-[var(--bg-elevated)] text-[var(--text-tertiary)]",
      };
    
      return (
        <span className={`inline-flex items-center px-2 py-0.5
          rounded-[var(--radius-badge)] text-[11px] font-semibold
          ${styles[variant]}`}>
          {children}
        </span>
      );
    }
  • middleware.ts
    import { NextResponse } from "next/server";
    import type { NextRequest } from "next/server";
    import { verifyToken } from "@/lib/auth";
    
    export async function middleware(request: NextRequest) {
      const token = request.cookies.get("session")?.value;
    
      if (!token) {
        return NextResponse.redirect(new URL("/login", request.url));
      }
    
      try {
        const payload = await verifyToken(token);
        const headers = new Headers(request.headers);
        headers.set("x-user-id", payload.sub);
        return NextResponse.next({ headers });
      } catch {
        return NextResponse.redirect(new URL("/login", request.url));
      }
    }
    
    export const config = {
      matcher: ["/dashboard/:path*", "/api/protected/:path*"],
    };
  • next.config.ts
    const cspHeader = `
      default-src 'self';
      script-src 'self' 'nonce-${nonce}';
      style-src 'self' 'unsafe-inline';
      img-src 'self' blob: data:;
      font-src 'self';
      connect-src 'self' https://api.example.com;
      frame-ancestors 'none';
      base-uri 'self';
      form-action 'self';
    `;
  • lib/rate-limit.ts
    const rateLimit = new Map<string, { count: number; last: number }>();
    
    export function checkRateLimit(
      ip: string,
      limit = 10,
      windowMs = 60_000
    ): boolean {
      const now = Date.now();
      const entry = rateLimit.get(ip);
    
      if (!entry || now - entry.last > windowMs) {
        rateLimit.set(ip, { count: 1, last: now });
        return true;
      }
    
      if (entry.count >= limit) return false;
    
      entry.count++;
      return true;
    }
  • Project layout
    project/
    ├── docker-compose.yml          # Main orchestration
    ├── docker-compose.override.yml # Dev overrides
    ├── .env                        # Environment variables
    ├── Makefile                    # Automation commands
    ├── srcs/
    │   ├── frontend/
    │   │   ├── Dockerfile
    │   │   └── ...
    │   ├── backend/
    │   │   ├── Dockerfile
    │   │   └── ...
    │   ├── nginx/
    │   │   ├── Dockerfile
    │   │   └── conf/
    │   └── monitoring/
    │       ├── prometheus.yml
    │       └── grafana/
    └── volumes/                    # Persistent data
  • docker-compose.yml
    services:
      nginx:
        build: ./srcs/nginx
        ports:
          - "443:443"
        depends_on:
          frontend:
            condition: service_healthy
          backend:
            condition: service_healthy
        networks:
          - frontend-net
        restart: unless-stopped
    
      frontend:
        build: ./srcs/frontend
        expose:
          - "3000"
        healthcheck:
          test: ["CMD", "curl", "-f", "http://localhost:3000"]
          interval: 30s
          timeout: 5s
          retries: 3
        networks:
          - frontend-net
        restart: unless-stopped
    
      backend:
        build: ./srcs/backend
        expose:
          - "8080"
        depends_on:
          db:
            condition: service_healthy
        env_file: .env
        networks:
          - frontend-net
          - backend-net
        restart: unless-stopped
    
      db:
        image: postgres:16-alpine
        volumes:
          - db-data:/var/lib/postgresql/data
        healthcheck:
          test: ["CMD-SHELL", "pg_isready -U $POSTGRES_USER"]
          interval: 10s
          timeout: 5s
          retries: 5
        networks:
          - backend-net
        restart: unless-stopped
  • srcs/backend/Dockerfile
    FROM eclipse-temurin:21-jre-alpine
    WORKDIR /app
    COPY target/*.jar app.jar
    
    HEALTHCHECK --interval=15s --timeout=5s --retries=3 \
      CMD wget -qO- http://localhost:8080/actuator/health || exit 1
    
    ENTRYPOINT ["java", "-jar", "app.jar"]
  • Makefile
    NAME    := ft_transcendence
    COMPOSE := docker compose
    
    .PHONY: all up down re logs clean fclean
    
    all: up
    
    up:
    	@echo "\033[32m[✓] Starting $(NAME)...\033[0m"
    	$(COMPOSE) up -d --build
    	@echo "\033[32m[✓] All services running.\033[0m"
    
    down:
    	$(COMPOSE) down
    
    re: down up
    
    logs:
    	$(COMPOSE) logs -f --tail=50
    
    clean: down
    	$(COMPOSE) down --rmi local -v
    
    fclean: clean
    	docker system prune -af --volumes