<?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 Md. Aminul Islam on Medium]]></title>
        <description><![CDATA[Stories by Md. Aminul Islam on Medium]]></description>
        <link>https://medium.com/@rahathssn?source=rss-c4665d593e17------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lBiDxQdv4j3RJ80Nhfxk0Q.jpeg</url>
            <title>Stories by Md. Aminul Islam on Medium</title>
            <link>https://medium.com/@rahathssn?source=rss-c4665d593e17------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 09:02:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rahathssn/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[Handling Axios Requests in Next.js for Both SSR and CSR]]></title>
            <link>https://medium.com/@rahathssn/handling-axios-requests-in-next-js-for-both-ssr-and-csr-9803ae751ca5?source=rss-c4665d593e17------2</link>
            <guid isPermaLink="false">https://medium.com/p/9803ae751ca5</guid>
            <category><![CDATA[client-side-rendering]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[axios]]></category>
            <category><![CDATA[cookies]]></category>
            <dc:creator><![CDATA[Md. Aminul Islam]]></dc:creator>
            <pubDate>Mon, 11 Aug 2025 17:45:24 GMT</pubDate>
            <atom:updated>2025-08-11T17:45:24.801Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OvtTigCKpU3_lBlMGpQ6dA.png" /><figcaption>Handling Axios Requests in Next.js</figcaption></figure><p>When building a Next.js application, we will often need to call APIs both <strong>on the server (SSR)</strong> and <strong>on the client (CSR)</strong>.</p><p>While Axios makes API calls simple, <strong>cookies</strong> can be tricky to handle across these environments, especially for authentication tokens like accessToken.</p><p>In this article, we will explore the problem, the solution, and some best practices<strong> </strong>so we can have a single Axios setup that works everywhere.</p><h3>The Problem</h3><p>Next.js runs your code in two environments:</p><ol><li><strong>Client-Side Rendering (CSR):</strong> Runs in the browser. If withCredentials: true is set and CORS is configured, cookies are sent automatically.</li><li><strong>Server-Side Rendering (SSR): </strong>Runs in Node.js. Axios does not automatically include the client’s cookies. We must attach them manually.</li></ol><p>This creates two main pain points:</p><ul><li><strong>Missing cookies in SSR</strong> → API calls fail with 401 Unauthorized.</li><li><strong>Different Axios logic for SSR &amp; CSR</strong> → messy, duplicated code.</li></ul><h3>The Solution: A Universal Axios Instance</h3><p>We can solve this by creating <strong>one Axios instance</strong> that:</p><ul><li>Detects if it’s running on the server or client.</li><li>Automatically attaches cookies during SSR using next/headers.</li><li>Works the same way for CSR (browser) requests.</li></ul><pre>import axios from &quot;axios&quot;;<br>import envConfig from &quot;@/config/envConfig&quot;;<br><br>// Detect environment<br>const isServer = typeof window === &quot;undefined&quot;;<br><br>// Create Axios instance<br>const axiosInstance = axios.create({<br>  baseURL: envConfig.baseApi,<br>  withCredentials: true, // for client-side cookies<br>  headers: {<br>    Accept: &quot;application/json&quot;,<br>  },<br>});<br><br>// Request interceptor<br>axiosInstance.interceptors.request.use(<br>  async (config) =&gt; {<br>    if (isServer) {<br>      const { cookies } = await import(&quot;next/headers&quot;);<br>      const cookieStore = await cookies();<br>      const token = cookieStore.get(&quot;accessToken&quot;)?.value;<br><br>      if (token) {<br>        config.headers?.set?.(&quot;Cookie&quot;, `accessToken=${token}`);<br>      }<br>    }<br>    return config;<br>  },<br>  (error) =&gt; Promise.reject(error)<br>);<br><br>// Response passthrough<br>axiosInstance.interceptors.response.use(<br>  (response) =&gt; response,<br>  (error) =&gt; Promise.reject(error)<br>);<br><br>export default axiosInstance;</pre><h3>How It Works</h3><ul><li><strong>SSR</strong> → Reads cookies from the incoming request using next/headers and attaches them to the outgoing Axios request.</li><li><strong>CSR</strong> → Browser sends cookies automatically when withCredentials: true is set and CORS is correct.</li><li><strong>Single Instance</strong> → Same logic for server and client.</li></ul><figure><img alt="SSR and CSR diagram" src="https://cdn-images-1.medium.com/max/1024/1*nXQPlsUH8_jxU0EejoAe-w.png" /></figure><h3>Pros and ❌ Cons</h3><h4>Pros</h4><ul><li><strong>One Axios instance</strong> for SSR &amp; CSR.</li><li><strong>Seamless auth</strong> across both environments.</li><li><strong>No boilerplate</strong> cookie forwarding in every SSR call.</li><li><strong>Next.js friendly</strong> with dynamic imports.</li><li><strong>Easy maintenance</strong> from a single config file.</li></ul><h4>Cons</h4><ul><li>Server-only code must be carefully isolated.</li><li>Slightly more complex setup for beginners.</li><li>Depends on next/headers (Next.js-specific).</li><li>If your API only supports Bearer tokens, you’ll need tweaks.</li><li>Still needs correct cookie &amp; CORS configuration.</li></ul><h3>When to Use / When Not to Use</h3><h4>Use When:</h4><ul><li>You have authenticated API calls in <strong>both SSR &amp; CSR</strong>.</li><li>You want <strong>centralized Axios configuration</strong>.</li><li>Your API uses <strong>cookie-based authentication</strong>.</li><li>You’re building with <strong>Next.js</strong> (App Router or Pages Router).</li></ul><h4>Avoid When:</h4><ul><li>Your site is <strong>static-only</strong> (SSG) with no SSR.</li><li>You store tokens in <strong>local/session storage</strong> instead of cookies.</li><li>Your SSR and CSR calls go to <strong>different APIs</strong>.</li><li>You’re <strong>not using Next.js</strong>.</li></ul><p>With this setup, we can make authenticated requests anywhere in our app without duplicating code or worrying about whether we are on the server or client.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9803ae751ca5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>