<?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 Somnathbaidya on Medium]]></title>
        <description><![CDATA[Stories by Somnathbaidya on Medium]]></description>
        <link>https://medium.com/@somnathbaidya82?source=rss-52f5609873cf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*0BVdNAe_mMtebBlw</url>
            <title>Stories by Somnathbaidya on Medium</title>
            <link>https://medium.com/@somnathbaidya82?source=rss-52f5609873cf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 00:43:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@somnathbaidya82/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[My Experience Building a Full-Stack App (Next.js + Express + MongoDB)]]></title>
            <link>https://medium.com/@somnathbaidya82/my-experience-building-a-full-stack-app-next-js-express-mongodb-672da7b31a37?source=rss-52f5609873cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/672da7b31a37</guid>
            <category><![CDATA[third-party-cookie]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[cross-origin]]></category>
            <category><![CDATA[jwt-authentication]]></category>
            <dc:creator><![CDATA[Somnathbaidya]]></dc:creator>
            <pubDate>Wed, 12 Nov 2025 08:11:49 GMT</pubDate>
            <atom:updated>2025-11-12T08:24:48.300Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dT6TE4d5BScPu_Mn3hFhTA.png" /></figure><p>I am turning to full-stack from a frontend developer. As a React.Js developer, I wanted to stick with the javascript ecosystem. So, intuitively I picked Next.Js to smoothen the transition, reused some of my react code blocks to do so &amp; built a few simple Node.Js apps.</p><p>Problems occurred as I built the frontend in Next.js and the backend with Express+MongoDB Compass, then deployed them on Vercel and Render separately.</p><h3>I ) Deployment Failure Due to Local MongoDB Setup :</h3><p>The Express + MongoDB application was deployed on <strong>Render</strong>, but it was still using a <strong>local MongoDB Compass setup</strong> instead of a cloud database.</p><p>As Render (and services like Vercels) are designed to connect to <strong>hosted databases</strong>, the deployment failed immediately.</p><h3>Resolve :</h3><p>I learned about the issue and created a MongoDB Atlas cluster, connected it with MongoDB Compass using the atlas connection string to access and manage the database in the cloud.</p><h3>II ) Incorrect Cookie Handling in Next.js :</h3><p>Initially, cookies were being <strong>set and verified in Next.js</strong> rather than in the <strong>Express backend</strong>. Since both environments were completely separate, it caused conflicts.</p><h3>A quick recap :</h3><ul><li>Only the <strong>backend</strong> should create and remove secure cookies (httpOnly, secure, sameSite).</li><li>The <strong>frontend</strong> should not handle sensitive cookie logic due to potential <strong>XSS</strong> <strong>attack</strong> risks.</li></ul><p>So the ideal way is to <strong>set and clear cookies from the backend</strong> during login and logout, while the frontend simply managed routing logic.</p><p>Also I was trying to verify cookie in <strong>Next.js Middleware</strong>, which runs in an <strong>Edge Runtime environment — not Node.js</strong>.</p><p>This environment can only check <strong>if a cookie exists</strong>, not verify it.</p><h3>Resolve :</h3><ul><li>Removed app/api/session.</li><li>Only conditional redirection logic (if-else checks) was kept in middleware.js.</li></ul><pre>export function middleware(req) {<br>  const session = req.cookies.get(&quot;session_marker&quot;)?.value;<br>  const path = req.nextUrl.pathname;<br><br>  if (!session &amp;&amp; path !== &quot;/login&quot;) {<br>    return NextResponse.redirect(new URL(&quot;/login&quot;, req.url));<br>  }<br><br>  if (session &amp;&amp; path === &quot;/login&quot;) {<br>    return NextResponse.redirect(new URL(&quot;/home&quot;, req.url));<br>  }<br><br>  return NextResponse.next();<br>}</pre><h3>III ) Cross-Origin Cookie Issue :</h3><p>New issue appeared as I deployed them.</p><p>While testing locally, both frontend and backend shared the same origin, so cookies persisted correctly.<br>But, in production:</p><ul><li><strong>Frontend</strong> <strong>: </strong>deployed on vercel.app.</li><li><strong>Backend</strong> <strong>:</strong> deployed on onrender.com.</li></ul><p>In production when a user logged in, the backend generated a cookie correctly using the firebase token. The cookie was visible in the browser’s DevTools for a fraction of sec but disappeared immediately as the page reloaded.</p><p>Now the user is redirected back to the login page, as if never authenticated.</p><pre>// Login (set)<br>res.cookie(&quot;auth_token&quot;, token, {<br>  httpOnly: true,<br>  secure: process.env.NODE_ENV === &quot;production&quot;,  <br>  sameSite: process.env.NODE_ENV === &quot;production&quot; ? &quot;none&quot; : &quot;lax&quot;,<br>  maxAge: 7 * 24 * 60 * 60 * 1000, // expires in 7 days<br>  path: &quot;/&quot;,<br>}); to fix the issue :</pre><pre>// Logout (clear)<br>res.clearCookie(&quot;auth_token&quot;, {<br>  httpOnly: true,<br>  secure: process.env.NODE_ENV===&quot;production&quot;,<br>  sameSite:process.env.NODE_ENV===&quot;production&quot;? &quot;none&quot; : &quot;lax&quot;,<br>  path: &quot;/&quot;,<br>});</pre><ul><li><strong>Using</strong> <strong>CHIPS (Cookies Having Independent Partitioned State).</strong></li><li><strong>Setting</strong> domain<strong> attributes for cookies explicitly.</strong></li><li>But that won’t work, as vercel.app &amp; onrender.com are completely different top-level domains</li></ul><pre>res.cookie(&quot;auth_token&quot;, token, {<br>  ....<br>  partitioned: true, // CHIPS<br>  domain: &quot;https://mern-todo-8f4w.onrender.com/&quot;,<br>});</pre><ul><li><strong>Adding proxy routes in </strong>next.config.js to simulate same-origin behaviour, which worked only on development.</li></ul><pre>/** @type {import(&#39;next&#39;).NextConfig} */<br>const nextConfig = {<br>  async rewrites() {<br>    return [<br>      {<br>        source: &quot;/api/:path*&quot;,<br>        destination: &quot;https://mern-todo-8f4w.onrender.com/:path*&quot;, <br>      },<br>    ];<br>  },<br>};<br><br>module.exports = nextConfig;</pre><h3>The Fact :</h3><p>Cross-origin cookies between different deployment domains are unreliable and often blocked by browsers.</p><h3>Implementing a Hybrid JWT + Session Authentication :</h3><p>Here is how it works,</p><h3>1. Login request :</h3><ul><li>The frontend sends a <strong>Firebase token</strong> to the backend.</li><li>The backend verifies it using firebase-admin.</li><li>A <strong>JWT</strong> is signed with verified user details.</li><li>A <strong>sessionId</strong> is generated using crypto.</li><li>Both JWT and sessionId are sent back to the frontend, and the session is stored in the database.</li></ul><h3>2. Frontend handling :</h3><ul><li>JWT is saved in localStorage.</li><li>A client-side cookie is created containing the sessionId, used only for routing logic in middleware.</li></ul><h3>3. Middleware routing :</h3><ul><li>Checks if the sessionId cookie exists.</li><li>Redirects the user to the home page if it does, otherwise to the login/signup page.</li></ul><h3>4. Authenticated requests :</h3><ul><li>Every request includes both JWT (from localStorage) and sessionId (from cookies) in the headers.</li></ul><h3>5. Authentication in backend :</h3><ul><li>The JWT is verified.</li><li>The sessionId is checked against the database.</li><li>If both are valid, the user data is attached to the request and proceed to server.</li></ul><p>I learned that cross-origin setups rarely have a conventional fix — you often need to experiment, blending a few ideas to obtain the right fit that works for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=672da7b31a37" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>