<?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 Safdar Ali on Medium]]></title>
        <description><![CDATA[Stories by Safdar Ali on Medium]]></description>
        <link>https://medium.com/@safdaralii?source=rss-770eecb25a8f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*gcWoDF78ju-Py4Yl</url>
            <title>Stories by Safdar Ali on Medium</title>
            <link>https://medium.com/@safdaralii?source=rss-770eecb25a8f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:18:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@safdaralii/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[JavaScript Promises vs Async/Await — Explained Simply]]></title>
            <link>https://medium.com/@safdaralii/javascript-promises-vs-async-await-explained-simply-cead303ac407?source=rss-770eecb25a8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/cead303ac407</guid>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[safdar-ali]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Safdar Ali]]></dc:creator>
            <pubDate>Sat, 14 Nov 2026 06:50:38 GMT</pubDate>
            <atom:updated>2026-11-14T06:50:38.949Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qm5RrvkUBQ6nTZe3" /></figure><p>I’m <a href="https://safdarali.in/about">Safdar Ali</a>, a frontend engineer in Bengaluru. “Promises vs async await” is not a rivalry — async/await is syntax sugar on top of Promises. You still need both mental models for React, Next.js Server Components, and every fetch call. This guide uses BEFORE/AFTER pairs from production code, not toy timers.</p><p>Async JavaScript is why frontend engineers touch backends without changing jobs — fetch, auth, file uploads, AI streams. Promises formalised callbacks; async/await made them readable. Search “promises vs async await” and forums still debate syntax preference. In production the debate is error handling and parallelism. Get those right and either syntax works; get them wrong and both fail silently on slow networks in India.</p><h3>Mental model — pending, fulfilled, rejected</h3><p>Every Promise is in one of three states. await only pauses inside async functions until fulfillment or rejection. The event loop keeps running other tasks — your loading spinner can animate while fetch waits.</p><h3>Same async operation — Promise chain vs async/await</h3><pre>type User = { id: string; name: string };</pre><pre>// Promise style</pre><pre>function loadUserPromise(id: string): Promise&lt;User&gt; {</pre><pre>  return fetch(&quot;/api/users/&quot; + id)</pre><pre>    .then((res) =&gt; {</pre><pre>      if (!res.ok) throw new Error(&quot;HTTP &quot; + res.status);</pre><pre>      return res.json() as Promise&lt;User&gt;;</pre><pre>    });</pre><pre>}</pre><pre>// async/await style — identical behavior</pre><pre>async function loadUserAsync(id: string): Promise&lt;User&gt; {</pre><pre>  const res = await fetch(&quot;/api/users/&quot; + id);</pre><pre>  if (!res.ok) throw new Error(&quot;HTTP &quot; + res.status);</pre><pre>  return res.json() as Promise&lt;User&gt;;</pre><pre>}</pre><p>Under the hood, async function always returns a Promise. await pauses that function until the Promise settles — it does not block the main thread.</p><p>fetch returns a Promise immediately — the HTTP response arrives later. await does not make fetch synchronous; it only pauses your async function until the Promise settles. Other UI keeps updating because the browser event loop is free. That distinction is what interviewers test when they ask about blocking vs non-blocking I/O.</p><h3>BEFORE / AFTER — escaping callback hell</h3><pre>// BEFORE — nested callbacks (hard to read, easy to miss errors)</pre><pre>getUser(id, (err, user) =&gt; {</pre><pre>  if (err) return handle(err);</pre><pre>  getOrders(user.id, (err2, orders) =&gt; {</pre><pre>    if (err2) return handle(err2);</pre><pre>    render(user, orders);</pre><pre>  });</pre><pre>});</pre><pre>// AFTER — async/await linear flow</pre><pre>async function showDashboard(id: string) {</pre><pre>  try {</pre><pre>    const user = await loadUserAsync(id);</pre><pre>    const orders = await loadOrders(user.id);</pre><pre>    render(user, orders);</pre><pre>  } catch (err) {</pre><pre>    handle(err);</pre><pre>  }</pre><pre>}</pre><h3>Error handling — try/catch vs .catch()</h3><p>StyleWhen I use ittry/catch around awaitMost async functions.catch() on chainFire-and-forget analyticsPromise.allSettledPartial failures OK</p><pre>// BEFORE — forgot await, try/catch never runs on rejection</pre><pre>async function bad() {</pre><pre>  try {</pre><pre>    const data = fetch(&quot;/api/data&quot;); // missing await — bug</pre><pre>    return data;</pre><pre>  } catch (e) {</pre><pre>    console.error(e);</pre><pre>  }</pre><pre>}</pre><pre>// AFTER</pre><pre>async function good() {</pre><pre>  try {</pre><pre>    const res = await fetch(&quot;/api/data&quot;);</pre><pre>    if (!res.ok) throw new Error(&quot;Failed&quot;);</pre><pre>    return await res.json();</pre><pre>  } catch (e) {</pre><pre>    console.error(e);</pre><pre>    throw e; // rethrow for UI error boundary</pre><pre>  }</pre><pre>}</pre><h3>Parallel fetch — Promise.all vs sequential await</h3><p>Sequential await is slow when requests are independent. Dashboard needs user + orders + notifications — run together.</p><pre>// BEFORE — 3 round trips in series (~900ms total on 300ms each)</pre><pre>async function loadSlow() {</pre><pre>  const user = await fetchUser();</pre><pre>  const orders = await fetchOrders();</pre><pre>  const notes = await fetchNotifications();</pre><pre>  return { user, orders, notes };</pre><pre>}</pre><pre>// AFTER — parallel (~300ms + overhead)</pre><pre>async function loadFast() {</pre><pre>  const [user, orders, notes] = await Promise.all([</pre><pre>    fetchUser(),</pre><pre>    fetchOrders(),</pre><pre>    fetchNotifications(),</pre><pre>  ]);</pre><pre>  return { user, orders, notes };</pre><pre>}</pre><pre>// One failure should not kill all — allSettled</pre><pre>const results = await Promise.allSettled([</pre><pre>  fetchUser(),</pre><pre>  fetchOrders(),</pre><pre>]);</pre><pre>const user = results[0].status === &quot;fulfilled&quot; ? results[0].value : null;</pre><p>Promise.race is useful for timeouts — reject if fetch exceeds eight seconds on flaky mobile data. Document timeout values in API client modules so the whole app behaves consistently. Sequential await is correct when order matters: create user, then create profile with user id — parallelising those two calls would be a bug.</p><h3>Next.js Server Components — async by default</h3><pre>// app/dashboard/page.tsx</pre><pre>type Stats = { users: number; revenue: number };</pre><pre>async function getStats(): Promise&lt;Stats&gt; {</pre><pre>  const res = await fetch(&quot;https://api.example.com/stats&quot;, {</pre><pre>    next: { revalidate: 60 },</pre><pre>  });</pre><pre>  if (!res.ok) throw new Error(&quot;Stats unavailable&quot;);</pre><pre>  return res.json();</pre><pre>}</pre><pre>export default async function DashboardPage() {</pre><pre>  const stats = await getStats();</pre><pre>  return &lt;StatsPanel stats={stats} /&gt;;</pre><pre>}</pre><p>Server Components are async functions — no useEffect fetch. See <a href="https://safdarali.in/blog/rsc-vs-client-components">RSC vs client components</a>.</p><h3>Client pitfalls — useEffect and race conditions</h3><pre>// BEFORE — no abort, stale response overwrites new search</pre><pre>useEffect(() =&gt; {</pre><pre>  fetch(&quot;/api/search?q=&quot; + query).then((r) =&gt; r.json()).then(setResults);</pre><pre>}, [query]);</pre><pre>// AFTER — AbortController</pre><pre>useEffect(() =&gt; {</pre><pre>  const ctrl = new AbortController();</pre><pre>  (async () =&gt; {</pre><pre>    try {</pre><pre>      const res = await fetch(&quot;/api/search?q=&quot; + query, { signal: ctrl.signal });</pre><pre>      const data = await res.json();</pre><pre>      setResults(data);</pre><pre>    } catch (e) {</pre><pre>      if ((e as Error).name !== &quot;AbortError&quot;) console.error(e);</pre><pre>    }</pre><pre>  })();</pre><pre>  return () =&gt; ctrl.abort();</pre><pre>}, [query]);</pre><h3>Promises vs async/await — quick comparison</h3><p>TopicPromises (.then)async/awaitReadabilityChains indent rightLinear top-to-bottomError handling.catch() at endtry/catch around awaitParallelismPromise.all([…])await Promise.all([…])Return typeAlways Promiseasync fn returns PromiseDebuggingStack in .thenStack at await line</p><h3>When I keep raw Promises</h3><p>Utility libraries returning Promises, combining with Promise.race for timeouts, or .then() in non-async callbacks. async/await is for readable control flow; Promises are the underlying contract.</p><h3>Creating Promises — wrap legacy callbacks once</h3><pre>function readFileAsync(path: string): Promise&lt;string&gt; {</pre><pre>  return new Promise((resolve, reject) =&gt; {</pre><pre>    readFile(path, &quot;utf8&quot;, (err, data) =&gt; {</pre><pre>      if (err) reject(err);</pre><pre>      else resolve(data);</pre><pre>    });</pre><pre>  });</pre><pre>}</pre><pre>// Prefer promisify utilities in Node; in browser wrap once at module boundary</pre><h3>Async iterators — streams beyond one JSON blob</h3><pre>async function* lineChunks(stream: ReadableStream&lt;Uint8Array&gt;) {</pre><pre>  const reader = stream.getReader();</pre><pre>  const decoder = new TextDecoder();</pre><pre>  let buffer = &quot;&quot;;</pre><pre>  while (true) {</pre><pre>    const { done, value } = await reader.read();</pre><pre>    if (done) break;</pre><pre>    buffer += decoder.decode(value, { stream: true });</pre><pre>    const lines = buffer.split(&quot;\n&quot;);</pre><pre>    buffer = lines.pop() ?? &quot;&quot;;</pre><pre>    for (const line of lines) yield line;</pre><pre>  }</pre><pre>}</pre><p>Large CSV exports and AI streaming responses use async iteration. Promises handle single results; iterators handle sequences. Both compose with await in for-await-of loops.</p><h3>Unhandled rejections — the production alert you want</h3><pre>// Node / edge — log unhandled rejections in API routes</pre><pre>process.on(&quot;unhandledRejection&quot;, (reason) =&gt; {</pre><pre>  console.error(&quot;Unhandled rejection:&quot;, reason);</pre><pre>});</pre><pre>// Always return Response from route handlers — never floating promise</pre><pre>export async function GET() {</pre><pre>  try {</pre><pre>    const data = await loadData();</pre><pre>    return Response.json(data);</pre><pre>  } catch (e) {</pre><pre>    return Response.json({ error: &quot;Server error&quot; }, { status: 500 });</pre><pre>  }</pre><pre>}</pre><p>Floating promises in server actions and API routes caused silent 500s on a client project until we wrapped every async entry point. Treat await like a return statement — every path must settle.</p><h3>Practice pattern</h3><p>Rewrite one sequential useEffect fetch as Promise.all. Add try/catch and rethrow. Measure network tab — the win is immediate on slow Indian mobile networks.</p><p>Async literacy is the bridge between UI work and API design. When you read backend OpenAPI docs, you already think in Promises — negotiating timeout and retry policies with your team gets easier.</p><p>The syntax debate ends when you debug: stack traces from async/await point at your await line; Promise chains point at the nearest .then. Pick whichever makes the failure obvious to your future self.</p><p>Server Actions in Next.js return Promises to the client when you call them from forms — same mental model, different wire format. Always handle rejection in UI with error boundaries or toast messages; unhandled rejections in the browser console are user-facing failures you never measured.</p><p>Next: <a href="https://safdarali.in/blog/javascript-array-methods-guide-2026">JavaScript array methods</a>. Performance: <a href="https://safdarali.in/blog/web-performance-checklist-2026">web performance checklist</a>.</p><p>Async patterns in React 19 and Next.js 15 still bottom out on Promises — Suspense boundaries await async children, error boundaries catch rejections. When you wrap a component in Suspense, you are telling React a Promise will resolve with UI. The syntax changed; the contract did not. Learn Promise.all before learning Server Actions — the same parallelism rules apply server-side.</p><p>Testing async code: use async test functions in Vitest, await expect(loadUser()).resolves.toMatchObject(…). Mock fetch at module level for API units; integration tests hit MSW handlers. Flaky tests often come from missing await or shared mutable state between tests — isolate with beforeEach resets.</p><p>Indian mobile networks add packet loss — always set fetch timeouts and show retry UI. Users blame your app, not Jio. Log failed requests with correlation ids in API routes so support can trace one user complaint to one server log line. Async without observability is debugging with eyes closed.</p><p>Dynamic import() returns a Promise — lazy routes in React and Next.js use it under the hood. await import() in event handlers loads code on demand; do not confuse with static import at top of file. Error boundaries catch render failures; import().catch handles load failures for chunks — handle both in production apps with friendly fallback UI.</p><p>Microtask queue education: await schedules continuations as microtasks; setTimeout is macrotask. Ordering bugs appear when mixing them in tests — flushPromises helpers in test utils exist for a reason. Read MDN event loop once; every async interview question becomes easier.</p><p>Promises vs async/await is not a style war — it is one runtime model. Write async/await in application code, read Promise chains in library source, debug both in stack traces. Ship one refactor this sprint: parallelise three serial fetches and measure waterfall in Network tab. The milliseconds you save are user trust earned.</p><p>Copy these BEFORE/AFTER blocks into your team wiki — replace URLs with internal APIs. New hires in India often learn async from YouTube shorts that skip error handling; this article is the correction layer before they touch production checkout flows.</p><p>finally blocks run after try/catch regardless of success — use for cleanup (revoke object URLs, set loading false). Do not return values from finally that override try return — confusing control flow. Keep finally boring: flags and cleanup only.</p><p>Async generators and for await…of handle streams of chunks — payment webhooks, log tailing, SSE. Promises return one value; iterators return many. Learn for await after mastering Promise.all — not before.</p><p>Top-level await in ES modules runs at import time — powerful in Node scripts, dangerous in client bundles that block parse. Next.js restricts patterns; follow framework docs. When in doubt, await inside async functions you call from entry points you control.</p><p>Save this article for code review — when you see .then().then().then(), suggest async/await refactor in a follow-up PR. When you see missing await, block merge. Async bugs are P0 in payment flows; style issues can wait, correctness cannot.</p><p>Promises vs async await is the same language at different readability levels — master both, ship fewer bugs, and explain your Next.js data layer in interviews without hand-waving. That is the whole goal of this guide from Bengaluru production work, not syntax trivia. Re-read the parallel fetch BEFORE/AFTER before your next dashboard page ships.</p><p>Promises vs async await confusion usually hides one bug: missing await, serial fetch, or swallowed rejection. Fix those three patterns and most async incidents disappear from your on-call rotation — more valuable than debating syntax preference in Slack threads that never ship code.</p><p>Open Network tab, find three serial fetches, parallelise with Promise.all, measure — that ten-minute exercise is worth more than rereading this paragraph. Promises vs async await only matters when milliseconds and error paths reach real users on real networks in India and everywhere else your app ships.</p><p>Server Actions return Promises to the client when invoked from forms — handle pending and error UI explicitly. Route handlers must await every async call before returning Response — floating promises caused silent failures on a fintech project I debugged in Bengaluru until we added integration tests that assert status codes. Async literacy is not optional for full-stack frontend roles in 2026; it is the baseline.</p><p>Copy the BEFORE/AFTER blocks into your codebase as comments above legacy fetch code — future refactors will thank you. Delete the comments after refactor ships. Promises vs async await is maintenance work, not a one-time read ever.</p><p>If this helped you</p><p>I publish free tutorials and write-ups like this in my spare time — no paywall on the guides. If it saved you an afternoon of trial and error, you can support the work:</p><ul><li>→ <a href="https://buymeacoffee.com/safdarali">Buy me a coffee at buymeacoffee.com/safdarali</a></li><li>👉 <a href="https://www.youtube.com/@safdarali_?sub_confirmation=1">Subscribe to my YouTube channel</a> — it’s free; 70+ React &amp; Next.js tutorials</li></ul><h3>Related reading</h3><p>More guides on safdarali.in — same author, production-focused.</p><ul><li><a href="https://safdarali.in/blog/frontend-developer-portfolio-guide-india-2026">Guide</a></li><li><a href="https://safdarali.in/blog/frontend-developer-portfolio-guide-india-2026">How to Build a Frontend Developer Portfolio That Stands Out</a></li><li><a href="https://safdarali.in/blog/frontend-developer-portfolio-guide-india-2026">Frontend developer portfolio guide for India — sections, React/Next.js examples, SEO, performance, personal branding, FAQ, and checklist to build and rank.</a></li><li><a href="https://safdarali.in/blog/frontend-developer-portfolio-guide-india-2026">May 2026 · Read article →</a></li></ul><p><a href="https://safdarali.in/blog/rsc-vs-client-components">Guide</a></p><ul><li><a href="https://safdarali.in/blog/rsc-vs-client-components">React Server Components vs Client Components — When to Use Which</a></li><li><a href="https://safdarali.in/blog/rsc-vs-client-components">Practical RSC vs client guide for Next.js App Router — when to use each, real code, bundle before/after, and performance impact.</a></li><li><a href="https://safdarali.in/blog/rsc-vs-client-components">May 2026 · Read article →</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cead303ac407" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prisma + PostgreSQL + Next.js — Full Stack Setup Guide]]></title>
            <link>https://medium.com/@safdaralii/prisma-postgresql-next-js-full-stack-setup-guide-66f66739df4f?source=rss-770eecb25a8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/66f66739df4f</guid>
            <category><![CDATA[fullstack-development]]></category>
            <category><![CDATA[safdar-ali]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[prisma]]></category>
            <dc:creator><![CDATA[Safdar Ali]]></dc:creator>
            <pubDate>Fri, 30 Oct 2026 14:36:01 GMT</pubDate>
            <atom:updated>2026-10-30T14:36:01.893Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dcAXamaqNXXh8h03" /></figure><p>I’m <a href="https://safdarali.in/about">Safdar Ali</a>. When a Next.js project needs real persistence — users, posts, orders — I default to Prisma over PostgreSQL. Not because ORMs are magic, but because typed queries, migrations, and App Router server components fit together cleanly. This prisma nextjs tutorial walks from zero to production queries, the same stack I use when a client needs a full product, not just a marketing shell on <a href="https://safdarali.in/">safdarali.in</a>.</p><h3>Prerequisites and project bootstrap</h3><p>Node 20+, a Next.js 15 App Router app, and PostgreSQL — local Docker, Neon, or Supabase free tier all work. India-friendly tip: Neon and Supabase both have free tiers with Mumbai-adjacent regions for lower latency than US-only hosts.</p><pre>npx create-next-app@latest my-app --typescript --app --eslint</pre><pre>cd my-app</pre><pre>npm install prisma @prisma/client</pre><pre>npx prisma init</pre><h3>.env</h3><pre>DATABASE_URL=&quot;postgresql://user:pass@localhost:5432/myapp?schema=public&quot;</pre><p>I use Docker Compose for local Postgres when clients want offline development — one docker compose up and DATABASE_URL points at localhost. For solo projects I often skip local Postgres entirely and use Neon’s free branch per developer; connection string in .env.local, no Docker overhead on a laptop that already runs Next.js, Prisma Studio, and Chrome with twelve tabs. Pick the path that gets you to a working schema fastest; you can always dockerize later.</p><p>TypeScript strict mode pairs well with Prisma — generated types flow into Server Components without manual interfaces. Enable strict in tsconfig.json before writing models so nullable fields and relation includes fail at compile time instead of in production when a client reports undefined author name on a blog post.</p><p>prisma nextjs tutorial students often skip .env discipline — commit .env.example, never .env.local. Add DATABASE_URL to Vercel before the first deploy that touches the database, or builds succeed and runtime crashes on the first Server Component query. I test locally with npx prisma studio to verify relations before writing UI — faster than debugging empty author names in JSX when the include was wrong.</p><h3>Schema design — models that match your UI</h3><p>Start from screens, not tables. A blog needs Post and User; a SaaS needs Organization and Member. Keep relations explicit in Prisma schema — your Server Components will thank you for include types.</p><pre>// prisma/schema.prisma</pre><pre>generator client {</pre><pre>  provider = &quot;prisma-client-js&quot;</pre><pre>}</pre><pre>datasource db {</pre><pre>  provider = &quot;postgresql&quot;</pre><pre>  url      = env(&quot;DATABASE_URL&quot;)</pre><pre>}</pre><pre>model User {</pre><pre>  id        String   @id @default(cuid())</pre><pre>  email     String   @unique</pre><pre>  name      String?</pre><pre>  posts     Post[]</pre><pre>  createdAt DateTime @default(now())</pre><pre>}</pre><pre>model Post {</pre><pre>  id        String   @id @default(cuid())</pre><pre>  title     String</pre><pre>  slug      String   @unique</pre><pre>  published Boolean  @default(false)</pre><pre>  authorId  String</pre><pre>  author    User     @relation(fields: [authorId], references: [id])</pre><pre>  createdAt DateTime @default(now())</pre><pre>}</pre><pre>// BEFORE — stringly-typed IDs and no unique slug</pre><pre>model Post {</pre><pre>  id    Int    @id @default(autoincrement())</pre><pre>  slug  String</pre><pre>}</pre><pre>// AFTER — cuid + unique slug for App Router [slug] routes</pre><pre>slug String @unique</pre><p>Relations deserve early attention. A Post belongs to User today; tomorrow you add Organization with multi-tenant posts. Adding authorId without planning tenantId means painful migrations when the second customer onboard. I sketch entity relationships on paper — or Excalidraw — before writing schema.prisma, even for weekend projects. Prisma makes schema changes easy; product direction changes are what hurt.</p><p>Enums versus strings is another choice. status Enum(PUBLISHED, DRAFT) gives database-level validation; status String gives flexibility when product adds ARCHIVED without a migration. For indie MVPs I use strings with Zod enums in application code; for fintech clients I prefer Prisma enums so bad data never lands in Postgres regardless of application bugs.</p><p>@@index directives in schema.prisma belong on columns you filter and sort — slug, authorId, published, createdAt. Missing indexes show up as slow dashboards long after launch. I add indexes when queries exist, not speculatively on every string column. Prisma migrate dev generates the SQL; review it like any migration before applying to production.</p><h3>Migrations — dev flow vs production</h3><p>Local development: prisma migrate dev creates SQL migration files you commit to Git. Production: prisma migrate deploy in CI or release step — never edit production schema by hand.</p><pre># Create and apply migration locally</pre><pre>npx prisma migrate dev --name init_blog</pre><h3>Generate client after schema changes</h3><pre>npx prisma generate</pre><h3>Production (CI script)</h3><pre>npx prisma migrate deploy</pre><p>I once skipped committing migration files and watched staging diverge from local — painful afternoon. Treat prisma/migrations like application code.</p><p>prisma db seed populates local databases with realistic fixtures — fake users, sample posts, test orders. I commit prisma/seed.ts and wire it in package.json so new engineers run npx prisma db seed after migrate dev. Seeds are not for production; they save hours clicking through empty admin UIs during development. Use faker or static JSON depending on whether you need reproducible demo data for screenshots.</p><p>Rollback strategy matters when migrate deploy fails mid-pipeline. CI should fail the deploy, not half-apply schema. I run migrations in a dedicated CI step before next build, with DATABASE_URL pointing at staging first. Production promote only after smoke tests pass. Prisma documents repair commands for drift — read them before you need them at 2 AM Bengaluru time.</p><p>prisma db push is for prototypes only — it syncs schema without migration history. I use it on weekend hacks, then throw away the database before production. Production always uses migrate dev and committed migration folders. Clients paying for reliability deserve auditable schema history, not a pushed schema that cannot roll back cleanly.</p><h3>Prisma client singleton — avoid connection exhaustion</h3><p>Next.js dev hot reload can spawn multiple PrismaClient instances. The standard singleton pattern fixes “too many connections” on localhost and serverless.</p><pre>// lib/prisma.ts</pre><pre>import { PrismaClient } from &quot;@prisma/client&quot;;</pre><pre>const globalForPrisma = globalThis as unknown as {</pre><pre>  prisma: PrismaClient | undefined;</pre><pre>};</pre><pre>export const prisma =</pre><pre>  globalForPrisma.prisma ??</pre><pre>  new PrismaClient({</pre><pre>    log: process.env.NODE_ENV === &quot;development&quot; ? [&quot;query&quot;, &quot;error&quot;] : [&quot;error&quot;],</pre><pre>  });</pre><pre>if (process.env.NODE_ENV !== &quot;production&quot;) globalForPrisma.prisma = prisma;</pre><p>The singleton pattern stores PrismaClient on globalThis during development so hot module replacement does not create connection number fifty-one. In production on serverless, each function invocation may still create a client — pooling at the database layer is mandatory, not optional. I log query duration in development only; production logs errors without printing full SQL that might contain PII from WHERE clauses.</p><h3>Server queries in App Router — read path</h3><pre>// app/blog/[slug]/page.tsx — Server Component</pre><pre>import { prisma } from &quot;@/lib/prisma&quot;;</pre><pre>import { notFound } from &quot;next/navigation&quot;;</pre><pre>type Props = { params: Promise&lt;{ slug: string }&gt; };</pre><pre>export default async function BlogPostPage({ params }: Props) {</pre><pre>  const { slug } = await params;</pre><pre>const post = await prisma.post.findUnique({</pre><pre>    where: { slug, published: true },</pre><pre>    include: { author: { select: { name: true } } },</pre><pre>  });</pre><pre>if (!post) notFound();</pre><pre>return (</pre><pre>    &lt;article&gt;</pre><pre>      &lt;h1&gt;{post.title}&lt;/h1&gt;</pre><pre>      &lt;p&gt;By {post.author.name}&lt;/p&gt;</pre><pre>    &lt;/article&gt;</pre><pre>  );</pre><pre>}</pre><p>HTML ships with content — same SEO win as my <a href="https://safdarali.in/blog/nextjs-vs-react-which-to-learn-2026">Next.js vs React</a> article. No client fetch waterfall.</p><p>Pagination belongs in the query, not in JavaScript filter after fetch. Use cursor-based pagination for infinite scroll feeds; offset pagination is fine for admin tables under ten thousand rows. Include only fields the UI needs — select and include are your friends against over-fetching. I have seen findMany without take pull entire tables into server memory and OOM a Vercel function on a client blog with five years of posts.</p><p>Caching interacts with Prisma through Next.js fetch cache and unstable_cache — wrap expensive read queries when data can be stale for sixty seconds. Do not cache user-specific rows in shared cache keys unless you include userId in the key. Public blog slugs cache well; /dashboard/me does not.</p><p>generateMetadata alongside findUnique lets blog posts ship correct Open Graph titles from the database — one query, SEO and body content aligned. I colocate the prisma call in generateMetadata and the page component only when necessary; often a shared getPostBySlug helper in lib/posts.ts avoids duplicate queries through React cache() in the same request.</p><h3>Mutations — Server Actions with Prisma</h3><pre>// app/actions/posts.ts</pre><pre>&quot;use server&quot;;</pre><pre>import { prisma } from &quot;@/lib/prisma&quot;;</pre><pre>import { revalidatePath } from &quot;next/cache&quot;;</pre><pre>import { z } from &quot;zod&quot;;</pre><pre>const CreatePost = z.object({</pre><pre>  title: z.string().min(1).max(120),</pre><pre>  slug: z.string().regex(/^[a-z0-9-]+$/),</pre><pre>});</pre><pre>export async function createPost(formData: FormData) {</pre><pre>  const parsed = CreatePost.safeParse({</pre><pre>    title: formData.get(&quot;title&quot;),</pre><pre>    slug: formData.get(&quot;slug&quot;),</pre><pre>  });</pre><pre>  if (!parsed.success) return { error: &quot;Invalid input&quot; };</pre><pre>await prisma.post.create({</pre><pre>    data: {</pre><pre>      title: parsed.data.title,</pre><pre>      slug: parsed.data.slug,</pre><pre>      authorId: &quot;user_id_from_session&quot;,</pre><pre>    },</pre><pre>  });</pre><pre>revalidatePath(&quot;/blog&quot;);</pre><pre>  return { ok: true };</pre><pre>}</pre><p>Deeper patterns: <a href="https://safdarali.in/blog/react-server-actions-production-guide">React Server Actions guide</a>.</p><p>Authorization belongs in Server Actions before prisma calls — verify session, check row ownership, then mutate. Never trust authorId from hidden form fields. I load the session server-side and compare post.authorId to session.userId before update or delete. Prisma does not know your auth rules; it executes whatever valid SQL your code requests.</p><p>Soft deletes with deletedAt DateTime? optional filter every findMany — easy to forget and leak rows. I prefer explicit archived boolean or a dedicated status enum. Prisma middleware can enforce soft delete globally, but that magic confuses juniors debugging why count queries disagree. Be explicit in query helpers until the team knows the data model cold.</p><h3>BEFORE / AFTER — raw SQL vs Prisma in a Next.js route</h3><pre>// BEFORE — pg pool in every route, manual mapping</pre><pre>import { Pool } from &quot;pg&quot;;</pre><pre>const pool = new Pool({ connectionString: process.env.DATABASE_URL });</pre><pre>export async function GET() {</pre><pre>  const res = await pool.query(&quot;SELECT * FROM Post WHERE published = true&quot;);</pre><pre>  return Response.json(res.rows);</pre><pre>}</pre><pre>// AFTER — typed Prisma in Server Component</pre><pre>const posts = await prisma.post.findMany({</pre><pre>  where: { published: true },</pre><pre>  orderBy: { createdAt: &quot;desc&quot; },</pre><pre>  take: 20,</pre><pre>});</pre><p>Raw SQL still has a place — reporting queries with window functions, bulk updates, or Postgres-specific features Prisma does not model. Use prisma.$queryRaw with tagged templates and parameterized values; never string-concatenate user input. For ninety percent of CRUD in Next.js apps, generated client methods stay readable and type-safe enough that raw SQL becomes the exception documented in code comments.</p><h3>Seeding local data — realistic dev without production dumps</h3><pre>// prisma/seed.ts</pre><pre>import { PrismaClient } from &quot;@prisma/client&quot;;</pre><pre>const prisma = new PrismaClient();</pre><pre>async function main() {</pre><pre>  await prisma.user.upsert({</pre><pre>    where: { email: &quot;dev@safdarali.in&quot; },</pre><pre>    update: {},</pre><pre>    create: {</pre><pre>      email: &quot;dev@safdarali.in&quot;,</pre><pre>      name: &quot;Safdar Ali&quot;,</pre><pre>      posts: {</pre><pre>        create: [</pre><pre>          { title: &quot;Draft post&quot;, slug: &quot;draft-post&quot;, published: false },</pre><pre>          { title: &quot;Hello world&quot;, slug: &quot;hello-world&quot;, published: true },</pre><pre>        ],</pre><pre>      },</pre><pre>    },</pre><pre>  });</pre><pre>}</pre><pre>main()</pre><pre>  .then(() =&gt; prisma.$disconnect())</pre><pre>  .catch((e) =&gt; { console.error(e); process.exit(1); });</pre><pre>// package.json</pre><pre>&quot;prisma&quot;: {</pre><pre>  &quot;seed&quot;: &quot;npx tsx prisma/seed.ts&quot;</pre><pre>}</pre><h3>Run after migrate dev</h3><pre>npx prisma db seed</pre><p>Seed scripts keep your App Router pages testable without clicking through admin UI every refresh. Never run seed against production — use migrations plus one-off scripts with explicit environment checks.</p><h3>Deploy checklist — connection pooling on serverless</h3><p>Serverless functions should not open unlimited DB connections. Use Prisma Accelerate, PgBouncer, or Neon’s pooled connection string in DATABASE_URL.</p><pre># Vercel build</pre><pre>prisma generate</pre><pre>prisma migrate deploy</pre><pre>next build</pre><h3>.env.production — pooled URL example (Neon)</h3><pre>DATABASE_URL=&quot;postgresql://user:pass@ep-xxx.ap-southeast-1.aws.neon.tech/neondb?sslmode=require&amp;pgbouncer=true&quot;</pre><p>Platform comparison: <a href="https://safdarali.in/blog/deploy-nextjs-free-vercel-netlify-railway">deploy Next.js free</a>.</p><p>Preview deployments on Vercel need their own DATABASE_URL or a shared staging database with clear naming — I prefix preview branch names in Neon and rotate credentials when interns leave. Never point preview at production Postgres; one bad seed script deletes real customer rows. Environment separation is boring until it saves your company.</p><h3>Production habits that save you on call</h3><p>Index columns you filter on (slug, authorId). Never expose prisma to client components. Seed scripts for local dev only. <strong>Prisma + PostgreSQL + Next.js</strong> is the full-stack default I recommend when the product stores data — learn the schema first, ship server queries second, wire actions third.</p><p>Related: <a href="https://safdarali.in/blog/graphql-vs-rest-nextjs-2026">GraphQL vs REST</a>, <a href="https://safdarali.in/contact">contact</a>.</p><p>Serverless without a connection pooler exhausts Postgres connections under traffic spikes. Neon, Supabase, and Railway offer pooled URLs — use them in Vercel environment variables. Prisma Accelerate is an option when latency to your database region is high from Indian users hitting a US-east instance.</p><p>Wrap multi-step writes in prisma.$transaction inside Server Actions — partial updates corrupt data. Validate input with Zod before every Prisma call. Use a separate TEST_DATABASE_URL in Jest; never hit production from tests.</p><p><strong>prisma nextjs tutorial takeaway:</strong> schema first, migrate second, singleton client third, Server Component reads fourth, Server Action writes fifth, deploy with pooler sixth. Ship one CRUD feature this weekend — a blog, a todo app, a contact form that persists — and you will understand the stack better than reading docs alone.</p><p>prisma studio is underrated for debugging — npx prisma studio opens a GUI on local data without writing SQL. Use it when Server Actions return unexpected null relations. For production debugging, prefer read-only replicas and logged queries over connecting Studio to live databases from a coffee shop WiFi in Bengaluru.</p><p>Indexing strategy: add @@index([authorId]) and @@index([slug]) in schema when lists filter on those columns. Prisma migrate generates the SQL; you review the migration file before apply. Missing indexes show up as slow queries in Neon dashboard long before users complain — if you are not monitoring query time, start there this week.</p><p>Soft deletes with deletedAt DateTime fields keep rows for audit without losing foreign keys — Prisma supports filtering where deletedAt is null in every query. Add a wrapper function so engineers cannot forget the filter. Hard deletes for GDPR erasure stay as explicit admin-only Server Actions with logging.</p><p>Read replicas are a later concern. For MVPs on Neon free tier, a single primary with connection pooling is enough. When read traffic ten times exceeds write traffic, split reads or move analytics to a warehouse — not on day one from a Bengaluru apartment dev setup.</p><p>If this helped you</p><p>I publish free tutorials and write-ups like this in my spare time — no paywall on the guides. If it saved you an afternoon of trial and error, you can support the work:</p><ul><li>→ <a href="https://buymeacoffee.com/safdarali">Buy me a coffee at buymeacoffee.com/safdarali</a></li><li>👉 <a href="https://www.youtube.com/@safdarali_?sub_confirmation=1">Subscribe to my YouTube channel</a> — it’s free; 70+ React &amp; Next.js tutorials</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66f66739df4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jev Is Not an LLM. That Is the Point.]]></title>
            <link>https://medium.com/@safdaralii/jev-is-not-an-llm-that-is-the-point-e33412fa08c4?source=rss-770eecb25a8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e33412fa08c4</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[jevs]]></category>
            <category><![CDATA[safdar-ali]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Safdar Ali]]></dc:creator>
            <pubDate>Sat, 03 Oct 2026 11:38:24 GMT</pubDate>
            <atom:updated>2026-10-03T11:38:24.687Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Jev Is Not an LLM. That Is the Point. | Safdar Ali" src="https://cdn-images-1.medium.com/max/1024/0*N36Z4bAWmgGiBNPy" /></figure><p>Most “AI features” are not writing tasks. They are decisions.</p><p>Is this ticket urgent? Which queue owns it? Is this shell command safe to run? Should this request go to a small model, a large one, or a person?</p><p>A language model can answer all of those. It does it by generating text, one token at a time, even when you asked for JSON. <a href="https://typesafe.ai/blog/introducing-system-one-models-and-jev">Jev</a>, from TypeSafe AI, does not generate text at all. You hand it a piece of state and a set of questions whose answers you already defined. It fills those answers in one pass and attaches a confidence score to each one.</p><p>That tradeoff is the product. Jev cannot write the email, the summary, or the code. Your program still decides what to do with the judgment.</p><h3>What you are actually calling</h3><p>TypeSafe calls Jev a System One model, after the fast, intuitive half of Daniel Kahneman’s <em>Thinking, Fast and Slow</em>. The name Jev comes from William Stanley Jevons: when a resource gets cheap enough, people find far more uses for it. The bet is that a decision cheap enough to put inside ordinary control flow gets used in places a frontier chat model never will.</p><p>The interface is closer to a function than to a chat:</p><p>A language modelJevOutputA string you parseA value you declared up frontSamplingOne token after anotherEvery answer in the same requestUncertaintyOnly if you ask, and often overconfidentA confidence score on every answerFailure modeWrong words, broken JSON, a type you did not expectA wrong choice inside the types you allowed</p><p>TypeSafe’s published pricing is $0.042 per million input tokens, with output tokens not billed. They report end-to-end times of about 70–500ms, and on their own workflow evals they cite figures around 190× faster and 440× cheaper than the large models they compared against. Those numbers are their benchmark, on workflows their own team wrote, scored against other labs’ models. Treat them as a reason to measure your path, not as a number to put in a launch post.</p><p>Schema match is a harder claim, and a narrower one. Jev cannot return a string when the field is an enum. It can still pick sales when billing was right. You fixed the shape. You did not get correctness for free.</p><h3>Put the question on the type, not in the prompt</h3><p>If you have used Pydantic AI, the call looks like any other structured-output agent. Install the TypeSafe extra and set TYPESAFE_API_KEY.</p><pre>pip install &quot;pydantic-ai-slim[typesafe]&quot;<br>export TYPESAFE_API_KEY=&quot;your-api-key&quot;</pre><p>The habit that does not carry over from a language model: the prompt is only the material being judged. The questions live on the output type. A question written into the prompt is more text to judge, not an instruction.</p><pre>from typing import Literal</pre><pre>from pydantic import BaseModel, Field<br>from pydantic_ai import Agent</pre><pre>class Ticket(BaseModel):<br>    &quot;&quot;&quot;Triage a support ticket.&quot;&quot;&quot;</pre><pre>    urgent: bool = Field(description=&quot;Does this need a reply within the hour?&quot;)<br>    area: Literal[&quot;billing&quot;, &quot;bug&quot;, &quot;account&quot;, &quot;other&quot;] = Field(<br>        description=&quot;Which team owns it?&quot;<br>    )</pre><pre>agent = Agent(&quot;typesafe:jev-latest&quot;, output_type=Ticket)<br>result = agent.run_sync(<br>    &quot;You charged me twice and my account is overdrawn. I need this reversed today.&quot;<br>)<br>print(result.output)<br># urgent=True area=&#39;billing&#39;</pre><p>Several fields go out together. That is where the latency win comes from: independent judgments are not separate generation rounds. Extra fields cost input tokens, not another round trip.</p><p>Ask one thing per field. “Is this a good ticket?” is several judgments wearing one name. Jev will still return something, often with low confidence, and you will notice too late. Split it. Combine the answers in code, where the rule is exact.</p><p>A str field, an unbounded number, or a datetime is rejected before the request is sent. If the answer is prose, this is the wrong model.</p><h3>Confidence is the part you branch on</h3><p>A boolean becomes True when Jev&#39;s probability of yes is at least typesafe_boolean_threshold, which defaults to 0.5. That default is a coin flip. It is the wrong bar when the two mistakes do not cost the same. Raising the threshold means a True has to be earned, which is what you want for &quot;safe to run this command with no one watching.&quot;</p><p>The margin on each field is on the response, not on the model instance:</p><pre>details = result.response.provider_details or {}<br>confidence = details.get(&quot;confidence&quot;, {})<br># {&#39;urgent&#39;: 0.91, &#39;area&#39;: 0.74}  — illustrative</pre><p>confidence here is a margin, not &quot;the probability this label is correct.&quot; For a yes/no it measures how far the probability sits from the threshold that decided it. For a pick-one, the full distribution is in provider_details[&#39;probabilities&#39;].</p><p>A practical split:</p><ul><li>High margin: let code act.</li><li>Middle: send the same state to a stronger generative model.</li><li>Low: ask a person.</li></ul><p>jev-latest moves when TypeSafe ships a release, and the numbers under a tuned threshold can move with it. Once a bar is calibrated on your own labels, pin a version such as typesafe:jev-1.13.0.</p><p>If the honest answer is sometimes “not enough information,” put that in the type. A yes/no with no third option forces a side.</p><h3>Where it fits, and where it does not</h3><p>Use Jev for the small semantic branch that used to be either a brittle regex or a full model call:</p><ul><li>Routing a ticket, a tool call, or a model.</li><li>Scoring a rubric you defined (ordered levels, each one described).</li><li>Checking an agent step: did it finish, did it leave the requested scope, does a human need to see this?</li><li>Guardrails around something a language model already wrote.</li></ul><p>Keep a language model for generation and for reasoning that does not fit in one judgment. Keep ordinary code for rules you can write down: amount greater than a limit, a missing field, an allow-list. Jev sitting in the middle does not replace either of those.</p><p>Two design limits are worth knowing before you sketch an architecture. Choice lists top out at 255 options, and a high-cardinality pick may be scored in two stages. Fields in the same request are independent, so one answer cannot depend on another answer from that same call. If the second judgment needs the first, make them two steps.</p><h3>A small architecture, not a new model in every slot</h3><pre>exact rule            → code<br>bounded judgment      → Jev<br>writing or reasoning  → a language model<br>high-stakes uncertainty → a person</pre><p>The useful question is not which model to standardize on. It is what kind of intelligence a given step needs. If the step is a decision with answers you can name in advance, generating those answers token by token is a lot of machinery for a branch.</p><p>Jev is in early access. The <a href="https://typesafe.ai/blog/introducing-system-one-models-and-jev">TypeSafe announcement</a> has their evals and the caveats attached to them. The <a href="https://pydantic.dev/docs/ai/models/typesafe/">Pydantic AI TypeSafe docs</a> are the practical reference for field types, thresholds, and provider_details.</p><h3>☕ If This Helped You</h3><p>I publish free tutorials and write-ups like this regularly.</p><p>If this article saved you time:</p><p>👉 <strong>Buy me a coffee:</strong></p><p><a href="https://buymeacoffee.com/safdarali">https://buymeacoffee.com/safdarali</a></p><p>👉 <strong>Subscribe to my YouTube channel (free):</strong></p><p><a href="https://www.youtube.com/@safdarali_?sub_confirmation=1">https://www.youtube.com/@safdarali_?sub_confirmation=1</a></p><p><em>More about how I work: </em><a href="https://safdarali.in/about"><em>safdarali.in/about</em></a><br><em>Projects and case studies: </em><a href="https://safdarali.in/projects"><em>safdarali.in/projects</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e33412fa08c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zustand vs Redux Toolkit — Which State Manager in 2026?]]></title>
            <link>https://medium.com/@safdaralii/zustand-vs-redux-toolkit-which-state-manager-in-2026-0a2c3541552d?source=rss-770eecb25a8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a2c3541552d</guid>
            <category><![CDATA[safdar-ali]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[zustand]]></category>
            <dc:creator><![CDATA[Safdar Ali]]></dc:creator>
            <pubDate>Sat, 11 Jul 2026 22:00:58 GMT</pubDate>
            <atom:updated>2026-07-11T22:00:58.713Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aU7a_noitQaTZiDK" /></figure><p>Global state still matters in 2026 — but most pages should not need it. When they do, the debate is <strong>zustand vs redux 2026</strong>: Redux Toolkit (RTK) is the enterprise default; Zustand is the minimal store juniors actually read. I have shipped both on dashboards in production. This article implements the same counter plus async user fetch in each, compares bundle size, and ends with what I pick for new repos.</p><h3>Zustand — counter and async fetch</h3><pre>// store/useAppStore.ts</pre><pre>import { create } from &quot;zustand&quot;;</pre><pre>type User = { id: string; name: string } | null;</pre><pre>type State = {</pre><pre>  count: number;</pre><pre>  user: User;</pre><pre>  loading: boolean;</pre><pre>  increment: () =&gt; void;</pre><pre>  fetchUser: () =&gt; Promise&lt;void&gt;;</pre><pre>};</pre><pre>export const useAppStore = create&lt;State&gt;((set) =&gt; ({</pre><pre>  count: 0,</pre><pre>  user: null,</pre><pre>  loading: false,</pre><pre>  increment: () =&gt; set((s) =&gt; ({ count: s.count + 1 })),</pre><pre>  fetchUser: async () =&gt; {</pre><pre>    set({ loading: true });</pre><pre>    const res = await fetch(&quot;/api/me&quot;);</pre><pre>    const user = await res.json();</pre><pre>    set({ user, loading: false });</pre><pre>  },</pre><pre>}));</pre><pre>// components/CounterPanel.tsx</pre><pre>&quot;use client&quot;;</pre><pre>import { useAppStore } from &quot;@/store/useAppStore&quot;;</pre><pre>export function CounterPanel() {</pre><pre>  const count = useAppStore((s) =&gt; s.count);</pre><pre>  const increment = useAppStore((s) =&gt; s.increment);</pre><pre>  return &lt;button onClick={increment}&gt;Count: {count}&lt;/button&gt;;</pre><pre>}</pre><p>No providers, no slices folder — one file, selective subscriptions via selectors. That is why Zustand spreads on small teams.</p><p>The async fetch above is intentionally boring — no thunk middleware, just async/await inside the store action. For error handling you extend with try/catch and an error field; for retries you either wrap fetch or move the request to TanStack Query. Zustand does not prescribe async patterns, which is freedom or chaos depending on team discipline.</p><h3>Redux Toolkit — same features, more structure</h3><pre>// store/appSlice.ts</pre><pre>import { createSlice, createAsyncThunk } from &quot;@reduxjs/toolkit&quot;;</pre><pre>export const fetchUser = createAsyncThunk(&quot;app/fetchUser&quot;, async () =&gt; {</pre><pre>  const res = await fetch(&quot;/api/me&quot;);</pre><pre>  return res.json();</pre><pre>});</pre><pre>const appSlice = createSlice({</pre><pre>  name: &quot;app&quot;,</pre><pre>  initialState: { count: 0, user: null as null | { id: string; name: string }, loading: false },</pre><pre>  reducers: {</pre><pre>    increment: (state) =&gt; { state.count += 1; },</pre><pre>  },</pre><pre>  extraReducers: (builder) =&gt; {</pre><pre>    builder</pre><pre>      .addCase(fetchUser.pending, (state) =&gt; { state.loading = true; })</pre><pre>      .addCase(fetchUser.fulfilled, (state, action) =&gt; {</pre><pre>        state.user = action.payload;</pre><pre>        state.loading = false;</pre><pre>      });</pre><pre>  },</pre><pre>});</pre><pre>export const { increment } = appSlice.actions;</pre><pre>export default appSlice.reducer;</pre><pre>// app/providers.tsx + useSelector in components</pre><p>RTK removes classic Redux boilerplate but still needs a store provider, typed hooks, and slice conventions — worth it when ten engineers touch the same state graph.</p><pre>// components/UserPanel.tsx — RTK async usage</pre><pre>&quot;use client&quot;;</pre><pre>import { useEffect } from &quot;react&quot;;</pre><pre>import { useAppDispatch, useAppSelector } from &quot;@/store/hooks&quot;;</pre><pre>import { fetchUser, increment } from &quot;@/store/appSlice&quot;;</pre><pre>export function UserPanel() {</pre><pre>  const dispatch = useAppDispatch();</pre><pre>  const count = useAppSelector((s) =&gt; s.app.count);</pre><pre>  const user = useAppSelector((s) =&gt; s.app.user);</pre><pre>  const loading = useAppSelector((s) =&gt; s.app.loading);</pre><pre>useEffect(() =&gt; {</pre><pre>    dispatch(fetchUser());</pre><pre>  }, [dispatch]);</pre><pre>return (</pre><pre>    &lt;div&gt;</pre><pre>      &lt;button onClick={() =&gt; dispatch(increment())}&gt;Count: {count}&lt;/button&gt;</pre><pre>      {loading ? &lt;p&gt;Loading…&lt;/p&gt; : &lt;p&gt;{user?.name ?? &quot;Guest&quot;}&lt;/p&gt;}</pre><pre>    &lt;/div&gt;</pre><pre>  );</pre><pre>}</pre><p>Same UX as the Zustand panel — more files, clearer audit trail in Redux DevTools when a bug report says “count jumped to 99 after refresh.” That traceability is why enterprise codebases keep RTK despite smaller alternatives.</p><h3>Bundle size comparison (approximate, gzipped)</h3><pre>// Measured on a minimal Next.js 15 client chunk (2026, rough)</pre><pre>// zustand@5 alone          ~ 1.2 kB gzip</pre><pre>// @reduxjs/toolkit + react-redux ~ 12–14 kB gzip</pre><pre>// Note: RTK buys DevTools, middleware patterns, large-team norms</pre><p>Numbers vary with tree-shaking and what you import. For a marketing site with one modal flag, neither library may be necessary — React context or URL state is enough. For a data-heavy dashboard, 12 kB might be cheap compared to engineering consistency.</p><p>Before you optimise kilobytes, profile real user metrics — I document that workflow in <a href="https://safdarali.in/blog/nextjs-performance-60-percent">Next.js performance case study</a>. A 10 kB store library rarely matters next to an unvirtualised table or a chart library. Still, greenfield SPAs with tight mobile budgets in India often pick Zustand because every gram of JS counts on 4G.</p><h3>10-criteria comparison table</h3><p>CriteriaZustandRedux ToolkitLearning curveLowMediumBoilerplateMinimalStructuredDevToolsPlugin availableExcellent nativeMiddlewareCustom, lightMature ecosystemAsync patternsYou write itcreateAsyncThunkTeam scaleSmall–mediumMedium–largeNext.js App RouterClient-only storeClient-only storeSelectorsInline functionsreselect / createSelectorTestingEasy store resetWell-documented patternsHiring familiarity in IndiaGrowing fastStill very common</p><h3>Before and after — prop drilling vs store</h3><pre>// BEFORE — theme passed through five layers</pre><pre>&lt;Layout theme={theme} setTheme={setTheme}&gt;</pre><pre>  &lt;Sidebar theme={theme} setTheme={setTheme}&gt;</pre><pre>    &lt;Nav theme={theme} setTheme={setTheme} /&gt;</pre><pre>// AFTER — Zustand (or RTK) at leaves only</pre><pre>const theme = useAppStore((s) =&gt; s.theme);</pre><pre>const setTheme = useAppStore((s) =&gt; s.setTheme);</pre><p>Do not reach for a global store because props are annoying once — reach when multiple distant trees share writable state that is not server data.</p><h3>Server state is not Redux or Zustand</h3><p>API lists, pagination, cache invalidation — use TanStack Query or Server Components + fetch with cache tags. I see teams stuff fetch results into Redux out of habit; that duplicates what Next.js already solves on public pages — see <a href="https://safdarali.in/blog/ssr-ssg-isr-nextjs-explained">SSR vs SSG vs ISR</a>.</p><h3>My production setup</h3><p>New dashboard in 2026: Zustand for UI chrome (sidebar, filters, wizard step). RTK when joining a legacy codebase that already exports slices and middleware. At my day job, the RTK codebase had time-travel debugging worth the bytes; greenfield internal tools get Zustand in under an hour.</p><p>Pair with <a href="https://safdarali.in/blog/rsc-vs-client-components">RSC boundaries</a> — stores are client-only; never import them into Server Components.</p><h3>The single takeaway</h3><p><strong>Zustand for new small/medium apps; RTK for large coordinated teams.</strong> Measure bundle impact, but optimise for maintainability. Most state should stay local or on the server.</p><p>Related: <a href="https://safdarali.in/blog/usecallback-vs-usememo-react-guide">useCallback vs useMemo</a>. <a href="https://safdarali.in/contact">Contact</a>.</p><p>If this helped you</p><p>I publish free tutorials and write-ups like this in my spare time — no paywall on the guides. If it saved you an afternoon of trial and error, you can support the work:</p><ul><li>→ <a href="https://buymeacoffee.com/safdarali">Buy me a coffee at buymeacoffee.com/safdarali</a></li><li>👉 <a href="https://www.youtube.com/@safdarali_?sub_confirmation=1">Subscribe to my YouTube channel</a> — it’s free; 70+ React &amp; Next.js tutorials</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a2c3541552d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tailwind CSS vs CSS Modules — What I Use in Production]]></title>
            <link>https://medium.com/@safdaralii/tailwind-css-vs-css-modules-what-i-use-in-production-5f9a67bfb676?source=rss-770eecb25a8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f9a67bfb676</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[safdar-ali]]></category>
            <category><![CDATA[css-modules]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <dc:creator><![CDATA[Safdar Ali]]></dc:creator>
            <pubDate>Sat, 11 Jul 2026 21:56:50 GMT</pubDate>
            <atom:updated>2026-07-11T21:56:50.214Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UCO783ubUwL_0ghM" /></figure><p>Every new project sparks the same debate: utility classes or scoped CSS files? I ship <strong>Tailwind CSS</strong> on most Next.js marketing sites — including <a href="https://safdarali.in/">safdarali.in</a> — but I still reach for <strong>CSS Modules</strong> when design tokens, animations, or designer handoff demand real stylesheets. This <strong>tailwind vs css modules</strong> comparison uses the same profile card in both approaches so you judge ergonomics, not different UIs.</p><h3>Same component — Tailwind version</h3><pre>// components/ProfileCard.tsx</pre><pre>type Props = { name: string; role: string; avatarUrl: string };</pre><pre>export function ProfileCardTailwind({ name, role, avatarUrl }: Props) {</pre><pre>  return (</pre><pre>    &lt;article className=&quot;flex gap-4 rounded-2xl border border-neutral-200 bg-white p-5 shadow-sm dark:border-white/10 dark:bg-neutral-900&quot;&gt;</pre><pre>      &lt;img</pre><pre>        src={avatarUrl}</pre><pre>        alt=&quot;&quot;</pre><pre>        className=&quot;h-14 w-14 rounded-full object-cover ring-2 ring-neutral-200 dark:ring-white/20&quot;</pre><pre>      /&gt;</pre><pre>      &lt;div&gt;</pre><pre>        &lt;h3 className=&quot;font-semibold text-neutral-950 dark:text-white&quot;&gt;{name}&lt;/h3&gt;</pre><pre>        &lt;p className=&quot;text-sm text-neutral-600 dark:text-neutral-400&quot;&gt;{role}&lt;/p&gt;</pre><pre>      &lt;/div&gt;</pre><pre>    &lt;/article&gt;</pre><pre>  );</pre><pre>}</pre><p>No context switch — layout, colour, and dark mode sit on the JSX. Colocation is excellent when you iterate alone. Class strings get long on complex grids; I break into smaller components instead of one 200-character line.</p><p>On a Bengaluru startup landing page last quarter, the designer changed card padding three times in one sprint. With Tailwind I adjusted utilities in the same PR as copy changes — no hunting a separate CSS file. That speed is why I default to utilities for marketing. The tradeoff is readability in code review: reviewers must know common class names or rely on preview deploys.</p><h3>Same component — CSS Modules version</h3><pre>// components/ProfileCard.module.css</pre><pre>.card {</pre><pre>  display: flex;</pre><pre>  gap: 1rem;</pre><pre>  padding: 1.25rem;</pre><pre>  border-radius: 1rem;</pre><pre>  border: 1px solid var(--border);</pre><pre>  background: var(--surface);</pre><pre>  box-shadow: 0 1px 2px rgb(0 0 0 / 0.06);</pre><pre>}</pre><pre>.avatar {</pre><pre>  width: 3.5rem;</pre><pre>  height: 3.5rem;</pre><pre>  border-radius: 9999px;</pre><pre>  object-fit: cover;</pre><pre>}</pre><pre>.name { font-weight: 600; }</pre><pre>.role { font-size: 0.875rem; color: var(--muted); }</pre><pre>// components/ProfileCard.tsx</pre><pre>import styles from &quot;./ProfileCard.module.css&quot;;</pre><pre>export function ProfileCardModules({ name, role, avatarUrl }: Props) {</pre><pre>  return (</pre><pre>    &lt;article className={styles.card}&gt;</pre><pre>      &lt;img src={avatarUrl} alt=&quot;&quot; className={styles.avatar} /&gt;</pre><pre>      &lt;div&gt;</pre><pre>        &lt;h3 className={styles.name}&gt;{name}&lt;/h3&gt;</pre><pre>        &lt;p className={styles.role}&gt;{role}&lt;/p&gt;</pre><pre>      &lt;/div&gt;</pre><pre>    &lt;/article&gt;</pre><pre>  );</pre><pre>}</pre><p>Designers reading Figma specs often prefer this — class names map to a stylesheet they can search. Theme variables live in one CSS file instead of duplicating dark: prefixes.</p><p>CSS Modules shine when you inherit a brand system documented as SCSS or plain CSS. I once joined a project where every spacing token lived in variables — rewriting into Tailwind would have taken weeks for zero user benefit. Modules let us wrap legacy styles with scoped class names while new React components shipped.</p><h3>8-criteria comparison table</h3><p>CriteriaTailwind CSSCSS ModulesColocation with JSXExcellentSplit filesDesign system tokenstailwind.config themeCSS variablesBundle sizePurged utilities (small)Only used classes shipComplex animationsVerbose in utilitiesNatural in CSSOnboarding juniorsLearn utility namesLearn CSS + scopingReadable diffsLong class stringsCleaner CSS diffsThird-party overrides<a href="https://dev.to/apply">@apply</a> or arbitrary:global() when neededNext.js default vibeVery commonBuilt-in support</p><h3>When Tailwind loses</h3><p>Tailwind is not weak — it is the wrong tool when the stylesheet is the product. Long-form editorial layouts, printable invoices, and white-label themes where each tenant ships different CSS files are easier to reason about in modules or global layers than in thousands of arbitrary utility strings.</p><p><strong>Keyframe-heavy animations</strong> — staggered reveals and complex hover chains read better in a module file. <strong>Print stylesheets</strong> — Tailwind can do it; CSS is clearer. <strong>Legacy design systems</strong> already documented in SCSS variables — rewriting into utilities is waste. <strong>Highly bespoke art-directed pages</strong> where every section has unique spacing not in your token scale — fighting arbitrary values is slower than writing CSS.</p><pre>/* ProfileCard.module.css — animation Tailwind would fight */</pre><pre>@keyframes riseIn {</pre><pre>  from { opacity: 0; transform: translateY(12px); }</pre><pre>  to { opacity: 1; transform: translateY(0); }</pre><pre>}</pre><pre>.cardAnimated {</pre><pre>  animation: riseIn 0.4s ease-out both;</pre><pre>}</pre><h3>Migrating styles — before and after</h3><pre>// BEFORE — global CSS leaked into production</pre><pre>.button {</pre><pre>  background: blue;</pre><pre>}</pre><pre>// Every &lt;button&gt; on the site turned blue</pre><pre>// AFTER — CSS Modules scope automatically</pre><pre>// Button.module.css</pre><pre>.root { background: var(--brand); }</pre><pre>// Only &lt;button className={styles.root}&gt;</pre><p>Tailwind avoids global leakage differently — utilities are atomic. Both beat unstructured global CSS from 2018 Create React App projects.</p><h3>The hybrid I use on client sites</h3><p>In production: Tailwind for layout, spacing, typography, responsive grids. CSS Modules (or a single globals.css) for animations, rare third-party overrides, and print rules. On a recent marketing rebuild, that split kept Lighthouse CSS payload small while designers still got a module for the hero animation — details in <a href="https://safdarali.in/blog/nextjs-performance-60-percent">performance case study</a>.</p><h3>My production setup</h3><p>Default stack: Next.js + TypeScript strict + Tailwind + cn() helper for conditional classes. I add modules per feature folder when a component accrues more than ~15 lines of custom CSS. At my day job, we banned new global selectors except resets.</p><p>Neither choice fixes bad component architecture — see <a href="https://safdarali.in/blog/nextjs-project-structure-guide-2026">Next.js folder structure guide</a> for how I colocate styles with features.</p><p>I also run Prettier with the Tailwind class sorter plugin on teams that use utilities — consistent order makes long class strings diff cleanly. CSS Module projects get stylelint for nesting and variable naming instead.</p><h3>The single takeaway</h3><p><strong>Tailwind for speed; CSS Modules for complexity.</strong> Pick per component, not per religion. Same card, two implementations — choose the file you will actually maintain six months from now.</p><p>Interview tip I give juniors in India: neither answer is wrong in isolation. Ask what the team already uses, whether designers pair with you daily, and whether the page is marketing or a long-lived dashboard. Match the toolchain to the delivery cadence, not Twitter polls.</p><p>Related: <a href="https://safdarali.in/projects">Projects</a>. <a href="https://safdarali.in/contact">Contact</a>.</p><p>If this helped you</p><p>I publish free tutorials and write-ups like this in my spare time — no paywall on the guides. If it saved you an afternoon of trial and error, you can support the work:</p><ul><li>→ <a href="https://buymeacoffee.com/safdarali">Buy me a coffee at buymeacoffee.com/safdarali</a></li><li>👉 <a href="https://www.youtube.com/@safdarali_?sub_confirmation=1">Subscribe to my YouTube channel</a> — it’s free; 70+ React &amp; Next.js tutorials</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f9a67bfb676" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React 19 Features — What Actually Changed and What I Use]]></title>
            <link>https://medium.com/@safdaralii/react-19-features-what-actually-changed-and-what-i-use-ad88509b3c70?source=rss-770eecb25a8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad88509b3c70</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-19]]></category>
            <dc:creator><![CDATA[Safdar Ali]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 18:41:04 GMT</pubDate>
            <atom:updated>2026-07-07T18:41:04.317Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FGbBaEvuV-0tfzbr" /></figure><p>React 19 shipped a laundry list of features. Twitter threads treated every hook like mandatory. In production on client sites and this portfolio, I adopted a subset — the ones that remove real bugs or UX jank — and ignored the rest until the ecosystem caught up. This is my honest <strong>react 19 features</strong> guide: what changed, code you can paste, and what I am still waiting on.</p><h3>What actually changed at a high level</h3><p>React 19 stabilised the Actions model (forms and mutations with pending state), added useOptimistic for instant UI feedback, introduced the use() hook for reading promises and context, improved hydration error messages, and made ref-as-prop cleaner. The compiler (React Forget) is separate — exciting, not required to upgrade.</p><p>Upgrade path: Next.js 15 projects already pin compatible React versions. Read <a href="https://safdarali.in/blog/rsc-vs-client-components">RSC vs client components</a> before mixing Actions with Server Components — boundaries still matter.</p><h3>React 19 hooks and APIs — quick reference table</h3><p>APIPurposeClient / ServerI use in prod?useOptimisticOptimistic UI while mutation runsClientYesuse()Read promise or contextBoth (with Suspense)Yes (with RSC)useActionStateForm action stateClientYesuseFormStatusPending from parent formClientYesref as propNo forwardRef boilerplateBothGradualDocument metadatatitle, meta in componentsClient (limited)Prefer Next.js metadata</p><h3>useOptimistic — instant feedback without lying to the user forever</h3><p>Cart quantity updates, like buttons, todo toggles — users expect instant UI. useOptimistic shows the next state while the server catches up, then reconciles on success or rolls back on error.</p><pre>&quot;use client&quot;;</pre><pre>import { useOptimistic, useTransition } from &quot;react&quot;;</pre><pre>import { updateQuantity } from &quot;./actions&quot;;</pre><pre>type Item = { id: string; qty: number };</pre><pre>export function CartLine({ item }: { item: Item }) {</pre><pre>  const [optimisticQty, setOptimisticQty] = useOptimistic(item.qty);</pre><pre>  const [isPending, startTransition] = useTransition();</pre><pre>function changeQty(next: number) {</pre><pre>    startTransition(async () =&gt; {</pre><pre>      setOptimisticQty(next);</pre><pre>      await updateQuantity(item.id, next);</pre><pre>    });</pre><pre>  }</pre><pre>return (</pre><pre>    &lt;div&gt;</pre><pre>      &lt;button onClick={() =&gt; changeQty(optimisticQty + 1)} disabled={isPending}&gt;</pre><pre>        +</pre><pre>      &lt;/button&gt;</pre><pre>      &lt;span&gt;{optimisticQty}&lt;/span&gt;</pre><pre>    &lt;/div&gt;</pre><pre>  );</pre><pre>}</pre><pre>// BEFORE — manual optimistic state with footguns</pre><pre>const [qty, setQty] = useState(item.qty);</pre><pre>const [pending, setPending] = useState(false);</pre><pre>async function bump() {</pre><pre>  const prev = qty;</pre><pre>  setQty(qty + 1); // optimistic</pre><pre>  setPending(true);</pre><pre>  try {</pre><pre>    await updateQuantity(item.id, qty + 1);</pre><pre>  } catch {</pre><pre>    setQty(prev); // easy to forget rollback paths</pre><pre>  } finally {</pre><pre>    setPending(false);</pre><pre>  }</pre><pre>}</pre><pre>// AFTER — useOptimistic + transition: rollback wired correctly</pre><h3>use() — promises and context without useEffect hacks</h3><pre>// Server Component passes a promise to client child</pre><pre>import { use } from &quot;react&quot;;</pre><pre>type Product = { id: string; name: string };</pre><pre>function ProductList({ productsPromise }: { productsPromise: Promise&lt;Product[]&gt; }) {</pre><pre>  const products = use(productsPromise); // suspends until resolved</pre><pre>  return (</pre><pre>    &lt;ul&gt;</pre><pre>      {products.map((p) =&gt; (</pre><pre>        &lt;li key={p.id}&gt;{p.name}&lt;/li&gt;</pre><pre>      ))}</pre><pre>    &lt;/ul&gt;</pre><pre>  );</pre><pre>}</pre><pre>// Parent (Server Component) creates the promise once</pre><pre>export default function Page() {</pre><pre>  const productsPromise = getProducts(); // do not await here</pre><pre>  return (</pre><pre>    &lt;Suspense fallback={&lt;p&gt;Loading products…&lt;/p&gt;}&gt;</pre><pre>      &lt;ProductList productsPromise={productsPromise} /&gt;</pre><pre>    &lt;/Suspense&gt;</pre><pre>  );</pre><pre>}</pre><p>In production I use use() with Server Components streaming data — same mental model as async server fetch, less client useEffect spaghetti.</p><h3>Actions and forms — less boilerplate than manual fetch</h3><pre>&quot;use client&quot;;</pre><pre>import { useActionState } from &quot;react&quot;;</pre><pre>import { subscribe } from &quot;./actions&quot;;</pre><pre>export function NewsletterForm() {</pre><pre>  const [state, formAction, pending] = useActionState(subscribe, { ok: false, message: &quot;&quot; });</pre><pre>return (</pre><pre>    &lt;form action={formAction}&gt;</pre><pre>      &lt;input name=&quot;email&quot; type=&quot;email&quot; required /&gt;</pre><pre>      &lt;button disabled={pending}&gt;{pending ? &quot;Sending…&quot; : &quot;Subscribe&quot;}&lt;/button&gt;</pre><pre>      {state.message &amp;&amp; &lt;p&gt;{state.message}&lt;/p&gt;}</pre><pre>    &lt;/form&gt;</pre><pre>  );</pre><pre>}</pre><p>Pair with Next.js Server Actions for mutations without a separate API route file — still validate on the server, still treat client state as untrusted.</p><h3>What I immediately adopted</h3><p><strong>useOptimistic</strong> on any user-facing mutation where latency is felt on Indian mobile networks. <strong>useActionState / useFormStatus</strong> on marketing forms — fewer lines than custom pending flags. <strong>use()</strong> with Suspense boundaries on catalog sections fed from server promises. <strong>Better hydration errors</strong> — saved me an hour debugging a client-only chart imported into a Server Component (fixed by splitting the leaf).</p><pre>// ref as prop — dropped forwardRef on new components</pre><pre>type ButtonProps = React.ComponentProps&lt;&quot;button&quot;&gt; &amp; { ref?: React.Ref&lt;HTMLButtonElement&gt; };</pre><pre>export function Button({ ref, ...props }: ButtonProps) {</pre><pre>  return &lt;button ref={ref} {...props} /&gt;;</pre><pre>}</pre><h3>What I’m waiting on</h3><p><strong>React Compiler (Forget)</strong> — I will enable it per-route after stable Next.js integration docs, not on day one of React 19. <strong>Document metadata in client trees</strong> — I still use Next.js generateMetadata for SEO. <strong>Full ecosystem typings</strong> — some third-party libs lagged React 19 types for weeks; I pinned versions until they caught up.</p><p>I am also not rewriting every forwardRef component overnight — new code uses ref-as-prop; old code migrates on touch.</p><p>Waiting is a strategy, not laziness. The compiler will change how much manual memo we write — see my <a href="https://safdarali.in/blog/usecallback-vs-usememo-react-guide">useCallback vs useMemo guide</a> for why I am not adding more memo hooks while the ecosystem catches up.</p><h3>My production setup</h3><p>In production: React 19 + Next.js 15, Server Components by default, React 19 Actions on forms that need pending UX, optimistic updates on commerce interactions. Performance work still lives in caching and bundle size — see <a href="https://safdarali.in/blog/nextjs-performance-60-percent">Next.js performance case study</a>.</p><p>When experimenting, I use the workflow in <a href="https://safdarali.in/blog/cursor-claude-react-workflow-2026">Cursor + Claude for React</a> — AI suggests React 19 APIs quickly, but I verify against official release notes before merge.</p><h3>The single takeaway</h3><p><strong>React 19 is not a rewrite mandate.</strong> Adopt optimistic UI, Actions, and use() where they solve problems you already have. Wait on compiler and metadata experiments until your stack documents them.</p><p>Related: <a href="https://safdarali.in/blog/nextjs-vs-react-which-to-learn-2026">Next.js vs React learning path</a>. <a href="https://safdarali.in/contact">Contact</a>.</p><p>If this helped you</p><p>I publish free tutorials and write-ups like this in my spare time — no paywall on the guides. If it saved you an afternoon of trial and error, you can support the work:</p><ul><li>→ <a href="https://buymeacoffee.com/safdarali">Buy me a coffee at buymeacoffee.com/safdarali</a></li><li>👉 <a href="https://www.youtube.com/@safdarali_?sub_confirmation=1">Subscribe to my YouTube channel</a> — it’s free; 70+ React &amp; Next.js tutorials</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad88509b3c70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SSR vs SSG vs ISR in Next.js — Plain English Explanation]]></title>
            <link>https://medium.com/@safdaralii/ssr-vs-ssg-vs-isr-in-next-js-plain-english-explanation-c9f8f881522e?source=rss-770eecb25a8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9f8f881522e</guid>
            <category><![CDATA[ssrs]]></category>
            <category><![CDATA[safdar-ali]]></category>
            <category><![CDATA[ssg]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[isr]]></category>
            <dc:creator><![CDATA[Safdar Ali]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 18:36:14 GMT</pubDate>
            <atom:updated>2026-07-07T18:36:14.075Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eEqd_7-WbF1DLiIP" /></figure><p>I’m <a href="https://safdarali.in/about">Safdar Ali</a>. For six months I treated every Next.js page like SSR because “server” sounded safest. Marketing pages were slower than they needed to be; dashboard pages were over-cached. <strong>SSR vs SSG in Next.js</strong> is not a popularity contest — it is a delivery choice: when HTML is built, how often it refreshes, and who pays the compute bill. This article is the plain-English map I wish I had, with code for all three modes and a flowchart you can screenshot.</p><h3>Three acronyms, one question: when is HTML built?</h3><p><strong>SSR (Server-Side Rendering)</strong> builds HTML on each request (or per-request cache miss). Fresh data, higher server load.</p><p><strong>SSG (Static Site Generation)</strong> builds HTML at deploy time. Fastest CDN delivery; stale until you redeploy unless you add revalidation.</p><p><strong>ISR (Incremental Static Regeneration)</strong> is SSG plus background refresh — static speed with a TTL. In App Router this is mostly fetch with next.revalidate.</p><pre>// Mental model — same page, three delivery timings</pre><pre>// SSG:  HTML built at deploy ──────────────────► CDN serves file</pre><pre>// ISR:  HTML built at deploy ──► stale ──► regen in background after N sec</pre><pre>// SSR:  HTML built when user hits URL ─────────► server sends fresh HTML</pre><p>None of these replace React. They describe when your React tree becomes HTML the browser can paint before hydration.</p><h3>Decision flowchart — which mode to pick</h3><pre>START: New Next.js page</pre><pre>                              |</pre><pre>                              v</pre><pre>                    Does Google need HTML</pre><pre>                    with real content on</pre><pre>                    first request?</pre><pre>                         /        \</pre><pre>                       NO          YES</pre><pre>                       |            |</pre><pre>                       v            v</pre><pre>              Authenticated      Is data identical</pre><pre>              dashboard / SPA?   for all users?</pre><pre>                    |                 /      \</pre><pre>                   YES               NO      YES</pre><pre>                    |                |        |</pre><pre>                    v                v        v</pre><pre>            &quot;use client&quot; +       SSR or      Changes</pre><pre>            client fetch         per-user    every hour+</pre><pre>            (no SSR win)         data?          /    \</pre><pre>                                /    \        NO    YES</pre><pre>                              YES    NO        |      |</pre><pre>                               |      |        v      v</pre><pre>                               v      v       SSG    ISR</pre><pre>                              SSR   ISR      (rare) (revalidate)</pre><pre>                                    or SSG</pre><pre>                                    + short</pre><pre>                                    revalidate</pre><p>Print that flowchart. When you are unsure, default marketing to ISR with a sensible revalidate, default logged-in dashboards to client rendering.</p><h3>SSG — build once, serve from the edge</h3><p>Use SSG for pages where data changes only when you deploy — legal pages, about pages, rarely updated landing heroes.</p><pre>// app/about/page.tsx — static by default (no fetch cache opts)</pre><pre>export default function AboutPage() {</pre><pre>  return (</pre><pre>    &lt;main&gt;</pre><pre>      &lt;h1&gt;About Safdar Ali&lt;/h1&gt;</pre><pre>      &lt;p&gt;Frontend engineer, Bengaluru — available for React / Next.js work.&lt;/p&gt;</pre><pre>    &lt;/main&gt;</pre><pre>  );</pre><pre>}</pre><pre>// Dynamic routes can still be SSG if you export generateStaticParams</pre><pre>export async function generateStaticParams() {</pre><pre>  const slugs = await getAllBlogSlugs();</pre><pre>  return slugs.map((slug) =&gt; ({ slug }));</pre><pre>}</pre><p>Tradeoff: a price change on an e-commerce SKU list will not appear until redeploy or ISR kicks in. For truly static content, that is a feature — zero origin load.</p><h3>ISR — static speed, controlled freshness</h3><pre>// app/products/page.tsx — ISR via fetch revalidate (App Router)</pre><pre>type Product = { id: string; name: string; price: number };</pre><pre>async function getProducts(): Promise&lt;Product[]&gt; {</pre><pre>  const res = await fetch(&quot;https://api.example.com/products&quot;, {</pre><pre>    next: { revalidate: 3600 }, // ISR: refresh at most every hour</pre><pre>  });</pre><pre>  if (!res.ok) throw new Error(&quot;Failed to load products&quot;);</pre><pre>  return res.json();</pre><pre>}</pre><pre>export default async function ProductsPage() {</pre><pre>  const products = await getProducts();</pre><pre>  return (</pre><pre>    &lt;ul&gt;</pre><pre>      {products.map((p) =&gt; (</pre><pre>        &lt;li key={p.id}&gt;{p.name} — ₹{p.price}&lt;/li&gt;</pre><pre>      ))}</pre><pre>    &lt;/ul&gt;</pre><pre>  );</pre><pre>}</pre><p>First visitor after TTL might still see stale HTML while regeneration runs — acceptable for catalog pages, unacceptable for live stock tickers. Know your freshness requirement before picking ISR.</p><h3>SSR — per-request HTML when data must be fresh</h3><pre>// app/dashboard/summary/page.tsx — SSR: no cache on fetch</pre><pre>async function getSummary(userId: string) {</pre><pre>  const res = await fetch(&quot;https://api.example.com/summary/&quot; + userId, {</pre><pre>    cache: &quot;no-store&quot;, // SSR — always fresh for this user</pre><pre>  });</pre><pre>  return res.json();</pre><pre>}</pre><pre>export default async function SummaryPage() {</pre><pre>  const session = await getSession();</pre><pre>  const summary = await getSummary(session.userId);</pre><pre>  return &lt;SummaryClient data={summary} /&gt;;</pre><pre>}</pre><p>SSR costs more at scale. Use it when personalisation or real-time correctness beats CDN economics — not because “server sounds professional.”</p><h3>SSR vs SSG vs ISR — comparison table</h3><p>CriteriaSSGISRSSRWhen HTML is builtDeploy timeDeploy + periodic regenEach requestTTFB on CDNFastestFast (often cached)SlowerData freshnessStale until deployTTL-basedReal-timeServer costLowestLow–mediumHighestSEOExcellentExcellentExcellentPer-user dataPoor fitPoor fitGood fitApp Router signalDefault static pagerevalidate: Ncache: no-store</p><h3>Marketing site vs dashboard — what I actually ship</h3><p><strong>Marketing site</strong> (public, SEO, shared content): ISR for blog and product listings, SSG for about/legal, Server Components for HTML. On a client rebuild I moved the blog to revalidate: 86400 and saw origin requests drop 70% — part of the story in <a href="https://safdarali.in/blog/nextjs-performance-60-percent">my Next.js performance case study</a>.</p><p><strong>Dashboard</strong> (authenticated, personal): client components, SWR or WebSockets, no ISR fantasy. Trying to ISR user-specific charts is how teams waste a sprint.</p><pre>// BEFORE — marketing page forced to SSR &quot;just because&quot;</pre><pre>export default async function PricingPage() {</pre><pre>  const plans = await fetch(&quot;https://api.example.com/plans&quot;, { cache: &quot;no-store&quot; });</pre><pre>  // Every visitor hits origin — same JSON for everyone</pre><pre>}</pre><pre>// AFTER — ISR: shared plans, CDN-friendly</pre><pre>export default async function PricingPage() {</pre><pre>  const res = await fetch(&quot;https://api.example.com/plans&quot;, { next: { revalidate: 3600 } });</pre><pre>  const plans = await res.json();</pre><pre>  // ...</pre><pre>}</pre><h3>My production setup</h3><p>In production I label routes in file comments — ISR 1h or SSR session — so the next developer does not &quot;optimise&quot; a dashboard into ISR by accident. Pair this with <a href="https://safdarali.in/blog/rsc-vs-client-components">RSC vs client components</a> — rendering mode and component boundary are two separate decisions.</p><p>At my day job, the mistake I see most is SSR everywhere because the team learned Pages Router getServerSideProps first. App Router caching is more granular — use it.</p><h3>The single takeaway</h3><p><strong>Pick rendering by freshness and audience, not acronym prestige.</strong> Marketing: ISR + SSG. Dashboards: client. Personalised SSR only when you mean it.</p><p>Related: <a href="https://safdarali.in/blog/nextjs-app-router-complete-guide-2026">App Router complete beginner guide</a>. <a href="https://safdarali.in/contact">Contact</a>.</p><p>If this helped you</p><p>I publish free tutorials and write-ups like this in my spare time — no paywall on the guides. If it saved you an afternoon of trial and error, you can support the work:</p><ul><li>→ <a href="https://buymeacoffee.com/safdarali">Buy me a coffee at buymeacoffee.com/safdarali</a></li><li>👉 <a href="https://www.youtube.com/@safdarali_?sub_confirmation=1">Subscribe to my YouTube channel</a> — it’s free; 70+ React &amp; Next.js tutorials</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9f8f881522e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript Strict Mode — Why I Use It in Every Project]]></title>
            <link>https://medium.com/@safdaralii/typescript-strict-mode-why-i-use-it-in-every-project-1b36f4f7f5af?source=rss-770eecb25a8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b36f4f7f5af</guid>
            <category><![CDATA[safdar-ali]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Safdar Ali]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 14:11:42 GMT</pubDate>
            <atom:updated>2026-07-05T14:11:42.213Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eyuFp7x-wIpLYGU1" /></figure><p>I’m <a href="https://safdarali.in/about">Safdar Ali</a>, a frontend engineer in Bengaluru. Three years ago I turned off strict mode on a client dashboard because the migration felt noisy. Two weeks later, a user with an empty profile name crashed the settings page in production — exactly the class of bug strictNullChecks would have flagged at compile time. Since then, <strong>typescript strict mode</strong> is non-negotiable on every React and Next.js repo I touch. This guide is the tsconfig I copy, the flags I care about, and the errors that actually save you hours.</p><h3>What “strict mode” actually means in TypeScript</h3><p>Strict mode is not one switch — it is a family of compiler checks bundled under strict: true in tsconfig.json. When enabled, TypeScript refuses code that relies on implicit any, unchecked null access, or loose function types.</p><p>The tradeoff is upfront friction: your first week on an old JavaScript codebase will surface hundreds of errors. The payoff is fewer 2am Slack messages and safer refactors when you rename a prop across forty components.</p><pre>// tsconfig.json — baseline I paste into new Next.js projects</pre><pre>{</pre><pre>  &quot;compilerOptions&quot;: {</pre><pre>    &quot;target&quot;: &quot;ES2017&quot;,</pre><pre>    &quot;lib&quot;: [&quot;dom&quot;, &quot;dom.iterable&quot;, &quot;esnext&quot;],</pre><pre>    &quot;allowJs&quot;: true,</pre><pre>    &quot;skipLibCheck&quot;: true,</pre><pre>    &quot;strict&quot;: true,</pre><pre>    &quot;noEmit&quot;: true,</pre><pre>    &quot;esModuleInterop&quot;: true,</pre><pre>    &quot;module&quot;: &quot;esnext&quot;,</pre><pre>    &quot;moduleResolution&quot;: &quot;bundler&quot;,</pre><pre>    &quot;resolveJsonModule&quot;: true,</pre><pre>    &quot;isolatedModules&quot;: true,</pre><pre>    &quot;jsx&quot;: &quot;preserve&quot;,</pre><pre>    &quot;incremental&quot;: true,</pre><pre>    &quot;plugins&quot;: [{ &quot;name&quot;: &quot;next&quot; }],</pre><pre>    &quot;paths&quot;: { &quot;@/&quot;: [&quot;./&quot;] }</pre><pre>  },</pre><pre>  &quot;include&quot;: [&quot;next-env.d.ts&quot;, &quot;/*.ts&quot;, &quot;/.tsx&quot;, &quot;.next/types//.ts&quot;],</pre><pre>  &quot;exclude&quot;: [&quot;node_modules&quot;]</pre><pre>}</pre><p>strict: true turns on strictNullChecks, noImplicitAny, and several related flags. You can enable them individually, but I have never found a good reason to run half-strict on a greenfield app.</p><h3>Strict flags — what each one does</h3><p>FlagCatchesPain levelstrictNullChecksnull / undefined used as valuesHigh on legacy APIsnoImplicitAnyParameters without typesMediumstrictFunctionTypesUnsafe callback assignmentsLow–mediumstrictBindCallApplyWrong bind/call/apply argsLownoImplicitThisAmbiguous this in functionsLowalwaysStrictEmits “use strict” per fileNoneuseUnknownInCatchVariablescatch (e) typed as anyLow</p><p>If you are migrating an old repo, enable flags one at a time in CI — fix noImplicitAny first, then strictNullChecks. That order reduces the simultaneous error flood.</p><h3>The 3 errors strict mode catches most often</h3><p>After dozens of code reviews, these three patterns account for most of the bugs strict mode prevented before merge — not theoretical type pedantry, real user-facing failures.</p><h3>1. Possibly undefined property access</h3><pre>type User = { id: string; displayName?: string };</pre><pre>function greet(user: User) {</pre><pre>  // Error under strictNullChecks: &#39;displayName&#39; is possibly &#39;undefined&#39;</pre><pre>  return &quot;Hello, &quot; + user.displayName.toUpperCase();</pre><pre>}</pre><pre>// Fix — narrow before use</pre><pre>function greetSafe(user: User) {</pre><pre>  const name = user.displayName ?? &quot;Guest&quot;;</pre><pre>  return &quot;Hello, &quot; + name.toUpperCase();</pre><pre>}</pre><h3>2. Implicit any on event handlers</h3><pre>// BEFORE — noImplicitAny flags the parameter</pre><pre>function handleChange(e) {</pre><pre>  setQuery(e.target.value);</pre><pre>}</pre><pre>// AFTER — explicit React type</pre><pre>import type { ChangeEvent } from &quot;react&quot;;</pre><pre>function handleChange(e: ChangeEvent&lt;HTMLInputElement&gt;) {</pre><pre>  setQuery(e.target.value);</pre><pre>}</pre><h3>3. Wrong API response shape assumed</h3><pre>type ApiOrder = { id: string; total: number; discount?: number };</pre><pre>async function getOrder(id: string): Promise&lt;ApiOrder&gt; {</pre><pre>  const res = await fetch(&quot;/api/orders/&quot; + id);</pre><pre>  return res.json();</pre><pre>}</pre><pre>function OrderSummary({ order }: { order: ApiOrder }) {</pre><pre>  // strictNullChecks: discount may be undefined</pre><pre>  const saved = order.discount ?? 0;</pre><pre>  return &lt;p&gt;Total: ₹{order.total - saved}&lt;/p&gt;;</pre><pre>}</pre><p>Number three is why I type API responses at the boundary — not inside every child component. One wrong assumption on fetch results propagates silently without strict types.</p><h3>The production bug strict mode would have caught</h3><p>At my day job, a checkout helper read user.address.line2 without checking if address existed. Indian users who signed up with phone-only onboarding had address: null. The page white-screened on submit.</p><pre>// BEFORE — passed review, failed in production</pre><pre>type User = { id: string; address: { line1: string; line2?: string } | null };</pre><pre>function formatShipping(user: User) {</pre><pre>  return user.address.line1 + &quot;, &quot; + user.address.line2;</pre><pre>}</pre><pre>// AFTER — compiler forces the guard</pre><pre>function formatShipping(user: User) {</pre><pre>  if (!user.address) return &quot;Address required&quot;;</pre><pre>  const line2 = user.address.line2 ?? &quot;&quot;;</pre><pre>  return user.address.line1 + (line2 ? &quot;, &quot; + line2 : &quot;&quot;);</pre><pre>}</pre><p>We added the guard in a hotfix. With strict null checks enabled from day one, the first version would never have compiled. That single incident paid for every strict migration I have done since.</p><h3>Migrating a component — before and after strict</h3><pre>// BEFORE — loose props, any sneaks in</pre><pre>export function ProductCard(props) {</pre><pre>  const { title, price, onAdd } = props;</pre><pre>  return (</pre><pre>    &lt;button onClick={() =&gt; onAdd(title)}&gt;</pre><pre>      {title} — ₹{price}</pre><pre>    &lt;/button&gt;</pre><pre>  );</pre><pre>}</pre><pre>// AFTER — explicit contract</pre><pre>type ProductCardProps = {</pre><pre>  title: string;</pre><pre>  price: number;</pre><pre>  onAdd: (title: string) =&gt; void;</pre><pre>};</pre><pre>export function ProductCard({ title, price, onAdd }: ProductCardProps) {</pre><pre>  return (</pre><pre>    &lt;button onClick={() =&gt; onAdd(title)}&gt;</pre><pre>      {title} — ₹{price}</pre><pre>    &lt;/button&gt;</pre><pre>  );</pre><pre>}</pre><p>The after version is longer by four lines. It is also grep-friendly: rename a prop and TypeScript lists every broken callsite instead of leaving undefined at runtime.</p><h3>Strict mode with Next.js App Router</h3><p>Next.js 15 projects ship with TypeScript by default. Server Components add one wrinkle: props and params are often Promise-wrapped. Strict typing there prevents awaiting the wrong shape.</p><pre>// app/blog/[slug]/page.tsx</pre><pre>type PageProps = { params: Promise&lt;{ slug: string }&gt; };</pre><pre>export default async function BlogPostPage({ params }: PageProps) {</pre><pre>  const { slug } = await params;</pre><pre>  const post = await getPost(slug);</pre><pre>  if (!post) return null;</pre><pre>  return &lt;Article post={post} /&gt;;</pre><pre>}</pre><p>Pair strict TypeScript with Server Components discipline from my <a href="https://safdarali.in/blog/rsc-vs-client-components">RSC vs client components guide</a> — types tell you what runs where; boundaries tell you what ships to the browser.</p><h3>When I temporarily relax a rule (rarely)</h3><p>Third-party libraries with broken types sometimes need @ts-expect-error on one line — not strict: false for the whole project. I also use skipLibCheck: true so node_modules type noise does not block builds — that is standard, not cheating.</p><pre>// Scoped escape — document why</pre><pre>// @ts-expect-error legacy chart lib ships wrong types until v4</pre><pre>&lt;LegacyChart data={metrics} /&gt;</pre><p>What I do not do: disable strict for “speed.” Typing saves more calendar time than it costs once the team is past the first migration week.</p><h3>My production setup</h3><p>In production I run strict: true, ESLint @typescript-eslint/recommended, and tsc --noEmit in CI before every merge. On this portfolio and client marketing sites, that combo caught unused env vars and wrong metadata types before they hit Vercel.</p><p>When I use AI-assisted refactors, I still read the diff — see my <a href="https://safdarali.in/blog/cursor-claude-react-workflow-2026">Cursor + Claude workflow</a> — but TypeScript strict mode is the safety net when autocomplete hallucinates a prop name.</p><p>Junior developers in Bengaluru often ask if strict is “for senior devs.” It is the opposite: strict mode teaches you the shape of data before runtime teaches you with user complaints.</p><h3>The single takeaway</h3><p><strong>TypeScript strict mode is cheap insurance.</strong> Turn it on in tsconfig.json, fix errors in order, and let the compiler catch null access, implicit any, and API drift before your users do.</p><p>Related: <a href="https://safdarali.in/blog/nextjs-vs-react-which-to-learn-2026">Next.js vs React — what to learn first</a>. Performance: <a href="https://safdarali.in/blog/nextjs-performance-60-percent">How I cut load time by 60% with Next.js</a>. Questions: <a href="https://safdarali.in/contact">safdarali.in/contact</a>.</p><p>If this helped you</p><p>I publish free tutorials and write-ups like this in my spare time — no paywall on the guides. If it saved you an afternoon of trial and error, you can support the work:</p><ul><li>→ <a href="https://buymeacoffee.com/safdarali">Buy me a coffee at buymeacoffee.com/safdarali</a></li><li>👉 <a href="https://www.youtube.com/@safdarali_?sub_confirmation=1">Subscribe to my YouTube channel</a> — it’s free; 70+ React &amp; Next.js tutorials</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b36f4f7f5af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js vs React — Which Should You Learn First in 2026?]]></title>
            <link>https://medium.com/@safdaralii/next-js-vs-react-which-should-you-learn-first-in-2026-fe060a2c5f12?source=rss-770eecb25a8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe060a2c5f12</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[safdar-ali]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Safdar Ali]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 13:52:52 GMT</pubDate>
            <atom:updated>2026-07-05T13:52:52.445Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iivCgxnnq3Pbfwu7" /><figcaption>Photo by <a href="https://unsplash.com/@jameswiseman?utm_source=medium&amp;utm_medium=referral">James Wiseman</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I’m <a href="https://safdarali.in/about">Safdar Ali</a>, a frontend engineer in Bengaluru. Last month a junior dev on LinkedIn asked me the same question I heard in 2022, 2024, and again this week: “Should I learn React or jump straight to Next.js?” After four years shipping both — marketing sites, dashboards, and this portfolio on <a href="https://safdarali.in/">safdarali.in</a> — my answer is not “always Next.js.” It’s learn React first, then Next.js fast. Here’s why, with code you can paste today.</p><h3>React and Next.js are not the same thing — stop comparing them like they are</h3><p><strong>React</strong> is a UI library. It handles components, state, and rendering. It does not ship routing, data fetching conventions, or a production server model out of the box.</p><p><strong>Next.js</strong> is a React framework. It sits on top of React and adds file-based routing, server rendering, image optimisation, and deployment defaults. When people search “nextjs vs react 2026,” they usually mean “plain React + Vite” vs “Next.js App Router.”</p><p>The tradeoff is clear: React alone gives you control. Next.js gives you speed to production — if you already understand what React is doing under the hood.</p><p>Think of it like driving. React is learning how an engine, steering, and brakes work. Next.js is a car that already has those parts assembled — plus GPS, airbags, and a service schedule. You can build a car from parts (React + Vite + React Router + your own SSR layer). Most product teams in 2026 don’t — they buy the assembled car and focus on where they’re going.</p><p>That analogy breaks if you don’t know what an engine is. Jump into Next.js without JSX, props, or state fundamentals and every error message feels like framework magic instead of JavaScript.</p><h3>Same feature, two stacks — a product list page side by side</h3><p>Take a simple product list: fetch data, render cards, link to detail pages. Here’s the split between a typical React + client fetch setup and Next.js App Router with a Server Component.</p><h3>React (Vite + client fetch) — you wire everything</h3><pre>// src/pages/ProductList.tsx — runs in the browser only</pre><pre>import { useEffect, useState } from &quot;react&quot;;</pre><pre>type Product = { id: string; name: string; price: number };</pre><pre>export function ProductList() {</pre><pre>  const [products, setProducts] = useState&lt;Product[]&gt;([]);</pre><pre>  const [loading, setLoading] = useState(true);</pre><pre>useEffect(() =&gt; {</pre><pre>    // SEO problem: crawlers see empty HTML until JS runs</pre><pre>    fetch(&quot;/api/products&quot;)</pre><pre>      .then((res) =&gt; res.json())</pre><pre>      .then(setProducts)</pre><pre>      .finally(() =&gt; setLoading(false));</pre><pre>  }, []);</pre><pre>if (loading) return &lt;p&gt;Loading…&lt;/p&gt;;</pre><pre>return (</pre><pre>    &lt;ul&gt;</pre><pre>      {products.map((p) =&gt; (</pre><pre>        &lt;li key={p.id}&gt;{p.name} — ₹{p.price}&lt;/li&gt;</pre><pre>      ))}</pre><pre>    &lt;/ul&gt;</pre><pre>  );</pre><pre>}</pre><h3>Next.js App Router — server fetch, less client JS</h3><pre>// app/products/page.tsx — Server Component by default</pre><pre>type Product = { id: string; name: string; price: number };</pre><pre>async function getProducts(): Promise&lt;Product[]&gt; {</pre><pre>  const res = await fetch(&quot;https://api.example.com/products&quot;, {</pre><pre>    next: { revalidate: 3600 }, // ISR-style cache — fresh enough for catalog pages</pre><pre>  });</pre><pre>  if (!res.ok) throw new Error(&quot;Failed to load products&quot;);</pre><pre>  return res.json();</pre><pre>}</pre><pre>export default async function ProductsPage() {</pre><pre>  const products = await getProducts();</pre><pre>// HTML arrives with content — better LCP, better SEO</pre><pre>  return (</pre><pre>    &lt;ul&gt;</pre><pre>      {products.map((p) =&gt; (</pre><pre>        &lt;li key={p.id}&gt;{p.name} — ₹{p.price}&lt;/li&gt;</pre><pre>      ))}</pre><pre>    &lt;/ul&gt;</pre><pre>  );</pre><pre>}</pre><p>Same UI. Different delivery model. On a client marketing site I migrated to App Router, that shift alone contributed to LCP dropping from 4.2s to 1.7s — I break down the full stack in my <a href="https://safdarali.in/blog/nextjs-performance-60-percent">Next.js performance case study</a>.</p><p>With the React version, you also own routing. You’d add React Router, configure a layout wrapper, and probably a loading skeleton component. None of that is hard — it’s just three extra files before you write business logic. Next.js collapses routing into folder names: app/products/page.tsx is both the route and the page. After four years of shipping React, that convention still saves me time on every new project.</p><p>The React approach wins when your API is a separate team’s problem and you only care about the browser. Next.js wins when HTML on first request matters — SEO, social previews, slow 4G in tier-2 Indian cities.</p><h3>Next.js vs React — 10 criteria compared</h3><p>CriteriaReact (Vite / CRA-style)Next.js (App Router)What it isUI libraryFull React frameworkRoutingYou add React RouterFile-based, built inSEO / first paintCSR unless you add SSRSSR, SSG, ISR nativeData fetchinguseEffect + fetch (client)async Server ComponentsLearning curveLower entry, higher assemblySteeper, fewer decisions laterBundle size controlYou own the whole graphRSC reduces client JS by defaultDeploymentStatic host + separate APIVercel/Node edge-readyBest for SPAsExcellentWorks, often overkillBest for marketing / content sitesExtra workExcellentJob market in India (2026)Still required everywhereListed on most product roles</p><p>Takeaway: React teaches you the language. Next.js teaches you how product teams ship that language at scale.</p><p>Neither row is a knockout punch. The job market row matters in India — recruiters still filter on “React” in CVs, but product job descriptions increasingly say “Next.js” or “React with SSR experience.” Learning both in sequence covers either filter without lying on your resume.</p><h3>When plain React still wins</h3><p>I still reach for React without Next.js when the app is a true SPA — authenticated dashboards, internal tools, or embeddable widgets inside another product. No SEO requirement, no server HTML, no file-based routing benefit.</p><pre>// When this is your whole app, Next.js adds ceremony you won&#39;t use:</pre><pre>// - Single route shell</pre><pre>// - Auth gate on the client</pre><pre>// - WebSocket or polling for live data</pre><pre>export function AnalyticsDashboard() {</pre><pre>  // 100% client-side — Server Components buy you nothing here</pre><pre>  return &lt;LiveChart streamUrl=&quot;/ws/metrics&quot; /&gt;;</pre><pre>}</pre><p>What nobody tells you is that forcing App Router patterns onto a dashboard can slow you down — you fight the framework instead of shipping features.</p><pre>// BEFORE — over-engineered dashboard page in Next.js</pre><pre>export default async function DashboardPage() {</pre><pre>  const session = await getServerSession(); // re-fetch every navigation</pre><pre>  const metrics = await fetchMetrics(session.userId);</pre><pre>  return &lt;DashboardClient initial={metrics} /&gt;; // still hydrates everything</pre><pre>}</pre><pre>// AFTER — honest SPA inside Next.js (or plain React if you prefer)</pre><pre>&quot;use client&quot;;</pre><pre>export default function DashboardPage() {</pre><pre>  const metrics = useLiveMetrics(); // WebSocket / SWR — belongs on client</pre><pre>  return &lt;DashboardClient metrics={metrics} /&gt;;</pre><pre>}</pre><p>I’ve shipped internal analytics tools as Create React App SPAs that ran for years without a rewrite. The users were logged-in employees on fast office networks — SEO was irrelevant. Pick the stack that matches the delivery model, not the hype cycle.</p><h3>When Next.js is the obvious pick in 2026</h3><p>Public websites, blogs, e-commerce, landing pages, anything that needs Google to see real HTML on first request. Also any full-stack product where API routes and server actions live next to UI — one repo, one deploy.</p><p>If you’re building like <a href="https://safdarali.in/projects">the client sites in my portfolio</a> — marketing-first, performance-sensitive, mobile-heavy — Next.js is the default I recommend in 2026.</p><pre>// app/products/[slug]/page.tsx — metadata + SSR in one file</pre><pre>import type { Metadata } from &quot;next&quot;;</pre><pre>type Props = { params: Promise&lt;{ slug: string }&gt; };</pre><pre>export async function generateMetadata({ params }: Props): Promise&lt;Metadata&gt; {</pre><pre>  const { slug } = await params;</pre><pre>  const product = await getProduct(slug);</pre><pre>  return {</pre><pre>    title: product.name + &quot; — Shop&quot;,</pre><pre>    description: product.summary, // Google + WhatsApp previews use this</pre><pre>    openGraph: { images: [product.imageUrl] },</pre><pre>  };</pre><pre>}</pre><pre>export default async function ProductPage({ params }: Props) {</pre><pre>  const { slug } = await params;</pre><pre>  const product = await getProduct(slug);</pre><pre>  return &lt;ProductDetail product={product} /&gt;;</pre><pre>}</pre><p>Try doing that cleanly in a client-only React app. You can — with react-helmet, a meta tag library, and probably a pre-render step — but you’re rebuilding what Next.js ships on day one. For public pages, that assembly tax adds up across every route.</p><h3>What I’d choose if starting today</h3><p>Week 1–4: React fundamentals — components, props, state, effects, lists, forms. Build small UI without a framework. I cover this path on my <a href="https://www.youtube.com/@safdarali_?sub_confirmation=1">YouTube channel</a> — 70+ free tutorials aimed at developers in India learning their first production stack.</p><p>Week 5–8: TypeScript basics, then Next.js App Router — one page, one layout, one Server Component fetch. Read my <a href="https://safdarali.in/blog/rsc-vs-client-components">RSC vs client components guide</a> before you sprinkle “use client” everywhere.</p><p>Month 3: Ship one real project — portfolio, blog, or small product — deploy to Vercel. Employers don’t hire tutorial completers. They hire people who shipped.</p><p>Free resources that worked for me: official React docs (beta.react.dev), Next.js learn course, and building in public on GitHub. Paid is optional until you need structured accountability — a ₹2,000 Udemy course is fine; a ₹2 lakh bootcamp is not required to land a first frontend role in India if your GitHub shows real work.</p><p>If you only have time for one thing this month: learn React. If you have two: add Next.js immediately after — not instead.</p><h3>Does React 19 change the nextjs vs react 2026 decision?</h3><p>React 19 stabilised features that used to be Next.js-only experiments — improved hydration, the use() hook, and better form actions. That does not make Next.js optional. It makes React itself more capable while Next.js still owns routing, caching, and deployment.</p><pre>// React 19 — use() for promises inside components (still client or RSC)</pre><pre>import { use } from &quot;react&quot;;</pre><pre>function ProductList({ productsPromise }: { productsPromise: Promise&lt;Product[]&gt; }) {</pre><pre>  const products = use(productsPromise); // suspends until resolved</pre><pre>  return (</pre><pre>    &lt;ul&gt;</pre><pre>      {products.map((p) =&gt; (</pre><pre>        &lt;li key={p.id}&gt;{p.name}&lt;/li&gt;</pre><pre>      ))}</pre><pre>    &lt;/ul&gt;</pre><pre>  );</pre><pre>}</pre><p>You can learn this API in a plain React sandbox. In production, I still reach for Next.js to wire the promise on the server and stream HTML. The library got sharper; the framework still saves calendar time.</p><p>Takeaway: React 19 is a reason to learn modern React, not a reason to skip Next.js on public web apps.</p><h3>My production setup</h3><p>In production I default to Next.js App Router with TypeScript strict mode, Tailwind CSS, and Server Components for anything public-facing. Client components are leaves — charts, modals, forms — not entire pages.</p><p>On a recent marketing rebuild, that discipline plus next/image and route caching moved Lighthouse performance from 54 to 91. The bundle analyser showed 38% less client JavaScript after we moved data fetching to the server — same pattern I document in the performance case study linked above.</p><p>Plain React stays in my toolbox for isolated widgets and legacy SPAs. Next.js is where I ship anything a user or crawler hits on the open web.</p><p>When I interview junior candidates in Bengaluru, I ask them to explain one component they wrote — props in, state updates, why a list needs keys. I don’t start with middleware or ISR. If they learned only Next.js templates, they often cannot answer. If they learned React first, the Next.js-specific questions become teachable in a week.</p><h3>The mistake I see most often</h3><p>Beginners skip React and copy-paste Next.js templates. They can deploy, but they cannot debug hydration errors, cannot explain why a component is client-only, and panic when the build fails on server/client boundaries.</p><pre>// BEFORE — copied from a template, broken mental model</pre><pre>&quot;use client&quot;;</pre><pre>export default function Page() {</pre><pre>  useEffect(() =&gt; {</pre><pre>    fetch(&quot;/api/data&quot;).then(/* ... */); // could be server-side</pre><pre>  }, []);</pre><pre>}</pre><pre>// AFTER — fetch on server, interactivity only where needed</pre><pre>export default async function Page() {</pre><pre>  const data = await getData(); // runs once on server</pre><pre>  return &lt;ProductGrid data={data} /&gt;;</pre><pre>}</pre><p>Learn React so the second snippet feels natural — not magic.</p><p>Bootcamps that advertise “Full Stack Next.js in 4 weeks” without JSX fundamentals produce developers who can clone a Vercel deploy — until the first production bug. I’d rather you ship one ugly React todo app you fully understand than a polished template you cannot modify.</p><h3>The single takeaway</h3><p><strong>Next.js vs React in 2026 is the wrong either/or.</strong> React is the skill. Next.js is how most product teams apply that skill on the web. Learn React first, ship one Next.js project second, and measure everything — LCP, bundle size, time-to-first-commit.</p><p>I still get DMs asking which certificate to buy. Buy none until you’ve built something. Certificates prove attendance; GitHub repos prove competence. Start with React this week, add Next.js next month, and publish the result — even if it’s rough.</p><p>Related reading: <a href="https://dev.to/blog/nextjs-performance-60-percent">How I cut load time by 60% with Next.js App Router</a>. More case studies: <a href="https://safdarali.in/projects">safdarali.in/projects</a>. Questions: <a href="https://safdarali.in/contact">safdarali.in/contact</a>.</p><p>If this helped you</p><p>I publish free tutorials and write-ups like this in my spare time — no paywall on the guides. If it saved you an afternoon of trial and error, you can support the work:</p><ul><li>→ <a href="https://buymeacoffee.com/safdarali">Buy me a coffee at buymeacoffee.com/safdarali</a></li><li>👉 <a href="https://www.youtube.com/@safdarali_?sub_confirmation=1">Subscribe to my YouTube channel</a> — it’s free; 70+ React &amp; Next.js tutorials</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe060a2c5f12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Free Video Thumbnail Generator That Never Uploads Your Files]]></title>
            <link>https://medium.com/@safdaralii/i-built-a-free-video-thumbnail-generator-that-never-uploads-your-files-82610ae5b2f2?source=rss-770eecb25a8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/82610ae5b2f2</guid>
            <category><![CDATA[safdar-ali]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[thumbnail-generator]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Safdar Ali]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 00:12:05 GMT</pubDate>
            <atom:updated>2026-06-07T00:12:05.174Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="I Built a Free Video Thumbnail Generator That Never Uploads Your Files" src="https://cdn-images-1.medium.com/max/1024/1*yaw-9wPGogUNzAOqp3z_xg.png" /></figure><p>Every creator hits the same wall: you finished the video, exported the MP4, uploaded to YouTube — and <strong>forgot the custom thumbnail</strong>.</p><p>Your best frame is already inside that file. You just need to grab it.</p><p>Most online tools make you <strong>upload the entire video to their server</strong>. That is slow for large files, risky for unreleased content, and often ends with a watermark unless you pay.</p><p>So I built <a href="https://framesnap.safdarali.in/"><strong>FrameSnap</strong></a> — a free browser tool that extracts thumbnails locally. No account. No watermark. Your video never leaves your device.</p><h3>The problem with “free” thumbnail tools</h3><p>Search for <em>free video thumbnail generator online</em> and you get dozens of results. Most fall into two camps:</p><ol><li><strong>Server-upload converters</strong> — your file goes to their cloud, gets processed, comes back with a logo on the free tier.</li><li><strong>Design apps</strong> — great for templates and text overlays, overkill when you already have a strong frame in your footage.</li></ol><p>Creators actually need something simpler:</p><ul><li>Scrub to the right moment</li><li>Export at <strong>1280×720</strong> for YouTube</li><li>Download <strong>PNG or JPG</strong></li><li>Optionally grab <strong>6–25 frames</strong> to compare before deciding</li><li>Do it <strong>without sending client footage to a random SaaS</strong></li></ul><p>That last point matters if you record courses, agency work, or anything under NDA.</p><h3>Why client-side wins here</h3><p>Modern browsers can decode MP4, WebM, and MOV through the &lt;video&gt; element. The <a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API">Canvas API</a> can draw any frame to a bitmap. Download via blob URL. Done.</p><p>The flow in FrameSnap:</p><pre>User selects file → video loads in memory → set currentTime → drawImage to canvas → export PNG/JPG</pre><p>No API route handles the video. No S3 bucket. No queue.</p><p><strong>Trade-offs I accepted:</strong></p><p>Works greatDoes not workLocal MP4, WebM, MOV, MKVYouTube watch-page URLs (platform blocks direct access)Direct .mp4 URLsDRM-protected streamsBatch export via auto-snap intervalsReplacing Photoshop for layered design</p><p>For the 80% case — <em>“I have an exported MP4 and need a still”</em> — client-side is faster and more private than upload-and-wait.</p><h3>Features I cared about as a user</h3><p>These shaped the product more than any framework choice:</p><p><strong>Auto-snap presets</strong> — Quick 6 frames, or every 2%/4%/5% of video length. Picking one thumbnail from a 15-minute video by manual scrubbing is painful.</p><p><strong>Download all as ZIP</strong> — Compare candidates side-by-side before adding text in Canva.</p><p><strong>Original aspect ratio</strong> — Portrait video stays portrait. No black bars from forcing everything into 16:9.</p><p><strong>JPG quality slider</strong> — YouTube’s custom thumbnail limit is 2 MB. PNG screen recordings blow past that; JPG at 90% usually does not.</p><p><strong>Direct MP4 URL tab</strong> — If your file is hosted at https://yoursite.com/demo.mp4, paste and go. Not a Google Drive preview link — an actual file URL.</p><h3>Stack (for the curious)</h3><ul><li><a href="https://nextjs.org/"><strong>Next.js 16</strong></a> — App Router, static blog with scheduled publishing</li><li><strong>TypeScript</strong> — the fun part is typed canvas math, not the boilerplate</li><li><strong>Canvas + HTML5 Video</strong> — frame capture</li><li><a href="https://stuartk.com/jszip/"><strong>JSZip</strong></a> — batch downloads</li><li><strong>Vercel</strong> — deploy at <a href="https://framesnap.safdarali.in/">framesnap.safdarali.in</a></li></ul><p>100% client-side processing. The server only serves HTML/JS.</p><h3>Try it</h3><p>👉 <a href="https://framesnap.safdarali.in/"><strong>framesnap.safdarali.in</strong></a></p><ol><li>Drop an MP4 (or paste a direct video URL)</li><li>Scrub or use auto-snap</li><li>Export HD (1280×720) PNG/JPG</li><li>Upload to YouTube Studio</li></ol><p>I also wrote a longer comparison guide on the site: <a href="https://framesnap.safdarali.in/blog/video-thumbnail-generator-online">Free Video Thumbnail Generator Online</a>.</p><h3>What’s next</h3><ul><li>More export presets for Shorts/Reels covers</li><li>Keyboard shortcuts for power users</li><li>Better error messages for codec edge cases</li></ul><p>If you try it and it saves you ten minutes before your next upload, that is enough for me.</p><h3>Links</h3><ul><li><strong>Tool:</strong> <a href="https://framesnap.safdarali.in/">FrameSnap</a></li><li><strong>Blog:</strong> <a href="https://framesnap.safdarali.in/blog">framesnap.safdarali.in/blog</a></li><li><strong>Portfolio:</strong> <a href="https://safdarali.in/">safdarali.in</a></li><li><strong>YouTube:</strong> <a href="https://www.youtube.com/@safdarali_?sub_confirmation=1">@safdarali_</a></li><li><strong>X / Twitter:</strong> <a href="https://x.com/safdarali___">@safdarali___</a></li><li><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/safdarali25/">Safdar Ali</a></li><li><strong>GitHub:</strong> <a href="https://github.com/Safdar-Ali-India">Safdar-Ali-India</a></li></ul><h3>Support the project</h3><p>FrameSnap is free with no export limits. If it helps your workflow, you can <a href="https://buymeacoffee.com/safdarali">buy me a coffee ☕</a> — it keeps side projects like this alive.</p><p><em>Built by </em><a href="https://safdarali.in/"><em>Safdar Ali</em></a><em>. Feedback welcome in the comments — especially if you hit a codec or browser edge case I have not seen yet.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82610ae5b2f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>