<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ege Bilge on Medium]]></title>
        <description><![CDATA[Stories by Ege Bilge on Medium]]></description>
        <link>https://medium.com/@egebilge?source=rss-2d7b511b69e7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KClqyfjM94QjCyIjwYsM2Q.jpeg</url>
            <title>Stories by Ege Bilge on Medium</title>
            <link>https://medium.com/@egebilge?source=rss-2d7b511b69e7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 14:34:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@egebilge/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Stale Closure Trap in React’s Batched World]]></title>
            <link>https://egebilge.medium.com/the-stale-closure-trap-in-reacts-batched-world-c19c2ccbb85a?source=rss-2d7b511b69e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c19c2ccbb85a</guid>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[staleclosure]]></category>
            <dc:creator><![CDATA[Ege Bilge]]></dc:creator>
            <pubDate>Tue, 03 Mar 2026 11:55:34 GMT</pubDate>
            <atom:updated>2026-03-03T11:55:34.627Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>TL;DR:</strong> Stale closures capture outdated state snapshots. React’s automatic batching (v18+) collapses multiple state updates into one render — which interacts with closures in ways that will surprise you if you’re not paying attention.</p><h3>How It Works</h3><p><strong>Stale closure</strong> — a function closes over a variable at definition time. If state updates happen after, the function still references the old value.</p><p><strong>React batching</strong> — React groups multiple setState calls into a single re-render. In v18+, this applies everywhere: event handlers, setTimeout, Promise chains, native event listeners. Previously, only React synthetic event handlers were batched.</p><pre>const [count, setCount] = useState(0);<br>// ...<br>useEffect(() =&gt; {<br>  const id = setInterval(() =&gt; {<br>    console.log(count); // Always logs 0 — stale closure<br>    setCount(count + 1); // Increments from 0 every time<br>  }, 1000);<br>  return () =&gt; clearInterval(id);<br>}, []); // Empty dep array = closure captures initial count</pre><p>The interval’s callback never sees updated count. Each tick reads the same 0.</p><h3>Where Batching Makes This Worse</h3><p>Before v18, async code wasn’t batched. You’d get intermediate renders that could “refresh” closures via component re-renders. With v18’s automatic batching, async code is now batched too — so closures in async contexts stay stale longer.</p><pre>const handleClick = async () =&gt; {<br>  // v18: all three updates batched into ONE render<br>  setA(a + 1); // stale `a`<br>  setB(b + 1); // stale `b`<br>  setC(c + 1); // stale `c`<br>  // Component renders once here with all three changes<br>  // Between these lines, `a`, `b`, `c` are still the old values<br>};</pre><p>This is usually a feature. But if your logic depends on reading updated state mid-function, you’re reading stale closures between those lines.</p><p><strong>The real trap:</strong> combining batching with useCallback or useMemo.</p><pre>const increment = useCallback(() =&gt; {<br>  setCount(count + 1); // Stale if deps are wrong<br>}, []); // Missing `count` in deps<br>// ...<br>const batchedOp = useCallback(async () =&gt; {<br>  await someApi();<br>  increment(); // Calls the stale version of increment<br>  increment(); // Both calls increment from the same old `count`<br>}, [increment]);</pre><p>Both increment() calls operate on the same captured count. Result: +1 instead of +2.</p><h3>The Fix Patterns</h3><p><strong>Functional updater form</strong> — reads current state at call time, not closure capture time:</p><pre>// Instead of:<br>setCount(count + 1);<br>// Use:<br>setCount(prev =&gt; prev + 1); // `prev` is always fresh</pre><p>This is the correct fix for the interval case and any accumulative updates.</p><p><strong>useRef for values you need to read in callbacks without re-subscribing:</strong></p><pre>const countRef = useRef(count);<br>useEffect(() =&gt; { countRef.current = count; }, [count]);<br>// ...<br>const callback = useCallback(() =&gt; {<br>  console.log(countRef.current); // Always fresh<br>}, []); // No dep needed</pre><p>Use this for callbacks passed to non-React systems (WebSockets, native event listeners, third-party libs) where you can’t update the callback reference easily.</p><p><strong>flushSync to opt out of batching when you explicitly need intermediate state:</strong></p><pre>import { flushSync } from &quot;react-dom&quot;;<br>// ...<br>flushSync(() =&gt; setCount(c =&gt; c + 1)); // Forces a synchronous render<br>const freshCount = countRef.current;   // Now readable if you sync via ref</pre><p><strong>Warning:</strong> flushSync is a last resort. Overuse kills performance. Default to functional updaters.</p><h3>Wrapping Up</h3><p>Stale closures are a React primitive — they’re not a bug in React, they’re a consequence of how JavaScript closures work combined with React’s render cycle. Automatic batching in v18 extended the surface area where you’ll encounter them. The functional updater pattern (prev =&gt; prev + 1) solves 90% of cases. The ref pattern covers the rest.</p><p><strong>Understand the closure’s “birth time” and you’ll never be surprised by what it reads.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c19c2ccbb85a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js Data Flow Demystified: SSR, Client Boundaries, and the Proxy Pattern]]></title>
            <link>https://egebilge.medium.com/next-js-data-flow-demystified-ssr-client-boundaries-and-the-proxy-pattern-2d3a1cde87c4?source=rss-2d7b511b69e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d3a1cde87c4</guid>
            <category><![CDATA[ssrs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Ege Bilge]]></dc:creator>
            <pubDate>Sun, 22 Feb 2026 19:54:30 GMT</pubDate>
            <atom:updated>2026-02-22T19:54:30.585Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>TL;DR:</strong> Next.js App Router gives you server-first rendering by default. &#39;use client&#39; opts a component into the browser bundle. &#39;use server&#39; marks functions that run exclusively on the server. The Proxy API pattern hides your backend URLs and credentials from the client entirely.</p><h3>How Server-Side Rendering Works in Next.js</h3><p>Every component in the App Router is a <strong>React Server Component (RSC)</strong> by default. It renders on the server, sends HTML to the browser, and never ships its code to the client bundle.</p><pre>// app/products/page.tsx — runs ONLY on the server<br>export default async function ProductsPage() {<br>  const data = await fetch(&#39;&lt;https://internal-api.company.com/products&gt;&#39;, {<br>    headers: { Authorization: `Bearer ${process.env.INTERNAL_API_KEY}` },<br>  });<br>  const products = await data.json();<br>  return &lt;ProductList items={products} /&gt;;<br>}</pre><p>Key behaviors:</p><ul><li><strong>async/await at the component level</strong> — you can fetch data directly in JSX</li><li><strong>No hydration cost</strong> — server components send zero JS to the client</li><li><strong>Environment variables without </strong><strong>NEXT_PUBLIC_</strong> — stay server-only, never leak</li><li><strong>No access to browser APIs</strong> — window, localStorage, event handlers are unavailable</li></ul><h3>&#39;use client&#39; — Crossing the Client Boundary</h3><p>Adding &#39;use client&#39; at the top of a file tells Next.js to include that module in the browser bundle. Everything below the boundary becomes interactive.</p><pre>&#39;use client&#39;;<br>// app/components/AddToCart.tsx<br>import { useState } from &#39;react&#39;;<br>export function AddToCart({ productId }: { productId: string }) {<br>  const [added, setAdded] = useState(false);<br>  return (<br>    &lt;button onClick={() =&gt; setAdded(true)}&gt;<br>      {added ? &#39;Added!&#39; : &#39;Add to Cart&#39;}<br>    &lt;/button&gt;<br>  );<br>}</pre><p>Rules to remember:</p><ul><li><strong>Boundary is per file</strong> — not per component; the entire file becomes a client module</li><li><strong>Children can still be RSCs</strong> — pass them as children props from a server parent</li><li><strong>Props must be serializable</strong> — no functions, class instances, or Dates across the boundary</li><li><strong>Hooks require this directive</strong> — useState, useEffect, useContext all need it</li></ul><p>A common mistake is marking a layout or a large page as &#39;use client&#39; just to handle one click. Instead, extract only the interactive leaf into its own file.</p><h3>&#39;use server&#39; — Server Functions Called from the Client</h3><p>&#39;use server&#39; creates <strong>Server Actions</strong>: async functions that execute on the server but can be invoked from client components like regular async calls. They are the replacement for writing dedicated API routes for mutations.</p><pre>// app/actions/cart.ts<br>&#39;use server&#39;;<br>import { revalidatePath } from &#39;next/cache&#39;;<br>import { db } from &#39;@/lib/db&#39;;<br>export async function addToCart(productId: string, userId: string) {<br>  await db.cart.upsert({ where: { userId }, data: { productId } });<br>  revalidatePath(&#39;/cart&#39;);<br>}</pre><pre>&#39;use client&#39;;<br>// Calling the server action from a client component<br>import { addToCart } from &#39;@/app/actions/cart&#39;;<br>export function BuyButton({ productId, userId }: Props) {<br>  return (<br>    &lt;button onClick={() =&gt; addToCart(productId, userId)}&gt;<br>      Buy Now<br>    &lt;/button&gt;<br>  );<br>}</pre><p>What happens under the hood:</p><ul><li><strong>Next.js creates a POST endpoint</strong> automatically for each Server Action</li><li><strong>Arguments are serialized</strong> via a secure POST request — no manual fetch needed</li><li><strong>revalidatePath / </strong><strong>revalidateTag</strong> let you bust the cache after mutations</li><li><strong>CSRF protection is built in</strong> — actions only accept requests from the same origin</li></ul><p><strong>Warning:</strong> Server Actions are public HTTP endpoints. Always validate and authorize inputs server-side — never trust the caller.</p><h3>The Proxy API Pattern</h3><p>Even with RSCs, you sometimes need a dedicated HTTP endpoint — for webhooks, third-party OAuth callbacks, or client-side polling. The Proxy API pattern uses Next.js Route Handlers as a thin layer that forwards requests to your real backend, keeping upstream URLs and secrets invisible to the browser.</p><pre>// app/api/products/route.ts<br>import { NextRequest, NextResponse } from &#39;next/server&#39;;<br>const UPSTREAM = process.env.INTERNAL_API_BASE_URL!;<br>const API_KEY  = process.env.INTERNAL_API_KEY!;<br>export async function GET(request: NextRequest) {<br>  const { searchParams } = request.nextUrl;<br>  const upstream = await fetch(`${UPSTREAM}/products?${searchParams}`, {<br>    headers: {<br>      Authorization: `Bearer ${API_KEY}`,<br>      &#39;Content-Type&#39;: &#39;application/json&#39;,<br>    },<br>    cache: &#39;no-store&#39;,<br>  });<br>  if (!upstream.ok) {<br>    return NextResponse.json({ error: &#39;Upstream error&#39; }, { status: upstream.status });<br>  }<br>  const data = await upstream.json();<br>  return NextResponse.json(data);<br>}</pre><p>The client calls /api/products — it never sees INTERNAL_API_BASE_URL or the bearer token.</p><h3>When to Use Each Pattern</h3><ul><li><strong>RSC fetch</strong> — read-only data needed at render time; fastest path, no round-trip</li><li><strong>Server Action</strong> — form submissions, mutations, anything triggered by user interaction</li><li><strong>Route Handler (Proxy)</strong> — webhooks, SSE streams, polling from client JS, third-party OAuth</li><li><strong>&#39;use client&#39; + SWR/React Query</strong> — data that must refresh in real time without a full page reload</li></ul><h3>Adding Auth and Rate Limiting to the Proxy</h3><pre>// app/api/products/route.ts (extended)<br>import { getServerSession } from &#39;next-auth&#39;;<br>import { authOptions } from &#39;@/lib/auth&#39;;<br>export async function GET(request: NextRequest) {<br>  const session = await getServerSession(authOptions);<br>  if (!session) {<br>    return NextResponse.json({ error: &#39;Unauthorized&#39; }, { status: 401 });<br>  }<br>  // ...forward to upstream<br>}</pre><p>Centralizing auth in the proxy means your upstream service trusts the Next.js layer and needs no per-client token validation.</p><h3>The Mental Model</h3><pre>Browser<br>  └─ &#39;use client&#39; components   ← interactive, hydrated, in the JS bundle<br>       └─ calls Server Actions  ← POST to auto-generated endpoint, runs on server<br>       └─ calls /api/* routes   ← proxy hides upstream URLs and secrets<br>Server<br>  └─ React Server Components   ← rendered to HTML, never sent as JS<br>       └─ direct DB / API calls ← env secrets safe, no client exposure</pre><p>The boundary between server and client is a <strong>trust boundary</strong>, not just a performance optimization. Code on the server can hold secrets; code in &#39;use client&#39; cannot.</p><h3>Wrapping Up</h3><p>Next.js App Router’s server-first model flips the traditional SPA mental model: start on the server, opt into the client only where interactivity demands it. Server Actions eliminate boilerplate API routes for mutations, while the Proxy pattern gives you a clean choke-point for auth, rate limiting, and secret management.</p><p>As the ecosystem matures, the lines between RSC, Server Actions, and Route Handlers will sharpen further — understanding each tool’s job now means you’ll write less code and ship more secure applications.</p><p><strong>“Ship server-first, opt into the client deliberately, and never let a secret touch the browser bundle.”</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d3a1cde87c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js’i Docker ile Production’a Taşımak: Adım Adım Rehber]]></title>
            <link>https://egebilge.medium.com/next-jsi-docker-ile-production-a-ta%C5%9F%C4%B1mak-ad%C4%B1m-ad%C4%B1m-rehber-f095eb55503a?source=rss-2d7b511b69e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f095eb55503a</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <dc:creator><![CDATA[Ege Bilge]]></dc:creator>
            <pubDate>Sun, 22 Feb 2026 19:28:42 GMT</pubDate>
            <atom:updated>2026-02-22T19:28:42.426Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>TL;DR:</strong> Next.js’i Docker’a taşırken output: &quot;standalone&quot; ayarı kritiktir — image boyutunu ~500MB&#39;den ~150MB&#39;ye düşürür. Multi-stage Dockerfile ile minimal production image oluşturun, docker-compose ile servisleri orkestre edin.</p><h3>Next.js Konfigürasyonu</h3><p>Docker ile çalışmadan önce next.config.ts&#39;de tek ama kritik bir değişiklik gerekiyor:</p><pre>import type { NextConfig } from &quot;next&quot;;<br>const nextConfig: NextConfig = {<br>  output: &quot;standalone&quot;,<br>};<br>export default nextConfig;</pre><p>standalone ne yapar:</p><ul><li>node_modules&#39;ın tamamı yerine sadece gereken dosyaları .next/standalone altına kopyalar</li><li>Kendi içinde server.js üretir — next start&#39;a gerek kalmaz</li><li>Image boyutu: <strong>~500MB → ~150MB</strong></li></ul><p><strong>Dikkat:</strong> standalone olmadan Docker image&#39;ınız tüm node_modules&#39;ı taşır. Bu hem boyut hem de güvenlik açısından kötüdür.</p><h3>.dockerignore</h3><p>Build context’ini küçük tutmak için mutlaka ekleyin:</p><pre>node_modules<br>.next<br>.git<br>*.md<br>.env*.local</pre><h3>Dockerfile (Multi-Stage Build)</h3><pre># 1. Dependencies — sadece paketleri kur<br>FROM node:20-alpine AS deps<br>WORKDIR /app<br>COPY package.json package-lock.json* ./<br>RUN npm ci<br># 2. Builder — uygulamayı derle<br>FROM node:20-alpine AS builder<br>WORKDIR /app<br>COPY --from=deps /app/node_modules ./node_modules<br>COPY . .<br>RUN npm run build<br># 3. Runner — sadece production çıktısını taşı<br>FROM node:20-alpine AS runner<br>WORKDIR /app<br>ENV NODE_ENV=production<br>ENV NEXT_TELEMETRY_DISABLED=1<br>RUN addgroup --system --gid 1001 nodejs<br>RUN adduser --system --uid 1001 nextjs<br>COPY --from=builder /app/.next/standalone ./<br>COPY --from=builder /app/.next/static ./.next/static<br>COPY --from=builder /app/public ./public<br>USER nextjs<br>EXPOSE 3000<br>ENV PORT=3000<br>ENV HOSTNAME=&quot;0.0.0.0&quot;<br>CMD [&quot;node&quot;, &quot;server.js&quot;]</pre><h3>Neden 3 Stage?</h3><ul><li><strong>deps</strong> — npm ci çalıştırır. package.json değişmedikçe Docker cache&#39;ten gelir, her build&#39;de tekrar inmez</li><li><strong>builder</strong> — next build çalıştırır. Dev dependencies dahildir ama sonraki stage&#39;e taşınmaz</li><li><strong>runner</strong> — Sadece standalone çıktısı + static + public. Minimal, güvenli, ~150MB</li></ul><p><strong>Not:</strong> USER nextjs satırı önemli. Container&#39;ı root yerine kısıtlı kullanıcıyla çalıştırır — production güvenliği için şart.</p><h3>Docker Compose — Basit Yapı</h3><p>Next.js + PostgreSQL için yeterli bir başlangıç:</p><pre>services:<br>  app:<br>    build: .<br>    ports:<br>      - &quot;3000:3000&quot;<br>    environment:<br>      - DATABASE_URL=postgresql://user:pass@db:5432/mydb<br>    depends_on:<br>      db:<br>        condition: service_healthy<br>  db:<br>    image: postgres:16-alpine<br>    environment:<br>      POSTGRES_USER: user<br>      POSTGRES_PASSWORD: pass<br>      POSTGRES_DB: mydb<br>    volumes:<br>      - postgres_data:/var/lib/postgresql/data<br>    healthcheck:<br>      test: [&quot;CMD-SHELL&quot;, &quot;pg_isready -U user&quot;]<br>      interval: 5s<br>      timeout: 5s<br>      retries: 5<br>volumes:<br>  postgres_data:</pre><p><strong>Önemli:</strong> DATABASE_URL&#39;de host olarak localhost değil servis adını (db) yazın. Docker network&#39;ünde container&#39;lar birbirini servis adıyla bulur.</p><h3>Docker Compose — Full Stack</h3><p>Next.js + PostgreSQL + Redis ile production-ready yapı:</p><pre>services:<br>  app:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>    ports:<br>      - &quot;3000:3000&quot;<br>    env_file:<br>      - .env.production<br>    depends_on:<br>      db:<br>        condition: service_healthy<br>      redis:<br>        condition: service_started<br>    restart: unless-stopped<br>  db:<br>    image: postgres:16-alpine<br>    environment:<br>      POSTGRES_USER: ${DB_USER}<br>      POSTGRES_PASSWORD: ${DB_PASSWORD}<br>      POSTGRES_DB: ${DB_NAME}<br>    volumes:<br>      - postgres_data:/var/lib/postgresql/data<br>    ports:<br>      - &quot;5432:5432&quot;<br>    healthcheck:<br>      test: [&quot;CMD-SHELL&quot;, &quot;pg_isready -U ${DB_USER}&quot;]<br>      interval: 5s<br>      timeout: 5s<br>      retries: 5<br>    restart: unless-stopped<br>  redis:<br>    image: redis:7-alpine<br>    ports:<br>      - &quot;6379:6379&quot;<br>    volumes:<br>      - redis_data:/data<br>    restart: unless-stopped<br>volumes:<br>  postgres_data:<br>  redis_data:</pre><h3>Environment Variables Yönetimi</h3><p>Next.js’te iki tür env var vardır ve Docker’da davranışları çok farklıdır:</p><ul><li><strong>NEXT_PUBLIC_*</strong> — Build-time&#39;da client bundle&#39;a yazılır. Runtime&#39;da değiştirilemez. Her ortam için ayrı build gerekir.</li><li><strong>Server-side env</strong> — Runtime’da okunur. docker-compose.yml veya env_file ile geçirilir, build&#39;e bağlı değildir.</li></ul><p>Build-time env’leri Dockerfile’a geçirmek için:</p><pre># docker-compose.yml<br>services:<br>  app:<br>    build:<br>      context: .<br>      args:<br>        - NEXT_PUBLIC_API_URL=https://api.example.com</pre><pre># Dockerfile — builder stage&#39;ine ekleyin<br>ARG NEXT_PUBLIC_API_URL<br>ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL</pre><p><strong>Uyarı:</strong> NEXT_PUBLIC_* değişkenleri docker-compose.yml&#39;deki environment bölümüne yazsanız bile çalışmaz — çünkü build sırasında bake edilir, runtime&#39;da okunmaz.</p><h3>Sık Kullanılan Komutlar</h3><pre>docker compose up -d --build        # Build &amp; çalıştır<br>docker compose logs -f app          # Logları izle<br>docker compose build --no-cache app # Cache&#39;siz yeniden build<br>docker compose restart app          # Sadece app&#39;i yeniden başlat<br>docker compose down -v              # Volume&#39;lar dahil her şeyi sil</pre><h3>Yaygın Sorunlar ve Çözümleri</h3><ul><li><strong>ECONNREFUSED DB bağlantısında</strong> — DATABASE_URL&#39;de localhost yerine servis adını (db) yazın. Container&#39;lar arası iletişim Docker DNS üzerinden çalışır.</li><li><strong>Image boyutu ~1GB+</strong> — next.config.ts&#39;de output: &quot;standalone&quot; eksik. Ekleyin, image 5-6x küçülür.</li><li><strong>public/ dosyaları 404 veriyor</strong> — Standalone mode public klasörünü otomatik kopyalamaz. Dockerfile&#39;da COPY --from=builder /app/public ./public satırını ekleyin.</li><li><strong>NEXT_PUBLIC_* env değişkenleri boş</strong> — Runtime&#39;da set edilmiş ama bu değişkenler build sırasında bake edilir. ARG + ENV ile build stage&#39;inde geçirin.</li><li><strong>Hot reload çalışmıyor (dev)</strong> — Production Dockerfile’ı dev için uygun değil. Ayrı bir docker-compose.dev.yml ile volume mount yapın:</li></ul><pre># docker-compose.dev.yml<br>services:<br>  app:<br>    build:<br>      target: deps<br>    command: npm run dev<br>    volumes:<br>      - .:/app<br>      - /app/node_modules<br>    ports:<br>      - &quot;3000:3000&quot;</pre><h3>Sonuç</h3><p>Next.js + Docker kurulumunda işin %80&#39;i iki şeye bağlı: output: &quot;standalone&quot; ayarı ve multi-stage Dockerfile. Bu ikisini doğru yapılandırdığınızda image boyutu düşer, build cache verimli çalışır ve production&#39;a güvenle deploy edebilirsiniz. Geri kalanı — compose, env yönetimi, healthcheck — bu temel üzerine eklenen detaylardır.</p><p><strong>“Standalone bir satırlık bir config değişikliği, ama production’da yüzlerce megabyte’lık fark yaratır.”</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f095eb55503a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding "use client" in Next.js]]></title>
            <link>https://egebilge.medium.com/understanding-use-client-in-next-js-33ae0a8e21c2?source=rss-2d7b511b69e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/33ae0a8e21c2</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Ege Bilge]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 11:12:46 GMT</pubDate>
            <atom:updated>2025-12-23T11:12:46.081Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s Clear Up a Common &quot;use client&quot; Myth in Next.js</h3><p>This comes up <em>a lot</em> in interviews, so let’s talk about it.</p><p>One of the most common misconceptions about Next.js is this idea that <strong>Client Components are not rendered on the server</strong>.<br>Sounds reasonable at first… but it’s actually wrong.</p><p>Straight from the official Next.js docs:</p><blockquote><strong><em>“Client Components and the RSC Payload are used to pre-render HTML.”</em></strong></blockquote><p>Yep — even Client Components are pre-rendered.</p><h3>So… What Does &quot;use client&quot; Actually Do?</h3><p>When you add &quot;use client&quot; to a component, you’re <strong>not</strong> telling Next.js:</p><blockquote><em>“Hey, render this only in the browser.”</em></blockquote><p>What you’re really saying is:</p><ul><li>“I need browser features here” (useState, useEffect, click handlers, etc.)</li><li>“This component should be <strong>hydrated</strong> on the client”</li><li>“But yes, you can still pre-render its HTML on the server”</li></ul><p>So the server sends HTML first (good for performance and SEO), and then the browser takes over to make it interactive. Best of both worlds.</p><h3>Okay, But What If I Really Want Client-Only?</h3><p>Good question — and this is where many people get tripped up.</p><p>If you want a component to <strong>skip the server entirely</strong> and render only in the browser, you need:</p><pre>import dynamic from &quot;next/dynamic&quot;;<br><br>const ClientOnlyComponent = dynamic(() =&gt; import(&quot;./Component&quot;), {<br>  ssr: false,<br>});</pre><p>That’s the <em>real</em> “client-only” switch.</p><h3>Quick Recap</h3><ul><li>&quot;use client&quot; does <strong>not</strong> mean “no server rendering”</li><li>Client Components <strong>are still pre-rendered</strong></li><li>next/dynamic + ssr: false = browser-only rendering</li></ul><p>Once you get this mental model right, Next.js suddenly makes a lot more sense 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33ae0a8e21c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Race Condition Zafiyetleri ve Önleme Rehberi]]></title>
            <link>https://egebilge.medium.com/race-condition-zafiyetleri-ve-%C3%B6nleme-rehberi-e2d6c20b4e84?source=rss-2d7b511b69e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2d6c20b4e84</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[race-condition]]></category>
            <category><![CDATA[drizzleorm]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Ege Bilge]]></dc:creator>
            <pubDate>Fri, 10 Oct 2025 08:21:28 GMT</pubDate>
            <atom:updated>2025-10-10T08:21:28.527Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Stack:</strong> Next.js, TypeScript, Drizzle ORM, PostgreSQL</p><h3>İçindekiler</h3><ol><li>Race Condition Nedir?</li><li>Kritik Senaryolar</li><li>Atomik İşlemler ve Transaction’lar</li><li>SELECT FOR UPDATE ile Satır Kilitleme</li><li>E-posta Değiştirme Güvenlik Açığı</li><li>Password Reset Race Condition</li><li>Finansal İşlemler</li><li>Mikroservis ve State Yönetimi</li><li>Geliştirici Zihniyeti</li><li>Best Practices</li></ol><h3>Race Condition Nedir?</h3><p>Race condition, iki veya daha fazla eşzamanlı işlemin aynı kaynağa erişmeye çalıştığında, işlemlerin zamanlamasına bağlı olarak beklenmeyen sonuçlar üretmesidir. Web uygulamalarında bu, özellikle yüksek trafikte veya kasıtlı saldırılarda kritik güvenlik açıklarına yol açabilir.</p><p><strong>Basit Örnek:</strong></p><pre>// ❌ ZAFIYET: Race condition var<br>async function increaseBalance(userId: string, amount: number) {<br>  const user = await db.select().from(users).where(eq(users.id, userId));<br>  const newBalance = user[0].balance + amount;<br>  await db.update(users)<br>    .set({ balance: newBalance })<br>    .where(eq(users.id, userId));<br>}</pre><pre>// İki istek aynı anda gelirse:<br>// İstek 1: balance = 100 okuyor, +50 ekliyor → 150 yazacak<br>// İstek 2: balance = 100 okuyor, +30 ekliyor → 130 yazacak<br>// Sonuç: 130 (50 TL kaybedildi!)</pre><h3>Kritik Senaryolar</h3><h3>1. Finansal İşlemler</h3><ul><li>Para transferleri</li><li>Bakiye güncellemeleri</li><li>Ödeme işlemleri</li><li>Kupon/promosyon kullanımı</li></ul><h3>2. Kimlik ve Doğrulama</h3><ul><li>E-posta değiştirme</li><li>Password reset</li><li>2FA token doğrulama</li><li>Session yönetimi</li></ul><h3>3. Envanter Yönetimi</h3><ul><li>Stok güncellemeleri</li><li>Ürün rezervasyonu</li><li>Sınırlı sayıda kaynak tahsisi</li></ul><h3>4. Metrik ve Sayaçlar</h3><ul><li>View count</li><li>Like/favorite sayısı</li><li>Rate limiting</li></ul><h3>Atomik İşlemler ve Transaction’lar</h3><p>Drizzle ORM ile PostgreSQL transaction’larını kullanarak kritik mantığı atomik hale getirebilirsiniz.</p><h3>Temel Transaction Kullanımı</h3><pre>import { db } from &#39;@/lib/db&#39;;<br>import { users, transactions as txTable } from &#39;@/lib/schema&#39;;<br>import { eq } from &#39;drizzle-orm&#39;;<br><br>// ✅ GÜVENLİ: Transaction ile atomik işlem<br>export async function transferMoney(<br>  fromUserId: string,<br>  toUserId: string,<br>  amount: number<br>) {<br>  return await db.transaction(async (tx) =&gt; {<br>    // Gönderen kullanıcının bakiyesini kontrol et ve güncelle<br>    const [sender] = await tx<br>      .select()<br>      .from(users)<br>      .where(eq(users.id, fromUserId))<br>      .for(&#39;update&#39;); // Satır kilidi!<br>    if (sender.balance &lt; amount) {<br>      throw new Error(&#39;Yetersiz bakiye&#39;);<br>    }<br>    // Gönderenin bakiyesini azalt<br>    await tx<br>      .update(users)<br>      .set({ balance: sender.balance - amount })<br>      .where(eq(users.id, fromUserId));<br>    // Alıcının bakiyesini artır<br>    await tx<br>      .update(users)<br>      .set({ balance: users.balance + amount })<br>      .where(eq(users.id, toUserId));<br>    // İşlem kaydı oluştur<br>    await tx.insert(txTable).values({<br>      fromUserId,<br>      toUserId,<br>      amount,<br>      timestamp: new Date(),<br>    });<br>    // Transaction başarılı - tümü birden commit edilir<br>    return { success: true };<br>  });<br>}</pre><p><strong>Önemli Notlar:</strong></p><ul><li>db.transaction() içindeki TÜM işlemler ya hep birden başarılı olur, ya hep birden geri alınır</li><li>Bir hata fırlatılırsa otomatik ROLLBACK yapılır</li><li>Transaction içinde tx nesnesini kullanın, db değil</li></ul><h3>SELECT FOR UPDATE ile Satır Kilitleme</h3><p>PostgreSQL’de SELECT FOR UPDATE, okuduğunuz satırları güncelleme yapılana kadar kilitler. Bu, eşzamanlı yazma çatışmalarını engeller.</p><h3>Drizzle ORM ile FOR UPDATE</h3><pre>import { db } from &#39;@/lib/db&#39;;<br>import { products, orders } from &#39;@/lib/schema&#39;;<br>import { eq } from &#39;drizzle-orm&#39;;<br><br>// ✅ GÜVENLİ: Stok kontrolü ve güncelleme atomik<br>export async function purchaseProduct(productId: string, quantity: number) {<br>  return await db.transaction(async (tx) =&gt; {<br>    // Ürünü kilitle ve oku<br>    const [product] = await tx<br>      .select()<br>      .from(products)<br>      .where(eq(products.id, productId))<br>      .for(&#39;update&#39;); // Satır kilidi - diğer transaction&#39;lar bekleyecek<br>    if (!product) {<br>      throw new Error(&#39;Ürün bulunamadı&#39;);<br>    }<br>    if (product.stock &lt; quantity) {<br>      throw new Error(&#39;Stok yetersiz&#39;);<br>    }<br>    // Stoku güncelle<br>    await tx<br>      .update(products)<br>      .set({ stock: product.stock - quantity })<br>      .where(eq(products.id, productId));<br>    // Sipariş oluştur<br>    const [order] = await tx<br>      .insert(orders)<br>      .values({<br>        productId,<br>        quantity,<br>        totalPrice: product.price * quantity,<br>      })<br>      .returning();<br>    return order;<br>  });<br>}</pre><h3>FOR UPDATE Varyasyonları</h3><pre>// NOWAIT: Kilit varsa hemen hata döndür (beklemez)<br>await tx.select().from(users).where(eq(users.id, userId)).for(&#39;update&#39;, { noWait: true });<br>// SKIP LOCKED: Kilitli satırları atla<br>await tx.select().from(users).where(eq(users.id, userId)).for(&#39;update&#39;, { skipLocked: true });</pre><h3>E-posta Değiştirme Güvenlik Açığı</h3><p>GitLab zafiyet örneği: Asenkron mail gönderme servisi eski state’i okurken, saldırgan eşzamanlı istekle e-postayı tekrar değiştirebiliyor.</p><h3>Zafiyetli Kod</h3><pre>// ❌ ZAFIYET VAR<br>export async function changeEmail(userId: string, newEmail: string) {<br>  // 1. E-postayı güncelle<br>  await db.update(users)<br>    .set({<br>      email: newEmail,<br>      emailVerified: false<br>    })<br>    .where(eq(users.id, userId));<br>  // 2. Token oluştur<br>    const token = generateToken();<br>    await db.insert(emailVerificationTokens).values({<br>      userId,<br>      token,<br>      expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),<br>    });<br>    // 3. Asenkron mail gönderme (BURADA PROBLEM!)<br>    const user = await db.select().from(users).where(eq(users.id, userId));<br>    await sendVerificationEmail(user[0].email, token);<br>    // Saldırgan burada ikinci bir istek gönderirse:<br>    // - user[0].email hala eski değerde olabilir<br>    // - Veya yeni değer okunup mail saldırgana gidebilir<br>}</pre><h3>Güvenli Çözüm</h3><pre>// ✅ GÜVENLİ: Transaction + Atomik state<br>export async function changeEmail(userId: string, newEmail: string) {<br>  return await db.transaction(async (tx) =&gt; {<br>    // 1. Kullanıcıyı kilitle ve oku<br>    const [user] = await tx<br>      .select()<br>      .from(users)<br>      .where(eq(users.id, userId))<br>      .for(&#39;update&#39;);<br>      // 2. Pending email değişikliği varsa iptal et<br>    await tx<br>      .delete(emailVerificationTokens)<br>      .where(eq(emailVerificationTokens.userId, userId));<br>    // 3. Token oluştur VE yeni e-postayı birlikte sakla<br>    const token = generateToken();<br>    const [verificationRecord] = await tx<br>      .insert(emailVerificationTokens)<br>      .values({<br>        userId,<br>        token,<br>        newEmail, // ✅ Yeni e-postayı token ile birlikte sakla<br>        oldEmail: user.email,<br>        expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),<br>        status: &#39;pending&#39;,<br>      })<br>      .returning();<br>    // Transaction commit oldu - artık mail gönderebiliriz<br>    // Mail gönderme transaction dışında, ama doğru email&#39;i kullanıyoruz<br>    await sendVerificationEmail(newEmail, token);<br>    return { success: true };<br>  });<br>}<br><br>// Token doğrulama<br>export async function verifyEmailChange(token: string) {<br>  return await db.transaction(async (tx) =&gt; {<br>    const [verification] = await tx<br>      .select()<br>      .from(emailVerificationTokens)<br>      .where(eq(emailVerificationTokens.token, token))<br>      .for(&#39;update&#39;);<br>    if (!verification || verification.status !== &#39;pending&#39;) {<br>      throw new Error(&#39;Geçersiz token&#39;);<br>    }<br>    if (verification.expiresAt &lt; new Date()) {<br>      throw new Error(&#39;Token süresi dolmuş&#39;);<br>    }<br>    // E-postayı güncelle<br>    await tx<br>      .update(users)<br>      .set({<br>        email: verification.newEmail,<br>        emailVerified: true<br>      })<br>      .where(eq(users.id, verification.userId));<br>    // Token&#39;ı kullanılmış olarak işaretle<br>    await tx<br>      .update(emailVerificationTokens)<br>      .set({ status: &#39;used&#39; })<br>      .where(eq(emailVerificationTokens.id, verification.id));<br>    return { success: true };<br>  });<br>}</pre><p><strong>Önemli İyileştirmeler:</strong></p><ul><li>Yeni e-posta adresi token ile birlikte saklanıyor</li><li>Transaction içinde atomik state yönetimi</li><li>Pending token’lar siliniyor (aynı anda birden fazla değişiklik engelleniyor)</li><li>Mail gönderme transaction dışında ama doğru email kullanılıyor</li></ul><h3>Password Reset Race Condition</h3><h3>Zafiyetli Senaryo</h3><pre>// ❌ ZAFIYET<br>export async function requestPasswordReset(email: string) {<br>  const user = await db.select().from(users).where(eq(users.email, email));<br>  if (!user[0]) {<br>    return; // Güvenlik için kullanıcı yoksa bile hata verme<br>  }<br>  const token = generateResetToken();<br>  await db.insert(passwordResetTokens).values({<br>    userId: user[0].id,<br>    token,<br>    expiresAt: new Date(Date.now() + 1 * 60 * 60 * 1000), // 1 saat<br>  });<br>  await sendPasswordResetEmail(email, token);<br>}<br>// Saldırgan aynı anda 10 istek gönderirse 10 farklı token oluşur!</pre><h3>Güvenli Çözüm</h3><pre>// ✅ GÜVENLİ<br>export async function requestPasswordReset(email: string) {<br>  return await db.transaction(async (tx) =&gt; {<br>    const [user] = await tx<br>      .select()<br>      .from(users)<br>      .where(eq(users.email, email))<br>      .for(&#39;update&#39;);<br>      if (!user) {<br>      // Timing attack&#39;i önlemek için bekle<br>      await new Promise(resolve =&gt; setTimeout(resolve, 200));<br>      return { success: true };<br>    }<br>    // Mevcut tüm token&#39;ları iptal et<br>    await tx<br>      .update(passwordResetTokens)<br>      .set({ status: &#39;invalidated&#39; })<br>      .where(<br>        and(<br>          eq(passwordResetTokens.userId, user.id),<br>          eq(passwordResetTokens.status, &#39;active&#39;)<br>        )<br>      );<br>    // Yeni token oluştur<br>    const token = generateResetToken();<br>    const [resetRecord] = await tx<br>      .insert(passwordResetTokens)<br>      .values({<br>        userId: user.id,<br>        token,<br>        expiresAt: new Date(Date.now() + 1 * 60 * 60 * 1000),<br>        status: &#39;active&#39;,<br>      })<br>      .returning();<br>    // Rate limiting için kayıt tut<br>    await tx.insert(passwordResetAttempts).values({<br>      userId: user.id,<br>      attemptedAt: new Date(),<br>      ipAddress: getClientIP(),<br>    });<br>    await sendPasswordResetEmail(email, token);<br>    return { success: true };<br>  });<br>}<br><br><br>// Token kullanımı<br>export async function resetPassword(token: string, newPassword: string) {<br>  return await db.transaction(async (tx) =&gt; {<br>    const [resetRecord] = await tx<br>      .select()<br>      .from(passwordResetTokens)<br>      .where(eq(passwordResetTokens.token, token))<br>      .for(&#39;update&#39;);<br>    if (<br>      !resetRecord ||<br>      resetRecord.status !== &#39;active&#39; ||<br>      resetRecord.expiresAt &lt; new Date()<br>    ) {<br>      throw new Error(&#39;Geçersiz veya süresi dolmuş token&#39;);<br>    }<br>    // Şifreyi güncelle<br>    const hashedPassword = await hashPassword(newPassword);<br>    await tx<br>      .update(users)<br>      .set({<br>        passwordHash: hashedPassword,<br>        passwordChangedAt: new Date(),<br>      })<br>      .where(eq(users.id, resetRecord.userId));<br>    // Token&#39;ı kullanılmış olarak işaretle<br>    await tx<br>      .update(passwordResetTokens)<br>      .set({<br>        status: &#39;used&#39;,<br>        usedAt: new Date(),<br>      })<br>      .where(eq(passwordResetTokens.id, resetRecord.id));<br>    // Diğer tüm active token&#39;ları iptal et<br>    await tx<br>      .update(passwordResetTokens)<br>      .set({ status: &#39;invalidated&#39; })<br>      .where(<br>        and(<br>          eq(passwordResetTokens.userId, resetRecord.userId),<br>          eq(passwordResetTokens.status, &#39;active&#39;),<br>          not(eq(passwordResetTokens.id, resetRecord.id))<br>        )<br>      );<br>    return { success: true };<br>  });<br>}</pre><h3>Finansal İşlemler</h3><h3>Kupon/Promosyon Kullanımı</h3><pre>// ✅ GÜVENLİ: Sınırlı sayıda kupon<br>export async function applyCoupon(userId: string, couponCode: string) {<br>  return await db.transaction(async (tx) =&gt; {<br>    // Kuponu kilitle<br>    const [coupon] = await tx<br>      .select()<br>      .from(coupons)<br>      .where(eq(coupons.code, couponCode))<br>      .for(&#39;update&#39;);<br>      if (!coupon) {<br>      throw new Error(&#39;Kupon bulunamadı&#39;);<br>    }<br>    // Kullanım kontrolü<br>    if (coupon.usageCount &gt;= coupon.maxUsage) {<br>      throw new Error(&#39;Kupon kullanım limiti doldu&#39;);<br>    }<br>    if (coupon.expiresAt &lt; new Date()) {<br>      throw new Error(&#39;Kupon süresi dolmuş&#39;);<br>    }<br>    // Kullanıcı daha önce kullanmış mı?<br>    const [existingUsage] = await tx<br>      .select()<br>      .from(couponUsages)<br>      .where(<br>        and(<br>          eq(couponUsages.couponId, coupon.id),<br>          eq(couponUsages.userId, userId)<br>        )<br>      );<br>    if (existingUsage &amp;&amp; !coupon.allowMultipleUse) {<br>      throw new Error(&#39;Bu kuponu zaten kullandınız&#39;);<br>    }<br>    // Kupon kullanımını kaydet<br>    await tx.insert(couponUsages).values({<br>      couponId: coupon.id,<br>      userId,<br>      usedAt: new Date(),<br>    });<br>    // Kullanım sayısını artır<br>    await tx<br>      .update(coupons)<br>      .set({ usageCount: coupon.usageCount + 1 })<br>      .where(eq(coupons.id, coupon.id));<br>    return {<br>      success: true,<br>      discount: coupon.discountAmount<br>    };<br>  });<br>}</pre><h3>Bakiye İşlemleri (Artırma/Azaltma)</h3><pre>// ✅ GÜVENLİ: Doğrudan DB&#39;de hesaplama<br>export async function adjustBalance(<br>  userId: string,<br>  amount: number,<br>  reason: string<br>) {<br>  return await db.transaction(async (tx) =&gt; {<br>    // SQL seviyesinde atomik güncelleme<br>    const [user] = await tx<br>      .update(users)<br>      .set({<br>        balance: sql`${users.balance} + ${amount}` // ✅ Atomik!<br>      })<br>      .where(eq(users.id, userId))<br>      .returning();<br>      // Negatif bakiye kontrolü (isterse)<br>    if (user.balance &lt; 0) {<br>      throw new Error(&#39;Bakiye negatif olamaz&#39;);<br>    }<br>    // İşlem logu<br>    await tx.insert(balanceTransactions).values({<br>      userId,<br>      amount,<br>      reason,<br>      balanceAfter: user.balance,<br>      createdAt: new Date(),<br>    });<br>    return user;<br>  });<br>}</pre><h3>Mikroservis ve State Yönetimi</h3><h3>JWT ve Stateless Tasarım</h3><pre>// Next.js API Route<br>import { NextRequest, NextResponse } from &#39;next/server&#39;;<br>import { verifyJWT } from &#39;@/lib/auth&#39;;<br>export async function GET(request: NextRequest) {<br>  // JWT ile stateless auth<br>  const token = request.cookies.get(&#39;auth-token&#39;)?.value;<br>  if (!token) {<br>    return NextResponse.json({ error: &#39;Unauthorized&#39; }, { status: 401 });<br>  }<br>  try {<br>    // JWT decode - DB&#39;ye gitmeden user bilgisi<br>    const payload = await verifyJWT(token);<br>    // ⚠️ DİKKAT: JWT&#39;deki bilgiler stale olabilir!<br>    // Kritik işlemlerde DB&#39;den güncel veriyi kontrol et<br>    if (isCriticalOperation(request)) {<br>      // Kritik işlem - DB&#39;den doğrula<br>      const [user] = await db<br>        .select()<br>        .from(users)<br>        .where(eq(users.id, payload.userId))<br>        .for(&#39;update&#39;);<br>      if (user.isBanned || !user.emailVerified) {<br>        return NextResponse.json(<br>          { error: &#39;Account suspended&#39; },<br>          { status: 403 }<br>        );<br>      }<br>    }<br>    // İşlemi gerçekleştir<br>    return NextResponse.json({ data: &#39;success&#39; });<br>  } catch (error) {<br>    return NextResponse.json({ error: &#39;Invalid token&#39; }, { status: 401 });<br>  }<br>}<br><br>function isCriticalOperation(request: NextRequest): boolean {<br>  const criticalPaths = [&#39;/api/payment&#39;, &#39;/api/transfer&#39;, &#39;/api/withdraw&#39;];<br>  return criticalPaths.some(path =&gt; request.nextUrl.pathname.startsWith(path));<br>}</pre><h3>Servis-Servis İletişim</h3><pre>// Servis A: Sipariş servisi<br>export async function createOrder(orderData: OrderData) {<br>  return await db.transaction(async (tx) =&gt; {<br>    // 1. Sipariş oluştur<br>    const [order] = await tx<br>      .insert(orders)<br>      .values(orderData)<br>      .returning();<br>      // 2. Stok servisini çağır (başka mikroservis)<br>    try {<br>      await fetch(&#39;&lt;http://inventory-service/api/reserve&gt;&#39;, {<br>        method: &#39;POST&#39;,<br>        headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>        body: JSON.stringify({<br>          orderId: order.id,<br>          productId: orderData.productId,<br>          quantity: orderData.quantity,<br>        }),<br>      });<br>    } catch (error) {<br>      // Stok rezervasyonu başarısız - transaction rollback<br>      throw new Error(&#39;Stok rezerve edilemedi&#39;);<br>    }<br>    // 3. Ödeme servisini çağır<br>    const paymentResult = await processPayment(order);<br>    if (!paymentResult.success) {<br>      throw new Error(&#39;Ödeme başarısız&#39;);<br>    }<br>    return order;<br>  });<br>}<br>// ⚠️ DİKKAT: Distributed transaction&#39;lar zor!<br>// Saga pattern veya eventual consistency düşünün</pre><h3>Geliştirici Zihniyeti</h3><h3>Her Branch’te Kritik Sorgula</h3><pre>// Her dal için kendine sor: &quot;Bu critical section mi?&quot;<br>export async function processRequest(userId: string, action: string) {<br>  const user = await getUser(userId);<br>  if (action === &#39;read-profile&#39;) {<br>    // ✅ Read-only - race condition riski yok<br>    return user.profile;<br>  }<br>  if (action === &#39;update-bio&#39;) {<br>    // ⚠️ Write ama kritik değil - rollback olsa sorun yok<br>    return await updateBio(userId, user.newBio);<br>  }<br>  if (action === &#39;transfer-money&#39;) {<br>    // 🚨 KRİTİK! Transaction + Lock gerekli<br>    return await db.transaction(async (tx) =&gt; {<br>      // Transaction içinde işle<br>    });<br>  }<br>}</pre><h3>Critical Section Kontrolü</h3><p><strong>İşletim sistemlerinden hatırlayın:</strong></p><pre>Critical Section = Aynı anda sadece bir thread&#39;in erişebileceği kod bloğu</pre><p><strong>Web’de:</strong></p><pre>Critical Section = Aynı anda sadece bir request&#39;in atomik çalıştırması gereken kod bloğu</pre><p><strong>Kontrol listesi:</strong></p><ul><li>[ ] Bu işlem para/varlık transfer ediyor mu?</li><li>[ ] Stok/envanter güncelliyor mu?</li><li>[ ] Tek kullanımlık bir kaynağı tüketiyor mu? (kupon, token)</li><li>[ ] İki okuma arasında veri değişirse problem olur mu?</li><li>[ ] Aynı işlem 2 kere çalışırsa veri bozulur mu?</li></ul><p>Herhangi biri EVET ise → Transaction + Lock kullan!</p><h3>Best Practices</h3><h3>1. Transaction Her Zaman Kullan</h3><pre>// ❌ KÖTÜ<br>async function updateUserData(userId: string, data: any) {<br>  await db.update(users).set(data).where(eq(users.id, userId));<br>  await db.insert(auditLog).values({ userId, action: &#39;update&#39; });<br>  // İkinci insert başarısız olursa user güncellendi ama log yok!<br>}<br><br>// ✅ İYİ<br>async function updateUserData(userId: string, data: any) {<br>  return await db.transaction(async (tx) =&gt; {<br>    await tx.update(users).set(data).where(eq(users.id, userId));<br>    await tx.insert(auditLog).values({ userId, action: &#39;update&#39; });<br>    // Her ikisi de başarılı olur veya hiçbiri olmaz<br>  });<br>}</pre><h3>2. SELECT FOR UPDATE Unutma</h3><pre>// Güncelleme yapacaksan önce kilitle<br>const [record] = await tx<br>  .select()<br>  .from(table)<br>  .where(eq(table.id, id))<br>  .for(&#39;update&#39;); // ✅ Kilit!<br><br>await tx.update(table).set({ ... }).where(eq(table.id, id));</pre><h3>3. Optimistic Locking (Version Control)</h3><pre>// Schema&#39;da version sütunu ekle<br>export const users = pgTable(&#39;users&#39;, {<br>  id: serial(&#39;id&#39;).primaryKey(),<br>  email: text(&#39;email&#39;).notNull(),<br>  balance: integer(&#39;balance&#39;).default(0),<br>  version: integer(&#39;version&#39;).default(1), // ✅ Version tracking<br>});<br><br>// Update yaparken version kontrol et<br>export async function updateUserOptimistic(<br>  userId: string,<br>  currentVersion: number,<br>  data: Partial&lt;User&gt;<br>) {<br>  const result = await db<br>    .update(users)<br>    .set({<br>      ...data,<br>      version: currentVersion + 1 // Version artır<br>    })<br>    .where(<br>      and(<br>        eq(users.id, userId),<br>        eq(users.version, currentVersion) // Mevcut version eşleşmeli<br>      )<br>    )<br>    .returning();<br>  if (result.length === 0) {<br>    throw new Error(&#39;Version conflict - data changed by another process&#39;);<br>  }<br>  return result[0];<br>}</pre><h3>4. Idempotency Keys (Tekrar İstek Güvenliği)</h3><pre>// Ödeme gibi kritik işlemlerde idempotency key kullan<br>export async function processPayment(<br>  userId: string,<br>  amount: number,<br>  idempotencyKey: string<br>) {<br>  return await db.transaction(async (tx) =&gt; {<br>    // Daha önce bu key ile işlem yapılmış mı?<br>    const [existing] = await tx<br>      .select()<br>      .from(payments)<br>      .where(eq(payments.idempotencyKey, idempotencyKey))<br>      .for(&#39;update&#39;);<br>    if (existing) {<br>      // Aynı işlem tekrar gelmiş - önceki sonucu döndür<br>      return existing;<br>    }<br>    // Yeni işlem<br>    const [payment] = await tx<br>      .insert(payments)<br>      .values({<br>        userId,<br>        amount,<br>        idempotencyKey,<br>        status: &#39;completed&#39;,<br>      })<br>      .returning();<br>    return payment;<br>  });<br>}<br><br><br>// Next.js API Route&#39;da kullanım<br>export async function POST(request: NextRequest) {<br>  const idempotencyKey = request.headers.get(&#39;idempotency-key&#39;)<br>    || crypto.randomUUID();<br>  const result = await processPayment(userId, amount, idempotencyKey);<br>  return NextResponse.json(result);<br>}</pre><h3>5. Rate Limiting Ekle</h3><pre>// Upstash Redis ile rate limiting<br>import { Ratelimit } from &#39;@upstash/ratelimit&#39;;<br>import { Redis } from &#39;@upstash/redis&#39;;<br>const redis = new Redis({<br>  url: process.env.UPSTASH_REDIS_URL!,<br>  token: process.env.UPSTASH_REDIS_TOKEN!,<br>});<br>const ratelimit = new Ratelimit({<br>  redis,<br>  limiter: Ratelimit.slidingWindow(5, &#39;1 m&#39;), // 1 dakikada 5 istek<br>});<br>export async function POST(request: NextRequest) {<br>  const ip = request.headers.get(&#39;x-forwarded-for&#39;) || &#39;unknown&#39;;<br>  const { success, limit, remaining } = await ratelimit.limit(<br>    `password-reset:${ip}`<br>  );<br>  if (!success) {<br>    return NextResponse.json(<br>      { error: &#39;Too many requests&#39; },<br>      { status: 429 }<br>    );<br>  }<br>  // İşlemi gerçekleştir<br>  return NextResponse.json({ success: true });<br>}</pre><h3>6. Retry Logic (Dikkatli)</h3><pre>// Deadlock durumunda retry yapabilirsin<br>export async function transferWithRetry(<br>  fromUserId: string,<br>  toUserId: string,<br>  amount: number,<br>  maxRetries = 3<br>) {<br>  for (let attempt = 0; attempt &lt; maxRetries; attempt++) {<br>    try {<br>      return await transferMoney(fromUserId, toUserId, amount);<br>    } catch (error: any) {<br>      // PostgreSQL deadlock error code<br>      if (error.code === &#39;40P01&#39; &amp;&amp; attempt &lt; maxRetries - 1) {<br>        // Exponential backoff<br>        await new Promise(resolve =&gt;<br>          setTimeout(resolve, 100 * Math.pow(2, attempt))<br>        );<br>        continue;<br>      }<br>      throw error;<br>    }<br>  }<br>  throw new Error(&#39;Max retries exceeded&#39;);<br>}</pre><h3>7. Monitoring ve Logging</h3><pre>export async function monitoredTransaction(<br>  operation: string,<br>  userId: string,<br>  fn: () =&gt; Promise&lt;any&gt;<br>) {<br>  const startTime = Date.now();<br>  try {<br>    const result = await fn();<br>    const duration = Date.now() - startTime;<br>    console.log(`✅ ${operation} completed in ${duration}ms`, {<br>      userId,<br>      duration,<br>      timestamp: new Date().toISOString(),<br>    });<br>    return result;<br>  } catch (error: any) {<br>    const duration = Date.now() - startTime;<br>    console.error(`❌ ${operation} failed after ${duration}ms`, {<br>      userId,<br>      error: error.message,<br>      stack: error.stack,<br>      timestamp: new Date().toISOString(),<br>    });<br>    throw error;<br>  }<br>}<br><br>// Kullanım<br>await monitoredTransaction(<br>  &#39;transfer-money&#39;,<br>  userId,<br>  () =&gt; transferMoney(fromUserId, toUserId, amount)<br>);</pre><h3>Özet Kontrol Listesi</h3><p><strong>Her kritik işlem için:</strong></p><ul><li>[ ] Transaction kullandın mı? (db.transaction)</li><li>[ ] Güncellemeden önce SELECT FOR UPDATE ile kilitleyecek misin?</li><li>[ ] İki okuma arasında veri değişirse sorun olur mu?</li><li>[ ] Aynı işlem 2 kere çalışırsa ne olur? (Idempotency düşündün mü?)</li><li>[ ] Version/Optimistic locking gerekli mi?</li><li>[ ] Rate limiting var mı?</li><li>[ ] Error handling ve rollback senaryoları düşünüldü mü?</li><li>[ ] Monitoring/logging ekledin mi?</li></ul><p><strong>Kritik akışlar:</strong></p><ul><li>Para transferi → Transaction + FOR UPDATE + Idempotency</li><li>E-posta değiştirme → Token ile state saklama + Transaction</li><li>Password reset → Token iptal + Rate limit + Transaction</li><li>Stok güncellemesi → FOR UPDATE + Transaction</li><li>Kupon kullanımı → FOR UPDATE + Unique constraint + Transaction</li></ul><h3>Kaynaklar</h3><ul><li>Drizzle ORM Transactions: <a href="https://orm.drizzle.team/docs/transactions">https://orm.drizzle.team/docs/transactions</a></li><li>PostgreSQL Locking: <a href="https://www.postgresql.org/docs/current/explicit-locking.html">https://www.postgresql.org/docs/current/explicit-locking.html</a></li></ul><p><strong>Video:</strong> <a href="https://www.youtube.com/watch?v=QAwXJUeLDAM">Mehmet İnce — Race Condition Zafiyetleri</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2d6c20b4e84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ CORS Problemini Next.js ile Çözmek: Proxy ve BFF Pattern Yaklaşımı]]></title>
            <link>https://egebilge.medium.com/cors-problemini-next-js-ile-%C3%A7%C3%B6zmek-proxy-ve-bff-pattern-yakla%C5%9F%C4%B1m%C4%B1-1c7676079ebc?source=rss-2d7b511b69e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c7676079ebc</guid>
            <category><![CDATA[cors]]></category>
            <category><![CDATA[proxy-pattern]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Ege Bilge]]></dc:creator>
            <pubDate>Fri, 05 Sep 2025 07:46:14 GMT</pubDate>
            <atom:updated>2025-09-05T07:46:14.809Z</atom:updated>
            <content:encoded><![CDATA[<p>Web geliştirme sürecinde karşımıza en sık çıkan sorunlardan biri <strong>CORS (Cross-Origin Resource Sharing)</strong> hatasıdır.<br> İster küçük bir proje yapıyor olun, ister büyük bir üretim sistemi geliştirin, tarayıcı üzerinden başka bir servise istek attığınızda bu hatayla karşılaşmanız çok olasıdır.</p><p>Bu yazıda:</p><ul><li><strong>CORS nedir, neden var?</strong></li><li><strong>Klasik çözümler neden yetersiz kalıyor?</strong></li><li><strong>Next.js API Routes kullanarak nasıl kalıcı bir çözüm üretebiliriz?</strong></li><li><strong>BFF (Backend for Frontend) yaklaşımı nedir, bize ne kazandırır?</strong></li></ul><p>bunlara değineceğiz.</p><h3>❓ CORS Nedir?</h3><p>CORS, tarayıcıların güvenlik için koyduğu bir kuraldır.<br> <strong>Aynı origin (domain, protokol, port) dışında bir yere istek atmaya çalıştığınızda</strong> tarayıcı bu isteği engeller.</p><p>Örneğin:</p><ul><li>✅ http://localhost:3000/api/data → Aynı origin, izinli</li><li>❌ https://external-api.com/data → Farklı origin, tarayıcı engeller</li></ul><p>Bunun amacı, kötü niyetli sitelerin sizin adınıza başka sistemlere izinsiz istek atmasını önlemektir.</p><h3>🛑 Karşılaşılan Sorun</h3><p>Birçok projede ihtiyaç duyduğumuz şey şu:<br> Frontend uygulamamız başka bir <strong>harici servisten (örneğin bir ödeme altyapısı, raporlama servisi, harita API’si)</strong> veri almak ister.</p><p>Ama doğrudan şöyle bir istek attığımızda:</p><pre>// ❌ CORS hatası verir<br>await fetch(&quot;https://external-api.com/data&quot;, {<br>  method: &quot;POST&quot;,<br>  body: JSON.stringify({ foo: &quot;bar&quot; })<br>});</pre><p>Tarayıcıdan şu hatayı alırız:</p><pre>Access to fetch at &#39;https://external-api.com/data&#39; <br>from origin &#39;http://localhost:3000&#39; has been blocked by CORS policy.</pre><h3>🔧 Klasik Çözüm Yöntemleri</h3><ol><li><strong>Tarayıcı eklentisi ile bypass etmek</strong> → Sadece development için işe yarar.</li><li><strong>Karşı servisten CORS header açmasını istemek</strong> → Çoğu zaman bizim kontrolümüzde değil.</li><li><strong>JSONP gibi eski teknikler</strong> → Artık modern web’de kullanılmıyor.</li></ol><p>Yani gerçek, sürdürülebilir bir çözüm lazım.</p><h3>🚀 Çözüm: Next.js API Routes ile Proxy</h3><p>Kalıcı çözüm, frontend’in doğrudan harici servise değil, <strong>önce kendi backend’ine istek atmasıdır.</strong><br> Backend (ya da burada Next.js API Routes) bu isteği harici servise yönlendirir.</p><p>Buna kısaca <strong>proxy pattern</strong> denir.</p><h3>Örnek API Route</h3><pre>// /app/api/proxy/route.ts<br>import { NextRequest, NextResponse } from &quot;next/server&quot;;<br><br>export async function POST(request: NextRequest) {<br>  const body = await request.json();<br>  try {<br>    // ✅ Server-to-server request (CORS problemi yok)<br>    const response = await fetch(&quot;https://external-api.com/data&quot;, {<br>      method: &quot;POST&quot;,<br>      headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>      body: JSON.stringify(body)<br>    });<br><br>    // Response&#39;u frontend&#39;e döndür<br>    const data = await response.json();<br>    return NextResponse.json(data, { status: response.status });<br>  } catch {<br>    return NextResponse.json({ error: &quot;Internal server error&quot; }, { status: 500 });<br>  }<br>}</pre><h3>Client-Side Kullanım</h3><pre>// ✅ Artık same-origin request<br>await fetch(&quot;/api/proxy&quot;, {<br>  method: &quot;POST&quot;,<br>  body: JSON.stringify({ foo: &quot;bar&quot; })<br>});</pre><p>Artık tarayıcı ile harici servis arasında doğrudan bağlantı yok.<br> Tüm trafik <strong>frontend → Next.js API Route → external API</strong> üzerinden geçiyor.</p><h3>🔄 Request Akışı</h3><p><strong>Önce (CORS hatası):</strong></p><pre>Browser → ❌ External API → BLOCKED</pre><p><strong>Sonra (Proxy ile):</strong></p><pre>Browser → ✅ Next.js API Route → ✅ External API → ✅ Response</pre><h3>🎯 BFF (Backend for Frontend) Pattern</h3><p>Bu yaklaşım aslında <strong>BFF (Backend for Frontend)</strong> pattern’inin bir uygulamasıdır.</p><p>Yani frontend uygulamanız için özel bir backend katmanı eklemek.</p><h3>Avantajları</h3><ol><li><strong>CORS çözümü</strong>: Tüm istekler same-origin olur.</li><li><strong>Güvenlik</strong>: API anahtarları frontend yerine backend’de saklanır.</li><li><strong>Dönüşüm</strong>: Harici servisten gelen cevap frontend’e uygun hale getirilebilir.</li><li><strong>Caching &amp; Rate Limiting</strong>: Performans ve maliyet kontrolü yapılabilir.</li><li><strong>Merkezi hata yönetimi</strong>: Kullanıcıya daha düzgün hata mesajları gösterilebilir.</li></ol><h3>⚡ Production İçin Öneriler</h3><ul><li><strong>Ortam değişkenleri kullanın</strong> → API URL’lerini .env dosyasında yönetin.</li><li><strong>Hata takibi yapın</strong> → Sentry veya benzeri araçlarla log tutun.</li><li><strong>Güvenlik başlıkları ekleyin</strong> → X-Frame-Options, X-Content-Type-Options gibi header’larla koruma artırın.</li><li><strong>Binary veriler için dikkat edin</strong> → PDF, resim gibi verileri arrayBuffer ile işleyin.</li></ul><h3>🏁 Sonuç</h3><p>CORS, modern web geliştirme sürecinde <strong>kaçınılmaz bir problem</strong>.<br>Ama Next.js API Routes kullanarak yazdığımız küçük bir proxy katmanı ile:</p><p>✅ Daha güvenli<br> ✅ Daha yönetilebilir<br> ✅ Daha esnek<br> ✅ Daha performanslı</p><p>bir mimariye geçiş yapabiliyoruz.</p><p>Ve aslında bu, frontend uygulamalarına özel tasarlanmış <strong>BFF pattern’inin</strong> en pratik örneklerinden biri. 🎉</p><p>✍️ Bu yazı, gerçek projelerde karşılaşılan CORS sorunlarına pratik ve kalıcı bir çözüm arayan geliştiriciler için hazırlandı.<br>Sen de benzer bir deneyim yaşadıysan yorumlarda paylaşabilirsin.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c7676079ebc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Normalizing Inconsistent API Responses in Frontend Development]]></title>
            <link>https://egebilge.medium.com/normalizing-inconsistent-api-responses-in-frontend-development-2e7441c471a1?source=rss-2d7b511b69e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e7441c471a1</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[normalization]]></category>
            <category><![CDATA[consistency]]></category>
            <dc:creator><![CDATA[Ege Bilge]]></dc:creator>
            <pubDate>Thu, 04 Sep 2025 07:33:33 GMT</pubDate>
            <atom:updated>2025-09-04T07:33:33.230Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Data consistency, code readability, and maintainability are critical factors in frontend development. This article explores how to effectively manage inconsistent API responses through normalization techniques.</em></blockquote><h3>📌 Problem Definition</h3><p>Our backend API returns different data structures for the same endpoint:</p><ul><li><strong>Sometimes a single object</strong></li><li><strong>Sometimes an array of objects</strong></li></ul><p>This inconsistency leads to complexity in frontend code, type safety issues, and potential runtime errors.</p><pre>// Different formats that can come from API<br>type ApiResponse = Product | Product[] | null;<br><br>// This inconsistency causes these problems:<br>const products = await fetchProducts();<br>products.map(...) // ❌ Error: products might be a single object</pre><h3>💡 Solution Strategy</h3><p>We normalize API responses on the frontend side to create a consistent data structure:</p><pre>// Basic normalization function<br>const normalizeToArray = &lt;T&gt;(data: T | T[] | null | undefined): T[] =&gt; {<br>  if (Array.isArray(data)) return data;<br>  if (data &amp;&amp; typeof data === &quot;object&quot;) return [data];<br>  return [];<br>};</pre><h3>Advanced Normalization (Recommended)</h3><p>A more comprehensive approach that preserves semantic information:</p><pre>interface NormalizedResponse&lt;T&gt; {<br>  items: T[];<br>  isSingle: boolean;<br>  originalData: T | T[] | null;<br>}<br><br>const normalizeApiResponse = &lt;T&gt;(data: T | T[] | null): NormalizedResponse&lt;T&gt; =&gt; {<br>  if (Array.isArray(data)) {<br>    return { <br>      items: data, <br>      isSingle: false, <br>      originalData: data <br>    };<br>  }<br>  <br>  if (data &amp;&amp; typeof data === &quot;object&quot;) {<br>    return { <br>      items: [data], <br>      isSingle: true, <br>      originalData: data <br>    };<br>  }<br>  <br>  return { <br>    items: [], <br>    isSingle: false, <br>    originalData: null <br>  };<br>};</pre><h3>✅ Benefits</h3><ul><li><strong>Code Stability</strong>: Predictable behavior with consistent data structure</li><li><strong>Array Methods</strong>: Safe usage of map, filter, reduce methods</li><li><strong>Type Safety</strong>: Enhanced type checking with TypeScript</li><li><strong>Developer Experience</strong>: Faster and safer development process</li><li><strong>Error Prevention</strong>: Minimized runtime errors</li></ul><h3>⚙️ Practical Implementation</h3><h3>Basic Usage</h3><pre>// API call<br>const fetchProducts = async (): Promise&lt;Product[]&gt; =&gt; {<br>  try {<br>    const response = await axios.get&lt;Product[] | Product&gt;(&#39;/api/products&#39;, {<br>      params: {<br>        categoryId: selectedCategory,<br>        limit: 20<br>      }<br>    });<br>    <br>    // Normalize the data<br>    const products = normalizeToArray(response.data);<br>    return products;<br>  } catch (error) {<br>    console.error(&#39;Error fetching products:&#39;, error);<br>    return [];<br>  }<br>};</pre><h3>React Hook with Optimization</h3><pre>const useNormalizedProducts = (categoryId: string) =&gt; {<br>  const [products, setProducts] = useState&lt;Product[]&gt;([]);<br>  const [loading, setLoading] = useState(false);<br><br> // Normalization optimization with useMemo<br>  const normalizedProducts = useMemo(() =&gt; {<br>    return normalizeToArray(products);<br>  }, [products]);<br><br> const fetchProducts = useCallback(async () =&gt; {<br>    setLoading(true);<br>    try {<br>      const response = await api.getProducts(categoryId);<br>      setProducts(normalizeToArray(response.data));<br>    } catch (error) {<br>      console.error(&#39;Error:&#39;, error);<br>      setProducts([]);<br>    } finally {<br>      setLoading(false);<br>    }<br>  }, [categoryId]);<br><br> return { products: normalizedProducts, loading, fetchProducts };<br>};</pre><h3>🔍 Performance Optimization</h3><h3>Reference Preservation</h3><pre>// ❌ Creates new array every time<br>const badNormalize = (data) =&gt; {<br>  return Array.isArray(data) ? [...data] : [data];<br>};<br><br>// ✅ Preserves reference when possible<br>const goodNormalize = (data) =&gt; {<br>  if (Array.isArray(data)) return data; // Reference preserved<br>  if (data) return [data]; // New array only when needed<br>  return EMPTY_ARRAY; // Constant reference<br>};<br><br>const EMPTY_ARRAY: readonly any[] = Object.freeze([]);</pre><h3>Memoization</h3><pre>const useOptimizedNormalization = &lt;T&gt;(data: T | T[] | null) =&gt; {<br>  return useMemo(() =&gt; normalizeToArray(data), [data]);<br>};</pre><h3>⚠️ Important Considerations</h3><h3>1. Semantic Meaning Loss</h3><pre>// These two cases might have different meanings<br>const singleProduct = { id: 1, name: &quot;Product&quot; }; // Single product<br>const productList = [{ id: 1, name: &quot;Product&quot; }]; // List with 1 item<br><br>// Solution: Preserve semantic information<br>const { items, isSingle } = normalizeApiResponse(apiData);<br>if (isSingle) {<br>  // Single product behavior<br>} else {<br>  // List behavior<br>}</pre><h3>2. Null/Undefined Handling</h3><pre>const safeNormalize = &lt;T&gt;(data: T | T[] | null | undefined): T[] =&gt; {<br>  // Null/undefined check<br>  if (data == null) return [];<br>  <br>  if (Array.isArray(data)) return data;<br>  return [data];<br>};</pre><h3>🎯 Long-term Solution Recommendations</h3><p>This normalization approach should be considered a <strong>temporary solution</strong>. In the long term:</p><h3>1. Backend Standardization (Most Ideal)</h3><pre>// Every endpoint returns consistent format<br>interface StandardResponse&lt;T&gt; {<br>  data: T[];<br>  meta: {<br>    total: number;<br>    page: number;<br>    isSingle: boolean;<br>  }<br>}</pre><h3>2. Endpoint Separation</h3><pre>GET /api/product/:id     // Single product<br>GET /api/products        // Product list</pre><h3>3. API Versioning</h3><pre>// Standardized format in v2 API<br>GET /api/v2/products → { items: Product[], total: number }</pre><h3>🔧 TypeScript Tips</h3><pre>// Generic type definitions<br>type ApiResponse&lt;T&gt; = T[] | T | null;<br><br>// Utility type<br>type Normalized&lt;T&gt; = {<br>  readonly items: T[];<br>  readonly isSingle: boolean;<br>};<br><br>// Type guard function<br>const isArrayResponse = &lt;T&gt;(data: ApiResponse&lt;T&gt;): data is T[] =&gt; {<br>  return Array.isArray(data);<br>};</pre><h3>📝 Testing Considerations</h3><pre>// Test cases for normalization<br>describe(&#39;normalizeToArray&#39;, () =&gt; {<br>  it(&#39;should return array as is&#39;, () =&gt; {<br>    const input = [1, 2, 3];<br>    expect(normalizeToArray(input)).toBe(input);<br>  });<br><br>it(&#39;should wrap single object in array&#39;, () =&gt; {<br>    const input = { id: 1 };<br>    expect(normalizeToArray(input)).toEqual([input]);<br>  });<br><br>it(&#39;should return empty array for null/undefined&#39;, () =&gt; {<br>    expect(normalizeToArray(null)).toEqual([]);<br>    expect(normalizeToArray(undefined)).toEqual([]);<br>  });<br>});</pre><h3>🚀 Best Practices</h3><h3>1. Create a Utility Library</h3><pre>// utils/apiNormalization.ts<br>export const createNormalizer = &lt;T&gt;() =&gt; ({<br>  toArray: (data: T | T[] | null): T[] =&gt; normalizeToArray(data),<br>  toResponse: (data: T | T[] | null): NormalizedResponse&lt;T&gt; =&gt; <br>    normalizeApiResponse(data)<br>});</pre><h3>2. Use Custom Hooks</h3><pre>const useApiNormalization = &lt;T&gt;() =&gt; {<br>  return useCallback((data: T | T[] | null) =&gt; {<br>    return normalizeToArray(data);<br>  }, []);<br>};</pre><h3>3. Document the Pattern</h3><pre>/**<br> * Normalizes API response to always return an array<br> * This is a temporary solution for inconsistent backend responses<br> * TODO: Remove when backend standardizes responses<br> */<br>const normalizeToArray = &lt;T&gt;(data: T | T[] | null): T[] =&gt; {<br>  // Implementation<br>};</pre><h3>📈 Migration Strategy</h3><p>When transitioning from normalized responses back to standard API responses:</p><pre>// Phase 1: Detection<br>const detectApiFormat = (response: any) =&gt; {<br>  return {<br>    isNormalized: Array.isArray(response.items),<br>    isLegacy: Array.isArray(response) || typeof response === &#39;object&#39;<br>  };<br>};<br><br>// Phase 2: Gradual migration<br>const handleApiResponse = &lt;T&gt;(response: any): T[] =&gt; {<br>  const format = detectApiFormat(response);<br>  <br>  if (format.isNormalized) {<br>    return response.items;<br>  }<br>  <br>  // Fallback to normalization<br>  return normalizeToArray(response);<br>};</pre><h3>📝 Conclusion</h3><p>API normalization is an effective defense mechanism against inconsistent backend behavior. However, it’s important to remember that this approach is a temporary solution, and long-term focus should be on backend standardization.</p><p><strong>Recommended Implementation Order:</strong></p><ol><li>Apply normalization to existing projects</li><li>Plan backend standardization for new projects</li><li>Gradually migrate legacy APIs to new standards</li></ol><p>With this approach, you can solve current problems while building a cleaner codebase for future development. The key is balancing immediate needs with long-term architectural goals.</p><p><em>Remember: The best API is a consistent API. While normalization helps us deal with inconsistencies, the ultimate goal should always be standardization at the source.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e7441c471a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git Hooks ile Modern JavaScript Geliştirme: Biome, Prettier ve ESLint Entegrasyonu]]></title>
            <link>https://egebilge.medium.com/git-hooks-ile-modern-javascript-geli%C5%9Ftirme-biome-prettier-ve-eslint-entegrasyonu-d445ca6e3e8f?source=rss-2d7b511b69e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d445ca6e3e8f</guid>
            <category><![CDATA[biomejs]]></category>
            <category><![CDATA[git-hooks]]></category>
            <category><![CDATA[formatting]]></category>
            <dc:creator><![CDATA[Ege Bilge]]></dc:creator>
            <pubDate>Fri, 22 Aug 2025 10:37:17 GMT</pubDate>
            <atom:updated>2025-08-22T10:37:17.339Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern web geliştirmede kod kalitesi ve tutarlılık, projenin başarısı için kritik faktörlerdir. Özellikle takım halinde çalışırken, farklı geliştirici stillerinin bir araya gelmesi kod tabanında karmaşaya yol açabilir. İşte bu noktada <strong>Git Hooks</strong> devreye girer ve geliştirme sürecimizi otomatikleştirerek kod kalitesini garanti altına alır.</p><p>Bu yazıda, Git Hooks’un ne olduğunu, nasıl çalıştığını ve modern toolchain’ler olan <strong>Biome</strong>, <strong>Prettier</strong> ve <strong>ESLint</strong> ile nasıl entegre edileceğini öğreneceksiniz.</p><h3>Git Hooks Nedir?</h3><p>Git Hooks, Git iş akışınızın belirli noktalarında otomatik olarak çalışan script’lerdir. Commit, push, merge gibi Git operasyonları sırasında tetiklenerek kod kalitesi kontrolü, test çalıştırma, formatting gibi işlemleri otomatik hale getirir.</p><h3>Temel Git Hook Türleri</h3><pre># Client-side hooks (yerel)<br>pre-commit      # Commit öncesi çalışır<br>pre-push        # Push öncesi çalışır  <br>commit-msg      # Commit mesajı kontrolü<br>post-commit     # Commit sonrası çalışır<br><br># Server-side hooks (remote)<br>pre-receive     # Push alınmadan önce<br>post-receive    # Push alındıktan sonra<br>update          # Branch güncellemesi sırasında</pre><h3>Husky ile Git Hooks Yönetimi</h3><p><a href="https://typicode.github.io/husky/">Husky</a>, Git Hooks’u JavaScript projelerde kolayca yönetmemizi sağlayan popüler bir tool’dur.</p><h3>Husky Kurulumu</h3><pre># Husky ve lint-staged kurulumu<br>npm install --save-dev husky lint-staged<br><br># Husky&#39;yi aktif et<br>npx husky install<br><br># package.json&#39;a prepare script ekle<br>npm pkg set scripts.prepare=&quot;husky install&quot;</pre><h3>Temel Hook Oluşturma</h3><pre># Pre-commit hook oluştur<br>npx husky add .husky/pre-commit &quot;npx lint-staged&quot;<br><br># Pre-push hook oluştur  <br>npx husky add .husky/pre-push &quot;npm test&quot;<br><br># Commit message hook oluştur<br>npx husky add .husky/commit-msg &#39;npx --no -- commitlint --edit ${1}&#39;</pre><h3>Scenario 1: ESLint + Prettier Entegrasyonu</h3><p>Klasik ve en yaygın kullanılan yaklaşım olan ESLint + Prettier kombinasyonu:</p><h3>Package.json Konfigürasyonu</h3><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;lint&quot;: &quot;eslint . --ext js,jsx,ts,tsx&quot;,<br>    &quot;lint:fix&quot;: &quot;eslint . --ext js,jsx,ts,tsx --fix&quot;,<br>    &quot;format&quot;: &quot;prettier --write .&quot;,<br>    &quot;prepare&quot;: &quot;husky install&quot;<br>  },<br>  &quot;lint-staged&quot;: {<br>    &quot;*.{js,jsx,ts,tsx}&quot;: [<br>      &quot;eslint --fix&quot;,<br>      &quot;prettier --write&quot;<br>    ],<br>    &quot;*.{json,css,md,yml}&quot;: [<br>      &quot;prettier --write&quot;<br>    ]<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;husky&quot;: &quot;^8.0.3&quot;,<br>    &quot;lint-staged&quot;: &quot;^13.2.2&quot;,<br>    &quot;eslint&quot;: &quot;^8.44.0&quot;,<br>    &quot;prettier&quot;: &quot;^2.8.8&quot;,<br>    &quot;@typescript-eslint/eslint-plugin&quot;: &quot;^5.60.1&quot;,<br>    &quot;@typescript-eslint/parser&quot;: &quot;^5.60.1&quot;<br>  }<br>}</pre><h3>ESLint Konfigürasyonu (.eslintrc.js)</h3><pre>module.exports = {<br>  parser: &#39;@typescript-eslint/parser&#39;,<br>  plugins: [&#39;@typescript-eslint&#39;],<br>  extends: [<br>    &#39;eslint:recommended&#39;,<br>    &#39;@typescript-eslint/recommended&#39;,<br>    &#39;prettier&#39; // Prettier ile conflict&#39;leri önler<br>  ],<br>  rules: {<br>    &#39;@typescript-eslint/no-unused-vars&#39;: &#39;error&#39;,<br>    &#39;@typescript-eslint/no-explicit-any&#39;: &#39;warn&#39;,<br>    &#39;prefer-const&#39;: &#39;error&#39;,<br>    &#39;no-var&#39;: &#39;error&#39;<br>  },<br>  env: {<br>    node: true,<br>    browser: true,<br>    es2022: true<br>  }<br>}</pre><h3>Prettier Konfigürasyonu (.prettierrc)</h3><pre>{<br>  &quot;semi&quot;: false,<br>  &quot;singleQuote&quot;: true,<br>  &quot;tabWidth&quot;: 2,<br>  &quot;trailingComma&quot;: &quot;es5&quot;,<br>  &quot;printWidth&quot;: 80,<br>  &quot;bracketSpacing&quot;: true,<br>  &quot;arrowParens&quot;: &quot;avoid&quot;<br>}</pre><h3>Hook Dosyası (.husky/pre-commit)</h3><pre>#!/usr/bin/env sh<br>. &quot;$(dirname -- &quot;$0&quot;)/_/husky.sh&quot;<br><br># Lint-staged çalıştır<br>npx lint-staged<br><br># TypeScript type check<br>npx tsc --noEmit</pre><h3>Scenario 2: Biome ile All-in-One Yaklaşım</h3><p><a href="https://biomejs.dev/">Biome</a>, Rust ile yazılmış ve ESLint + Prettier’ın yerini almayı hedefleyen ultra-hızlı bir tool’dur.</p><h3>Biome Kurulumu ve Konfigürasyonu</h3><pre># Biome kurulumu<br>npm install --save-dev @biomejs/biome<br><br># Biome config dosyası oluştur<br>npx @biomejs/biome init</pre><h3>Biome Konfigürasyonu (biome.json)</h3><pre>{<br>  &quot;$schema&quot;: &quot;https://biomejs.dev/schemas/1.4.1/schema.json&quot;,<br>  &quot;organizeImports&quot;: {<br>    &quot;enabled&quot;: true<br>  },<br>  &quot;linter&quot;: {<br>    &quot;enabled&quot;: true,<br>    &quot;rules&quot;: {<br>      &quot;recommended&quot;: true,<br>      &quot;style&quot;: {<br>        &quot;noNonNullAssertion&quot;: &quot;error&quot;,<br>        &quot;useConst&quot;: &quot;error&quot;<br>      },<br>      &quot;complexity&quot;: {<br>        &quot;noExtraBooleanCast&quot;: &quot;error&quot;,<br>        &quot;useSimplifiedLogicExpression&quot;: &quot;error&quot;<br>      }<br>    }<br>  },<br>  &quot;formatter&quot;: {<br>    &quot;enabled&quot;: true,<br>    &quot;formatWithErrors&quot;: false,<br>    &quot;indentStyle&quot;: &quot;space&quot;,<br>    &quot;indentWidth&quot;: 2,<br>    &quot;lineWidth&quot;: 80,<br>    &quot;lineEnding&quot;: &quot;lf&quot;<br>  },<br>  &quot;javascript&quot;: {<br>    &quot;formatter&quot;: {<br>      &quot;quoteStyle&quot;: &quot;single&quot;,<br>      &quot;trailingComma&quot;: &quot;es5&quot;,<br>      &quot;semicolons&quot;: &quot;asNeeded&quot;<br>    }<br>  },<br>  &quot;files&quot;: {<br>    &quot;include&quot;: [&quot;src/**/*&quot;, &quot;app/**/*&quot;, &quot;components/**/*&quot;],<br>    &quot;ignore&quot;: [&quot;node_modules&quot;, &quot;dist&quot;, &quot;.next&quot;, &quot;coverage&quot;]<br>  }<br>}</pre><h3>Biome ile Package.json</h3><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;lint&quot;: &quot;biome lint .&quot;,<br>    &quot;lint:fix&quot;: &quot;biome lint --apply .&quot;,<br>    &quot;format&quot;: &quot;biome format --write .&quot;,<br>    &quot;check&quot;: &quot;biome check .&quot;,<br>    &quot;check:fix&quot;: &quot;biome check --apply .&quot;,<br>    &quot;prepare&quot;: &quot;husky install&quot;<br>  },<br>  &quot;lint-staged&quot;: {<br>    &quot;*.{js,jsx,ts,tsx,json}&quot;: [<br>      &quot;biome check --apply&quot;<br>    ]<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;husky&quot;: &quot;^8.0.3&quot;,<br>    &quot;lint-staged&quot;: &quot;^13.2.2&quot;,<br>    &quot;@biomejs/biome&quot;: &quot;^1.4.1&quot;<br>  }<br>}</pre><h3>Biome Hook Dosyası (.husky/pre-commit)</h3><pre>#!/usr/bin/env sh<br>. &quot;$(dirname -- &quot;$0&quot;)/_/husky.sh&quot;<br><br># Biome check (lint + format + organize imports)<br>npx lint-staged<br><br># TypeScript check (Biome henüz type checking yapmıyor)<br>npx tsc --noEmit</pre><h3>Scenario 3: Hibrit Yaklaşım (ESLint + Biome)</h3><p>Bazı projeler için ESLint’in rule zenginliği ile Biome’un hızını birleştirmek isteyebilirsiniz:</p><h3>Hibrit Konfigürasyon</h3><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;lint&quot;: &quot;eslint . &amp;&amp; biome lint .&quot;,<br>    &quot;format&quot;: &quot;biome format --write .&quot;,<br>    &quot;prepare&quot;: &quot;husky install&quot;<br>  },<br>  &quot;lint-staged&quot;: {<br>    &quot;*.{js,jsx,ts,tsx}&quot;: [<br>      &quot;biome format --write&quot;,<br>      &quot;eslint --fix&quot;<br>    ],<br>    &quot;*.{json,css,md}&quot;: [<br>      &quot;biome format --write&quot;<br>    ]<br>  }<br>}</pre><h3>Gelişmiş Hook Konfigürasyonları</h3><h3>Commit Message Validation</h3><pre># .husky/commit-msg<br><br>#!/usr/bin/env sh<br>. &quot;$(dirname -- &quot;$0&quot;)/_/husky.sh&quot;<br><br># Conventional commits kontrolü<br>npx --no -- commitlint --edit ${1}</pre><h3>Commitlint Konfigürasyonu (.commitlintrc.js)</h3><pre>module.exports = {<br>  extends: [&#39;@commitlint/config-conventional&#39;],<br>  rules: {<br>    &#39;type-enum&#39;: [<br>      2,<br>      &#39;always&#39;,<br>      [<br>        &#39;feat&#39;,     // Yeni özellik<br>        &#39;fix&#39;,      // Bug düzeltme<br>        &#39;docs&#39;,     // Dokümantasyon<br>        &#39;style&#39;,    // Formatting<br>        &#39;refactor&#39;, // Kod iyileştirme<br>        &#39;test&#39;,     // Test ekleme<br>        &#39;chore&#39;     // Genel bakım<br>      ]<br>    ]<br>  }<br>}</pre><h3>Pre-push Hook ile Test Validation</h3><pre># .husky/pre-push<br><br>#!/usr/bin/env sh<br>. &quot;$(dirname -- &quot;$0&quot;)/_/husky.sh&quot;<br><br># Unit testleri çalıştır<br>npm test<br><br># E2E testleri çalıştır (opsiyonel)<br>npm run test:e2e<br><br># Build kontrolü<br>npm run build</pre><h3>Performance Karşılaştırması</h3><p>Tool Format Speed / Lint Speed / Bundle Size / Setup Karmaşıklığı <br><strong>Prettier + ESLint</strong> Orta Yavaş Büyük Yüksek <br><strong>Biome</strong> Çok Hızlı Hızlı Küçük Düşük <br><strong>Hibrit</strong> Hızlı Orta Orta Orta</p><h3>Biome’un Avantajları:</h3><ul><li>⚡ <strong>10–100x daha hızlı</strong> (Rust ile yazılmış)</li><li>🔧 <strong>All-in-one</strong> (linting + formatting + import organizing)</li><li>📦 <strong>Küçük bundle size</strong></li><li>⚙️ <strong>Kolay konfigürasyon</strong></li></ul><h3>ESLint + Prettier’ın Avantajları:</h3><ul><li>🔍 <strong>Daha zengin rule seti</strong></li><li>🌍 <strong>Büyük ekosistem</strong> ve plugin desteği</li><li>📚 <strong>Mature</strong> ve well-tested</li><li>🔧 <strong>Granular konfigürasyon</strong></li></ul><h3>Real-World Örnek: Next.js Projesi</h3><p>İşte gerçek bir Next.js projesi için complete setup:</p><h3>Package.json</h3><pre>{<br>  &quot;name&quot;: &quot;interviewace&quot;,<br>  &quot;version&quot;: &quot;0.1.0&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;next dev&quot;,<br>    &quot;build&quot;: &quot;next build&quot;,<br>    &quot;start&quot;: &quot;next start&quot;,<br>    &quot;lint&quot;: &quot;biome lint .&quot;,<br>    &quot;lint:fix&quot;: &quot;biome lint --apply .&quot;,<br>    &quot;format&quot;: &quot;biome format --write .&quot;,<br>    &quot;type-check&quot;: &quot;tsc --noEmit&quot;,<br>    &quot;prepare&quot;: &quot;husky install&quot;<br>  },<br>  &quot;lint-staged&quot;: {<br>    &quot;*.{js,jsx,ts,tsx}&quot;: [<br>      &quot;biome check --apply&quot;<br>    ],<br>    &quot;*.{json,md}&quot;: [<br>      &quot;biome format --write&quot;<br>    ]<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;next&quot;: &quot;^14.0.0&quot;,<br>    &quot;react&quot;: &quot;^18.2.0&quot;,<br>    &quot;react-dom&quot;: &quot;^18.2.0&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;@biomejs/biome&quot;: &quot;^1.4.1&quot;,<br>    &quot;@types/node&quot;: &quot;^20.8.0&quot;,<br>    &quot;@types/react&quot;: &quot;^18.2.0&quot;,<br>    &quot;husky&quot;: &quot;^8.0.3&quot;,<br>    &quot;lint-staged&quot;: &quot;^13.2.2&quot;,<br>    &quot;typescript&quot;: &quot;^5.2.0&quot;<br>  }<br>}</pre><h3>Biome Configuration (biome.json)</h3><pre>{<br>  &quot;$schema&quot;: &quot;https://biomejs.dev/schemas/1.4.1/schema.json&quot;,<br>  &quot;organizeImports&quot;: {<br>    &quot;enabled&quot;: true<br>  },<br>  &quot;linter&quot;: {<br>    &quot;enabled&quot;: true,<br>    &quot;rules&quot;: {<br>      &quot;recommended&quot;: true,<br>      &quot;a11y&quot;: {<br>        &quot;useKeyWithClickEvents&quot;: &quot;error&quot;,<br>        &quot;useKeyWithMouseEvents&quot;: &quot;error&quot;<br>      },<br>      &quot;complexity&quot;: {<br>        &quot;noExtraBooleanCast&quot;: &quot;error&quot;,<br>        &quot;useLiteralKeys&quot;: &quot;error&quot;<br>      },<br>      &quot;style&quot;: {<br>        &quot;noNonNullAssertion&quot;: &quot;error&quot;,<br>        &quot;useConst&quot;: &quot;error&quot;,<br>        &quot;useShorthandPropertyAssignment&quot;: &quot;error&quot;<br>      }<br>    }<br>  },<br>  &quot;formatter&quot;: {<br>    &quot;enabled&quot;: true,<br>    &quot;indentStyle&quot;: &quot;space&quot;,<br>    &quot;indentWidth&quot;: 2,<br>    &quot;lineWidth&quot;: 100<br>  },<br>  &quot;javascript&quot;: {<br>    &quot;formatter&quot;: {<br>      &quot;quoteStyle&quot;: &quot;single&quot;,<br>      &quot;trailingComma&quot;: &quot;es5&quot;,<br>      &quot;semicolons&quot;: &quot;asNeeded&quot;<br>    }<br>  },<br>  &quot;files&quot;: {<br>    &quot;include&quot;: [<br>      &quot;app/**/*&quot;,<br>      &quot;components/**/*&quot;, <br>      &quot;lib/**/*&quot;,<br>      &quot;types/**/*&quot;<br>    ],<br>    &quot;ignore&quot;: [<br>      &quot;node_modules&quot;,<br>      &quot;.next&quot;,<br>      &quot;out&quot;,<br>      &quot;coverage&quot;,<br>      &quot;dist&quot;<br>    ]<br>  }<br>}</pre><h3>Hook Files</h3><pre># .husky/pre-commit<br>#!/usr/bin/env sh<br>. &quot;$(dirname -- &quot;$0&quot;)/_/husky.sh&quot;<br>npx lint-staged<br>npm run type-check<br><br># .husky/pre-push  <br>#!/usr/bin/env sh<br>. &quot;$(dirname -- &quot;$0&quot;)/_/husky.sh&quot;<br>npm run build</pre><h3>CI/CD Entegrasyonu</h3><p>Git Hooks’u GitHub Actions ile de entegre edebilirsiniz:</p><pre># .github/workflows/quality.yml<br>name: Code Quality<br>on: [push, pull_request]<br>jobs:<br>  quality:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v3<br>      <br>      - uses: actions/setup-node@v3<br>        with:<br>          node-version: &#39;18&#39;<br>          cache: &#39;npm&#39;<br>          <br>      - run: npm ci<br>      <br>      - name: Biome Check<br>        run: npm run lint<br>        <br>      - name: Type Check<br>        run: npm run type-check<br>        <br>      - name: Build Check<br>        run: npm run build</pre><h3>Troubleshooting</h3><h3>Yaygın Sorunlar ve Çözümleri</h3><p><strong>Problem 1:</strong> Hook’lar çalışmıyor</p><pre># Çözüm: Executable permission ver<br>chmod +x .husky/pre-commit</pre><p><strong>Problem 2:</strong> Lint-staged dosyaları bulamıyor</p><pre># Çözüm: Git staged files kontrol et<br>git status<br>git add .</pre><p><strong>Problem 3:</strong> Biome konfigürasyonu uygulanmıyor</p><pre># Çözüm: Config dosyası kontrolü<br>npx @biomejs/biome check --config-path ./biome.json</pre><h3>Sonuç</h3><p>Git Hooks, modern JavaScript geliştirmede kod kalitesini garantiye almanın en etkili yöntemlerinden biridir. Bu yazıda gördüğümüz üzere:</p><ul><li><strong>ESLint + Prettier</strong>: Mature ve feature-rich</li><li><strong>Biome</strong>: Ultra-fast ve all-in-one</li><li><strong>Hibrit yaklaşım</strong>: Her iki dünyanın en iyisi</li></ul><p>Hangi yaklaşımı seçerseniz seçin, önemli olan tutarlı bir development workflow kurarak takımınızın kod kalitesi standartlarını korumaktır.</p><h3>Öneriler:</h3><ul><li>🚀 <strong>Yeni projeler için</strong>: Biome’u deneyin</li><li>🏢 <strong>Enterprise projeler için</strong>: ESLint + Prettier kombinasyonu</li><li>⚡ <strong>Performance kritik</strong>: Biome all-the-way</li><li>🔧 <strong>Custom rules gerekiyorsa</strong>: ESLint hybrid approach</li></ul><p>Git Hooks ile happy coding! 🎉</p><p><em>Bu yazı, modern web geliştirme best practice’lerini takip eden bir yaklaşımla hazırlanmıştır. Sorularınız için benimle iletişime geçebilirsiniz.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d445ca6e3e8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Fixed Database Connection Timeouts and Improved Performance by 99%]]></title>
            <link>https://egebilge.medium.com/how-i-fixed-database-connection-timeouts-and-improved-performance-by-99-82e6745f9f3f?source=rss-2d7b511b69e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/82e6745f9f3f</guid>
            <category><![CDATA[supabase]]></category>
            <category><![CDATA[drizzle]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Ege Bilge]]></dc:creator>
            <pubDate>Sat, 02 Aug 2025 16:42:52 GMT</pubDate>
            <atom:updated>2025-08-02T16:42:52.897Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*zo4eg4kZgqkV28umnJPWlQ@2x.png" /></figure><p>A real-world case study of optimizing database connections in a Node.js application</p><h3>The Problem That Kept Me Up at Night</h3><p>Picture this: your users are complaining about slow loading times, your monitoring dashboard is lit up with timeout errors, and every database query takes anywhere from 13 to 30 seconds. This was exactly the situation I faced with our application.</p><p>The error messages were haunting:</p><pre>Error: write CONNECT_TIMEOUT undefined:undefined</pre><p>User authentication was painfully slow, blog posts took forever to load, and the overall user experience was suffering. Something had to change, and fast.</p><h3>The Investigation: Finding the Root Cause</h3><p>After digging deep into our database setup, I discovered three critical issues that were killing our performance:</p><h3>1. We Were Using the Wrong Connection Type</h3><pre>// The problematic code<br>const connectionString = process.env.POSTGRES_URL_NON_POOLING!;</pre><p><strong>The mistake:</strong> We were using a non-pooling connection, which meant every single request opened a brand new database connection. Imagine going to a restaurant where they build you a new table for every order — that’s essentially what we were doing.</p><p><strong>Supabase provides two connection types:</strong></p><ul><li>POSTGRES_URL_NON_POOLING: Direct connection (port 5432) — for migrations only</li><li>POSTGRES_URL: Pooled connection (port 6543) — <strong>this is what you want for your app</strong></li></ul><h3>2. Missing Connection Pool Configuration</h3><pre>// Bare minimum setup (not good enough)<br>const client = postgres(connectionString, {<br>  prepare: false,<br>});</pre><p>We had no connection pooling, no timeout management, and no connection lifecycle control. It was like driving a car without brakes.</p><h3>3. No Error Handling</h3><pre>// Dangerous: crashes on timeout<br>export async function getUserByEmail(email: string) {<br>  const [user] = await db.select()... // Boom! 💥<br>}</pre><p>When timeouts occurred, our entire request would crash instead of gracefully handling the error.</p><h3>The Solution: A Three-Step Fix</h3><h3>Step 1: Switch to Pooled Connections</h3><pre>// The fix that changed everything<br>const connectionString = process.env.POSTGRES_URL || process.env.POSTGRES_URL_NON_POOLING!;</pre><p><strong>Why this works:</strong> Supabase’s connection pooler reuses existing connections instead of creating new ones. It’s like having a dedicated lane on the highway instead of building a new road for every car.</p><h3>Step 2: Implement Proper Connection Pool Settings</h3><pre>const client = postgres(connectionString, {<br>  prepare: false,<br>  max: 20,                    // Connection pool size<br>  idle_timeout: 30,           // Close idle connections after 30s<br>  max_lifetime: 60 * 60,      // Max connection age: 1 hour<br>  connect_timeout: 10,        // Connection timeout: 10s<br>  transform: {<br>    undefined: null,<br>  },<br>});</pre><p><strong>Breaking down each setting:</strong></p><ul><li>max: 20: Allow up to 20 simultaneous connections</li><li>idle_timeout: 30: Clean up unused connections after 30 seconds</li><li>max_lifetime: 3600: Refresh connections every hour to prevent stale connections</li><li>connect_timeout: 10: Don&#39;t wait more than 10 seconds to establish a connection</li></ul><h3>Step 3: Add Robust Error Handling</h3><pre>export async function getUserByEmail(email: string) {<br>  if (!email) return null;<br>  <br>  try {<br>    const normalizedEmail = email.toLowerCase().trim();<br>    const [user] = await db.select()<br>      .from(users)<br>      .where(eq(users.email, normalizedEmail))<br>      .limit(1);<br>    return user || null;<br>  } catch (error) {<br>    console.error(&quot;Error fetching user by email:&quot;, error);<br>    return null; // Graceful fallback instead of crashing<br>  }<br>}</pre><h3>The Results: Dramatic Performance Improvements</h3><p>The transformation was nothing short of spectacular:</p><p>Function Before After Improvement getUserByEmail 2–30 seconds &lt;100ms <strong>99%+ faster</strong> getFeaturedInsights 14 seconds &lt;500ms <strong>96% faster</strong> Dashboard load 2.8 seconds &lt;1 second <strong>65% faster</strong> Connection errors Frequent Rare <strong>95% reduction</strong></p><h3>Key Lessons Learned</h3><h3>1. Always Use Pooled Connections in Production</h3><pre># ✅ Correct for your application<br>POSTGRES_URL=&quot;postgres://user:pass@host:6543/db?pooler=supabase&quot;</pre><pre># ❌ Only use this for database migrations<br>POSTGRES_URL_NON_POOLING=&quot;postgres://user:pass@host:5432/db&quot;</pre><h3>2. Size Your Connection Pool Appropriately</h3><p>For most applications:</p><ul><li><strong>Development:</strong> 5–10 connections</li><li><strong>Production:</strong> 15–25 connections</li><li><strong>High traffic:</strong> 25–50 connections</li></ul><p>Monitor your usage and adjust accordingly.</p><h3>3. Implement Proper Error Handling</h3><p>Always wrap database calls in try-catch blocks and provide graceful fallbacks. Your users should never see a crash when a database operation fails.</p><h3>The Complete Setup Template</h3><p>Here’s the optimized configuration you can use in your own projects:</p><pre>import { drizzle } from &quot;drizzle-orm/postgres-js&quot;;<br>import postgres from &quot;postgres&quot;;</pre><pre>const connectionString = process.env.POSTGRES_URL || process.env.POSTGRES_URL_NON_POOLING!;</pre><pre>const client = postgres(connectionString, {<br>  prepare: false,<br>  max: process.env.NODE_ENV === &#39;production&#39; ? 20 : 10,<br>  idle_timeout: 30,<br>  max_lifetime: 60 * 60,<br>  connect_timeout: 10,<br>  transform: { undefined: null },<br>});</pre><pre>export const db = drizzle(client);</pre><h3>Don’t Forget to Monitor</h3><p>Set up monitoring for:</p><ul><li>Query duration (alert if &gt;5 seconds)</li><li>Connection pool utilization</li><li>Error rates</li><li>Database timeout frequency</li></ul><h3>The Bottom Line</h3><p>Connection pooling isn’t just an optimization — it’s essential for any production application. This simple change transformed our app from a sluggish, error-prone experience into a fast, reliable platform that users actually enjoy using.</p><p><strong>The most important takeaway:</strong> If you’re using Supabase (or any database service), make sure you’re using pooled connections for your application and save the direct connections for migrations only.</p><p>Your users (and your sanity) will thank you.</p><p><em>Have you faced similar database performance issues? Share your experiences in the comments below! 👇</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82e6745f9f3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[48 Saatte Modern Bir AI Blog Platformu: ai.codebiy.com Geliştirme Deneyimi]]></title>
            <link>https://egebilge.medium.com/48-saatte-modern-bir-ai-blog-platformu-ai-codebiy-com-geli%C5%9Ftirme-deneyimi-d73aa65af2cc?source=rss-2d7b511b69e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d73aa65af2cc</guid>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[cursor]]></category>
            <dc:creator><![CDATA[Ege Bilge]]></dc:creator>
            <pubDate>Sat, 02 Aug 2025 15:39:12 GMT</pubDate>
            <atom:updated>2025-08-02T15:39:14.629Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*v2WjWlMoVdkdclhg6AqRug@2x.png" /></figure><p><em>Claude Code ve Cursor ile hızlı geliştirmenin gücü</em></p><p>Yazılım dünyasında “hızlı prototipleme” kavramı hiç bu kadar anlamlı olmamıştı. AI destekli kod editörleri ve yardımcılarının yaygınlaşmasıyla birlikte, sadece 48 saatte kapsamlı bir web uygulaması geliştirmek artık hayal değil, gerçeklik.</p><p>Bu yazıda, <strong>ai.codebiy.com</strong> adlı AI blog platformunun 48 saatlik geliştirme sürecini ve bu deneyimden çıkardığım dersleri paylaşacağım. Eğer siz de hızlı prototipleme yapmak istiyorsanız, bu deneyim size ilham verebilir.</p><h3>🚀 Projenin Doğuşu</h3><p><strong>ai.codebiy.com</strong>, AI hakkında yazılar paylaşmak için tasarlanmış modern bir blog platformu. Fakat bu proje sadece bir blog değil — aynı zamanda modern web geliştirme teknolojilerinin ne kadar hızlı bir şekilde birleştirilebileceğinin de kanıtı.</p><h3>Teknoloji Stack’i</h3><ul><li><strong>Next.js 15.4.5</strong> — React 19 tabanlı full-stack framework (Turbopack ile)</li><li><strong>Supabase</strong> — SSR destekli auth ve veritabanı</li><li><strong>Drizzle ORM</strong> — Type-safe veritabanı operations</li><li><strong>PostgreSQL</strong> — Ana veritabanı</li><li><strong>TypeScript 5</strong> — Tam tip güvenliği</li><li><strong>Tailwind CSS 4</strong> — Next-gen utility-first CSS</li><li><strong>shadcn/ui</strong> — Radix UI tabanlı modern component library</li><li><strong>Bun</strong> — Ultra-fast JavaScript runtime</li><li><strong>Biome</strong> — Rust-based linting ve formatting</li><li><strong>Claude Code</strong> — AI destekli geliştirme</li><li><strong>Cursor</strong> — AI-powered kod editörü</li></ul><h3>📈 48 Saatlik Evrim: Version by Version</h3><h3>Version 0.1.0 — “GENESIS” (İlk 12 Saat)</h3><p>İlk gün, temel altyapının kurulmasına odaklandım:</p><ul><li>Supabase ile kullanıcı kimlik doğrulama sistemi</li><li>Blog yazıları için CRUD operasyonları</li><li>Yorum sistemi ve beğeni mekanizması</li><li>Temel admin dashboard</li><li>Dark/light tema desteği</li></ul><p><strong>Ders #1:</strong> Güçlü bir temel oluşturmak, sonraki adımları büyük ölçüde hızlandırır.</p><h3>Version 0.2.0 — “ADMIN_MATRIX” (İkinci Gün)</h3><p>Admin panelini güçlendirdim:</p><ul><li>Raporlama ve içerik yönetimi sistemi</li><li>Yazar sayfaları ve sosyal bağlantılar</li><li>Performans optimizasyonları</li><li>Rate limiting implementasyonu</li></ul><p><strong>Ders #2:</strong> Admin araçları kullanıcı deneyimi kadar önemli — ihmal etmeyin.</p><h3>Version 0.3.0 — “NEURAL_SYNC”</h3><p>Email doğrulama süreçlerini iyileştirdim:</p><ul><li>Çift tıklama logout problemi çözüldü</li><li>Geliştirme modu banner’ı eklendi</li><li>Changelog sayfası (meta seviye!)</li></ul><p><strong>Ders #3:</strong> Küçük UX problemleri büyük hayal kırıklıklarına yol açabilir.</p><h3>Version 0.4.0 — “CYBER_MATRIX”</h3><p>Yükleme durumları için unified sistem:</p><ul><li>CyberPageLoader ve CyberInlineLoader bileşenleri</li><li>Tutarlı loading deneyimi</li><li>Cyber temalı animasyonlar</li></ul><p><strong>Ders #4:</strong> Loading states kullanıcının sabır seviyesini doğrudan etkiler.</p><h3>Version 0.5.0 — “USER_NEXUS” (Güncel)</h3><p>Kullanıcı yönetimi sistemini tamamladım:</p><ul><li>Kullanıcı askıya alma sistemi</li><li>Self-service hesap silme</li><li>Geliştirme auto-confirmation</li><li>Race condition korumaları</li></ul><h3>🛠️ AI Destekli Geliştirmenin Gücü</h3><h3>Bun Runtime ile Süper Hızlı Development</h3><p>Package.json’dan da görebileceğiniz gibi, bu proje <strong>Bun</strong> runtime’ını kullanıyor. Bu seçim development hızını inanılmaz artırdı:</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;next dev --turbopack&quot;,<br>    &quot;clean&quot;: &quot;rm -rf .next node_modules bun.lockb package-lock.json out dist &amp;&amp; bun install&quot;,<br>    &quot;db:fresh&quot;: &quot;bun run db:push &amp;&amp; bun run db:seed&quot;<br>  }<br>}</pre><p><strong>Bun’ın Avantajları:</strong></p><ul><li>NPM’den 25x daha hızlı paket yüklemesi</li><li>Built-in test runner</li><li>Zero-config TypeScript desteği</li><li>Native bundling capabilities</li></ul><h3>Modern Toolchain: Next.js 15 + React 19</h3><p>En yeni teknolojileri kullanmak risk gibi görünebilir, ama avantajları muazzam:</p><p><strong>Next.js 15.4.5 ile gelen yenilikler:</strong></p><ul><li><strong>Turbopack</strong> — Webpack’ten 10x daha hızlı</li><li>Improved caching strategies</li><li>Better TypeScript performance</li><li>Enhanced developer experience</li></ul><p><strong>React 19&#39;un getirdikleri:</strong></p><ul><li>Server Components optimizasyonları</li><li>Concurrent features</li><li>Better hydration performance</li></ul><h3>Drizzle ORM: Type-Safe Database Operations</h3><p>Supabase ile birlikte Drizzle ORM kullanmak, hem hız hem de güvenlik açısından mükemmel bir kombinasyon:</p><pre>// Örnek Drizzle schema tanımı<br>const users = pgTable(&#39;users&#39;, {<br>  id: uuid(&#39;id&#39;).defaultRandom().primaryKey(),<br>  email: text(&#39;email&#39;).notNull().unique(),<br>  suspended: boolean(&#39;suspended&#39;).default(false),<br>  suspendedAt: timestamp(&#39;suspended_at&#39;),<br>  suspendedReason: text(&#39;suspended_reason&#39;)<br>});</pre><h3>shadcn/ui: Copy-Paste Component Philosophy</h3><p>En akıllı seçimlerden biri <strong>shadcn/ui</strong> kullanmak oldu. Bu component library’nin farkı, dependency olarak yüklenmemesi:</p><pre># shadcn/ui component&#39;leri nasıl eklenir<br>npx shadcn-ui@latest add button<br>npx shadcn-ui@latest add dialog  <br>npx shadcn-ui@latest add dropdown-menu</pre><p><strong>shadcn/ui’ın Avantajları:</strong></p><ul><li><strong>Copy-paste yaklaşımı</strong> — Kodlar projenizde yaşar</li><li><strong>Radix UI primitive’leri</strong> — Accessibility built-in</li><li><strong>Tailwind CSS integration</strong> — Perfect styling harmony</li><li><strong>Customizable</strong> — İstediğiniz gibi modify edebilirsiniz</li><li><strong>No bundle bloat</strong> — Sadece kullandığınız componentler</li></ul><h3>Claude Code ile Terminal Üzerinden Geliştirme</h3><p>Claude Code, terminal üzerinden AI’ya görevler delegasyonu yapmanızı sağlıyor. Bu süreçte en çok işime yarayanlar:</p><pre># Örnek Claude Code komutları<br>claude &quot;Drizzle schema için suspended users tablosu ekle&quot;<br>claude &quot;shadcn/ui dialog ile admin suspension komponenti yaz&quot;<br>claude &quot;TypeScript interface&#39;lerini güncelle&quot;<br>claude &quot;Bun test script&#39;i için unit testler ekle&quot;</pre><h3>Cursor ile Akıllı Kod Editörü Deneyimi</h3><p>Cursor, satır satır kod yazma sürecini büyük ölçüde hızlandırdı:</p><ul><li>Otomatik kod tamamlama</li><li>Bug detection ve öneriler</li><li>Refactoring önerileri</li><li>Context-aware AI yardımı</li></ul><h3>📊 48 Saatin Analizi</h3><h3>Zaman Dağılımı</h3><ul><li><strong>%25</strong> — Database schema ve Drizzle ORM setup</li><li><strong>%20</strong> — Radix UI component integration</li><li><strong>%20</strong> — Supabase SSR auth implementation</li><li><strong>%15</strong> — Tailwind CSS 4 styling ve responsive design</li><li><strong>%10</strong> — Biome linting ve TypeScript configuration</li><li><strong>%10</strong> — Testing ve Bun optimization</li></ul><h3>En Çok Zaman Alan Konular</h3><ol><li><strong>Drizzle ORM Migration Setup</strong> — PostgreSQL schema design</li><li><strong>Supabase SSR Integration</strong> — Server-side auth flow</li><li><strong>Radix UI Customization</strong> — Accessible component styling</li><li><strong>Tailwind CSS 4 Migration</strong> — Next-gen CSS configuration</li><li><strong>Bun Runtime Optimization</strong> — Package management ve build process</li></ol><h3>🎯 Gelecek Planları</h3><p>Roadmap’te heyecan verici özellikler var:</p><ul><li><strong>Multi-language support</strong> 🌐</li><li><strong>Comment notifications</strong> 🔔</li><li><strong>@Mentions sistemi</strong> 💬</li><li><strong>Newsletter integration</strong> 📧</li><li><strong>Advanced search</strong> 🔍</li></ul><h3>🔧 Technical Deep Dive</h3><h3>Package.json Analizi</h3><p>Projenin package.json dosyası, modern web development&#39;in en iyi örneklerinden birini sunuyor:</p><p><strong>Dikkat Çeken Dependency’ler:</strong></p><ul><li>@supabase/ssr: Server-side rendering desteği</li><li>drizzle-orm + drizzle-kit: Type-safe ORM</li><li>@radix-ui/*: 10+ accessible component</li><li>sonner: Modern toast notifications</li><li>react-hook-form + @hookform/resolvers: Form management</li><li>zod: Runtime type validation</li></ul><p><strong>Development Experience:</strong></p><pre>bun run dev          # Turbopack ile lightning-fast reload<br>bun run db:fresh     # Database reset + seed in seconds  <br>bun run format       # Biome ile instant formatting<br>bun run type-check   # Zero-config TypeScript validation</pre><h3>Performance Optimization Secrets</h3><ol><li><strong>Bun Runtime</strong>: NPM’den 25x daha hızlı</li><li><strong>Turbopack</strong>: Webpack’den 10x daha hızlı bundling</li><li><strong>Drizzle ORM</strong>: Zero-overhead query building</li><li><strong>Radix UI</strong>: Tree-shakable, accessible components</li><li><strong>Tailwind CSS 4</strong>: Oxide engine ile instant compilation</li></ol><h3>💡 Hızlı Prototipleme İçin Tavsiyeler</h3><h3>1. Doğru Araçları Seçin</h3><ul><li><strong>Runtime:</strong> Bun (hız için kritik)</li><li><strong>Framework:</strong> Next.js 15 + React 19 (cutting-edge features)</li><li><strong>Database:</strong> Drizzle ORM + PostgreSQL (type safety)</li><li><strong>UI:</strong> Radix UI + Tailwind CSS 4 (accessibility + speed)</li><li><strong>Tooling:</strong> Biome (Rust-based linting)</li><li><strong>AI Tools:</strong> Claude Code, Cursor, GitHub Copilot</li></ul><h3>2. Development Scripts’lerini Optimize Edin</h3><pre>{<br>  &quot;db:fresh&quot;: &quot;bun run db:push &amp;&amp; bun run db:seed&quot;,<br>  &quot;clean&quot;: &quot;rm -rf .next node_modules bun.lockb &amp;&amp; bun install&quot;,<br>  &quot;dev&quot;: &quot;next dev --turbopack&quot;<br>}</pre><p>Bu script’ler development cycle’ını inanılmaz hızlandırıyor.</p><h3>2. MVP Mentalitesi</h3><ul><li>Önce core features’ları bitirin</li><li>Polish’i sonraya bırakın</li><li>Kullanıcı feedback’i alın</li><li>Iterative geliştirme yapın</li></ul><h3>3. AI’yı Verimli Kullanın</h3><ul><li>Specific promptlar yazın</li><li>Code context’ini paylaşın</li><li>Best practices’i sorun</li><li>Debugging’de yardım alın</li></ul><h3>4. Documentation is King</h3><ul><li>Her versiyonu changelog’da kaydedin</li><li>Breaking changes’i not edin</li><li>Future planning yapın</li><li>Code comments yazmayı unutmayın</li></ul><h3>🔮 Sonuç</h3><p>48 saatte <strong>ai.codebiy.com</strong> platformunu geliştirmek, modern web development araçlarının ne kadar güçlü olduğunu bir kez daha gösterdi. AI destekli araçlar sadece kod yazma hızınızı artırmıyor, aynı zamanda daha kaliteli ve maintainable kod yazmanızı da sağlıyor.</p><p><strong>En önemli ders:</strong> Hız ve kalite artık birbirine zıt kavramlar değil. Doğru araçlar ve yaklaşımla, her ikisini de elde etmek mümkün.</p><p>Eğer sizin de benzer bir proje fikriniz varsa, 48 saatinizi ayırın ve denemeye başlayın. Sonuçlar sizi şaşırtabilir!</p><p><em>Bu makale, ai.codebiy.com platformunun geliştirme sürecinden ilham alınarak yazılmıştır. Platform aktif olarak geliştirilmeye devam ediyor ve her yeni versiyonla daha da güçleniyor.</em></p><p><strong>Proje:</strong> <a href="https://ai.codebiy.com/">ai.codebiy.com</a><br> <strong>Changelog:</strong> Platform üzerinde detaylı version geçmişi mevcut</p><p><em>AI ile geliştirme deneyimlerinizi yorumlarda paylaşmayı unutmayın! 🚀</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d73aa65af2cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>