<?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 Palsagnik on Medium]]></title>
        <description><![CDATA[Stories by Palsagnik on Medium]]></description>
        <link>https://medium.com/@palsagnik2001?source=rss-bf53a7123a68------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*LHKP3GK7wePbO23n</url>
            <title>Stories by Palsagnik on Medium</title>
            <link>https://medium.com/@palsagnik2001?source=rss-bf53a7123a68------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:18:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@palsagnik2001/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[Migrating react-native-track-player to React Native New Architecture — What Broke and How I Fixed…]]></title>
            <link>https://medium.com/@palsagnik2001/migrating-react-native-track-player-to-react-native-new-architecture-what-broke-and-how-i-fixed-cc97943e2373?source=rss-bf53a7123a68------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc97943e2373</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[mobile-development]]></category>
            <dc:creator><![CDATA[Palsagnik]]></dc:creator>
            <pubDate>Sun, 19 Apr 2026 16:10:48 GMT</pubDate>
            <atom:updated>2026-04-19T16:10:48.940Z</atom:updated>
            <content:encoded><![CDATA[<h3>Migrating react-native-track-player to React Native New Architecture — What Broke and How I Fixed It</h3><p><em>Three native crashes, one patch file, and what it taught me about JSI, Android services, and the New Architecture internals</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NiE7AC4YvxDgghrQW8oVBQ.png" /></figure><p>I’m building a Spotify-like podcast player in React Native using the New Architecture (Fabric + TurboModules/JSI). The app needs background audio that survives app kills, lock screen controls, and MMKV-based queue persistence — the full deal.</p><p>I chose react-native-track-player (RNTP) v4.1.2 because it&#39;s the most complete audio library in the RN ecosystem. But on a New Architecture project, it crashed immediately at startup with three separate native errors.</p><p>This article documents all three crashes, explains exactly why each one happens, and shows the patches I wrote to fix them. All fixes are maintained via patch-package so they survive yarn install.</p><p>If you’re hitting any of these errors, this should save you hours.</p><h3>The Setup</h3><ul><li>React Native 0.76.x (New Architecture enabled by default)</li><li>react-native-track-player 4.1.2</li><li>newArchEnabled=true in android/gradle.properties</li><li>Android target SDK 34</li></ul><h3>Crash 1 — Exception in HostObject::get for prop &#39;TrackPlayerModule&#39;</h3><h3>The error</h3><pre>Exception in HostObject::get for prop &#39;TrackPlayerModule&#39;</pre><p>The app crashed at startup before any JS ran. Nothing in the JS layer, pure native.</p><h3>Root cause</h3><p>When New Architecture boots, it inspects every @ReactMethod on your native modules to build a type-safe JSI interface. It reads the <strong>return type</strong> of each method to generate the bridge.</p><p>The problem was Kotlin’s expression body syntax. RNTP’s MusicModule.kt had methods written like this:</p><pre>// BROKEN — expression body returns Job<br>@ReactMethod<br>fun add(data: ReadableArray?, callback: Promise) = scope.launch {<br>    // async work<br>}</pre><p>In Kotlin, = scope.launch { } is expression body syntax — the function&#39;s return value is whatever scope.launch {} returns. And scope.launch {} returns a kotlinx.coroutines.Job object.</p><p>So New Architecture saw:</p><pre>@ReactMethod fun add(...) → returns Job</pre><p>It tried to map Job to a JS type. It couldn&#39;t — Job is a Kotlin coroutine handle, meaningless to JS. Crash.</p><h3>The fix</h3><p>Switch from expression body to block body so the function explicitly returns Unit (Kotlin&#39;s void):</p><pre>// FIXED — block body returns Unit<br>@ReactMethod<br>fun add(data: ReadableArray?, callback: Promise) {<br>    scope.launch {<br>        // same async work, still runs<br>    }<br>}</pre><p>The coroutine still runs. You just changed what the function <strong>declares</strong> it returns. One character difference — = vs { — but completely different behaviour from New Architecture&#39;s perspective.</p><p>This fix applies to every @ReactMethod in MusicModule.kt. There are about 30 of them. All had the same pattern.</p><p><strong>The key insight:</strong> Old Architecture was lazy — it serialised everything as JSON and didn’t inspect types at startup. New Architecture is strict — it builds a C++ type map at startup by inspecting every native method’s signature. A method returning an unexpected type fails hard at initialisation, not at call time.</p><h3>Crash 2 — You should not use ReactNativeHost directly in the New Architecture</h3><h3>The error</h3><pre>java.lang.RuntimeException: You should not use ReactNativeHost directly in the New Architecture<br>    at com.facebook.react.HeadlessJsTaskService.getReactNativeHost<br>    at com.doublesymmetry.trackplayer.service.MusicService.emit</pre><p>This one happened when playback started and the service tried to emit an event back to JS.</p><h3>Root cause</h3><p>In Old Architecture, React Native had one central object called ReactNativeHost that owned everything — the JS runtime, the bridge, the React context. Native modules emitted events by walking this chain:</p><pre>// OLD ARCH — walked the host chain to reach JS<br>reactNativeHost<br>    .reactInstanceManager<br>    .currentReactContext<br>    ?.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)<br>    ?.emit(event, data)</pre><p>This is exactly how RNTP’s MusicService was emitting playback events. It grabbed ReactNativeHost, walked to reactInstanceManager, got currentReactContext, then emitted.</p><p>New Architecture replaced that whole chain. There is no single ReactNativeHost managing everything anymore. When a library touches ReactNativeHost directly, RN throws immediately — it&#39;s an intentional hard crash to force library authors to update.</p><h3>The fix</h3><p>HeadlessJsTaskService (the parent class of RNTP&#39;s MusicService) already holds a direct reference to reactContext. Use that instead:</p><pre>// FIXED — direct context reference, New Arch safe<br>reactContext<br>    ?.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)<br>    ?.emit(event, data)</pre><p>No chain. reactContext is already available on the service through its own registration — you&#39;re just using what&#39;s already there instead of walking the demolished old path.</p><p>This change appears twice in MusicService.kt — once in the single-event emit() function and once in the array-event emitter that pushes lists of events to JS.</p><p><strong>The bigger picture:</strong> New Architecture didn’t just change how JS calls native — it changed how native calls JS. Old Architecture: everything flows through one central host. New Architecture: every module has its own context reference. Libraries that were written for the old model need auditing anywhere they touched ReactNativeHost directly.</p><h3>Crash 3 — ForegroundServiceStartNotAllowedException</h3><h3>The error</h3><pre>android.app.ForegroundServiceStartNotAllowedException</pre><p>Appeared in Logcat when the app was killed and reopened. Audio stopped on restart.</p><h3>Root cause</h3><p>Android 12+ introduced strict rules about when an app can start a foreground service. You’re only allowed to start one when the app is fully visible to the user — not during a restart window.</p><p>When the app reopens after a kill, RNTP tries to restart its MusicService foreground service immediately via startAndStopEmptyNotificationToAvoidANR(). But at that exact moment, Android considers the app to be mid-restart and not fully in the foreground yet. So it throws ForegroundServiceStartNotAllowedException.</p><p>Before the fix, this exception was unhandled. It propagated up and killed the service process, stopping audio.</p><h3>The fix</h3><p>Wrap the call in a try-catch so it logs instead of crashing:</p><pre>override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {<br>    startTask(getTaskConfig(intent))<br>    try {<br>        startAndStopEmptyNotificationToAvoidANR()<br>    } catch (exception: Exception) {<br>        Timber.w(exception, &quot;Unable to start temporary foreground notification&quot;)<br>    }<br>    return START_STICKY<br>}</pre><p>The service continues. Audio continues. The warning shows in Logcat but doesn’t kill anything.</p><p>This is the pattern Google recommends in their own documentation for this exact scenario. The temporary notification is a workaround for an ANR (Application Not Responding) edge case — if it can’t start, that’s acceptable. What’s not acceptable is the service dying because of it.</p><h3>Maintaining the fixes with patch-package</h3><p>None of these changes live in your codebase — they’re in node_modules, which isn&#39;t committed to git. Without patch-package, every yarn install would wipe your fixes.</p><pre># Install patch-package<br>yarn add patch-package --dev</pre><pre># After making your changes to node_modules, generate the patch<br>npx patch-package react-native-track-player</pre><pre># Add postinstall to package.json so patches re-apply automatically</pre><pre>&quot;scripts&quot;: {<br>  &quot;postinstall&quot;: &quot;patch-package&quot;<br>}</pre><p>Now every yarn install re-applies all three fixes automatically.</p><p>One thing to watch: make sure node_modules/react-native-track-player/android/build/ is in your .gitignore before generating the patch. Otherwise the patch file will contain hundreds of compiled .dex and .class binary diffs that bloat it massively without adding anything useful.</p><pre># .gitignore<br>node_modules/react-native-track-player/android/build/</pre><h3>Why so many crashes for one library?</h3><p>RNTP is complex because it runs a persistent Android service. It has more touchpoints with the native layer than most libraries — foreground service lifecycle, event emission, background task management. Each touchpoint is a potential New Architecture incompatibility.</p><p>Here’s what changed between Old and New Architecture that affected RNTP specifically:</p><p>Old Arch New Arch Impact on RNTP Async JSON bridge JSI synchronous calls @ReactMethod return types now inspected at startup ReactNativeHost central host ReactHost + module-level context Direct host access throws Permissive startup Strict type inspection Any non-void @ReactMethod crashes Android foreground rules (pre-12) Strict Android 12+ rules Unguarded startForeground throws during restart</p><p>Most libraries written for Old Architecture work fine on New Architecture if they only use @ReactMethod, Promise, and ReadableMap. RNTP does more — it manages service lifecycle and emits events from the native layer — which is exactly where New Architecture&#39;s stricter model breaks things.</p><h3>What I’m building</h3><p>These patches are part of a podcast player I’m building to demonstrate background audio architecture on React Native New Architecture. The full stack:</p><ul><li>react-native-track-player (patched) for background audio via Android foreground service + iOS AVAudioSession</li><li>react-native-mmkv for kill-proof queue and position persistence</li><li>WatermelonDB for offline episode storage</li><li>react-native-blob-util for episode downloads</li><li>Detox E2E tests covering the kill-and-reopen flow</li></ul><p>The interesting part is the kill → reopen sequence: the native audio service keeps playing after the app is killed, JS reattaches to it on reopen, MMKV is read to restore queue and position, and the UI syncs without flicker. That rehydration order is the tricky part — TrackPlayer.add() must be called before seekTo(), and you have to wait for the player to be ready before syncing UI or you&#39;ll get a brief stutter.</p><p>I’ll write that up separately once the project is shipped.</p><h3>The patch file</h3><p>You can find the complete patch on GitHub: <a href="https://github.com/sagnik2001/Podecast-AudioPlayer">https://github.com/sagnik2001/Podecast-AudioPlayer</a></p><p>It covers all three fixes in a single react-native-track-player+4.1.2.patch file. Drop it in your patches/ folder, add patch-package to postinstall, and you&#39;re good.</p><p>If you’re on a different version of RNTP, the same logic applies — the crashes are architectural, not version-specific — but the line numbers in the diff will be different. You may need to apply the concepts manually.</p><h3>Summary</h3><p>Crash Root cause Fix HostObject::get TrackPlayerModule Kotlin = scope.launch {} returns Job, not Unit Change expression body to block body on all @ReactMethod functions ReactNativeHost directly in New Architecture MusicService.emit() walked the old host chain Replace with direct reactContext reference ForegroundServiceStartNotAllowedException Unguarded startForeground() during app restart on Android 12+ Wrap in try-catch, log with Timber.w</p><p>If you’ve been stuck on any of these, I hope this saves you some hours. The RN New Architecture migration is genuinely hard for libraries that go deep into native territory — and the crash messages alone won’t tell you any of this.</p><p><em>Sagnik Pal — Frontend &amp; React Native Engineer</em> <em>Building at the intersection of web performance and mobile architecture.</em> <a href="https://github.com/sagnik2001"><em>GitHub</em></a><em> · </em><a href="https://linkedin.com/in/sagnik-pal-4437b2209"><em>LinkedIn</em></a><em> · </em><a href="https://sagnik-2001.vercel.app/"><em>Portfolio</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc97943e2373" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scroll Restoration In NextJs Pages Router :]]></title>
            <link>https://medium.com/@palsagnik2001/scroll-restoration-in-nextjs-pages-router-cf189bf5398e?source=rss-bf53a7123a68------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf189bf5398e</guid>
            <category><![CDATA[page-routing]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[scroll]]></category>
            <dc:creator><![CDATA[Palsagnik]]></dc:creator>
            <pubDate>Sat, 07 Dec 2024 07:58:28 GMT</pubDate>
            <atom:updated>2024-12-07T07:58:28.680Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scroll Restoration In NextJs Pages Router :</h3><p>When building the NewMe website, one of the features I wanted to prioritize was user experience, specifically for the shop page. Users often scroll through long lists of products, but when they navigate away and return, the page reloads, causing them to lose their progress. To improve this experience, I implemented scroll restoration by caching products, so users can pick up exactly where they left off. In this blog, I’ll share how I achieved this using insights.</p><p><strong>Why Scroll Restoration Matters</strong></p><p>For e-commerce websites, especially those with long product lists, user experience can often be disrupted by page reloads or navigation. When users navigate away from the shop page, they may forget where they are and have to scroll all the way down again, which can be frustrating. Scroll restoration solves this problem by saving the scroll position and reapplying it when the user returns to the page, ensuring a seamless browsing experience.</p><p><strong>The Challenge</strong></p><p>In the context of my website, the issue was with the product list on the shop page, where users would lose their scroll position if they refreshed or returned after visiting another page. My solution was to store the product list in a cache(redux state) and restore the scroll position whenever necessary using Nextjs scroll restoration.</p><h4>The Solution: Caching Products and Restoring Scroll Position</h4><p>Here’s how I implemented scroll restoration on the shop page:</p><ol><li><strong>Storing Products in Cache</strong></li></ol><pre>// Effect 1: Handle Initial Data Fetching and Event Listeners<br>ON COMPONENT MOUNT OR WHEN &#39;searchParams&#39; CHANGE:<br>    // Step 1: Extract query parameters<br>    SET params TO searchParams<br><br>    // Step 2: Define an asynchronous function to fetch data<br>    FUNCTION fetchData():<br>        // Implementation details for fetching data<br>        ...<br><br>    // Step 3: Check if the shop page data is already loaded from Redux cache<br>    IF shopPageLoaded IS TRUE:<br>        // If data is cached, fetch fresh data<br>        CALL fetchData()<br>    ELSE:<br>        // If data is not cached, determine the current page number<br>        SET page TO params[&#39;p&#39;]<br>        IF page EXISTS:<br>            SET pageNum TO PARSE page AS INTEGER<br>            IF PARSE FAILED:<br>                SET pageNum TO 1<br>        ELSE:<br>            SET pageNum TO 1<br>        END IF<br>        // (Optional) Use pageNum for further logic if needed<br>    END IF<br><br>    // Step 4: Add event listener for scroll events<br>    ADD &#39;scroll&#39; EVENT LISTENER TO WINDOW WITH handler &#39;handlShopScroll&#39;<br><br>    // Step 5: Add event listener for window load event<br>    FUNCTION onLoadEvent(event):<br>        // Remove the &#39;p&#39; parameter from query params<br>        REMOVE &#39;p&#39; FROM params<br><br>        // Scroll the window to the top<br>        SCROLL WINDOW TO POSITION (0, 0)<br><br>        // Update the URL without reloading the page (shallow routing)<br>        CALL router.replace WITH:<br>            pathname: current pathname<br>            query: updated params<br>            hash: current URL hash<br>            options: { shallow: TRUE }<br><br>    ADD &#39;load&#39; EVENT LISTENER TO WINDOW WITH handler &#39;onLoadEvent&#39;<br><br>    // Step 6: Cleanup function to remove event listeners when component unmounts<br>    FUNCTION cleanup():<br>        REMOVE &#39;scroll&#39; EVENT LISTENER FROM WINDOW WITH handler &#39;handlShopScroll&#39;<br>        REMOVE &#39;load&#39; EVENT LISTENER FROM WINDOW WITH handler &#39;onLoadEvent&#39;<br><br>    RETURN cleanup FUNCTION<br>END EFFECT 1<br><br><br>// Effect 2: Update State and Cache Data When &#39;Data&#39; Changes<br>ON &#39;Data&#39; CHANGE:<br>    // Step 1: Check if the shop page is loaded and data is available<br>    IF shopPageLoaded IS TRUE AND Data EXISTS:<br>        // Step 2: Extract shop page data from &#39;Data&#39;<br>        SET shopPageData TO Data<br><br>        // Step 3: Update the local state with the new products<br>        CALL setProducts WITH shopPageData<br><br>        // Step 4: Cache the fetched products in Redux store / Can store in any storage <br>        CALL dispatch WITH action setCachedShopProducts:<br>            [<br>                ...cachedShopProducts,                       // Existing cached products<br>                ...(productData?.data?.products OR [])      // New products from fetched data<br>            ]<br><br>        // Step 5: Cache the current shop page data in Redux store<br>        CALL dispatch WITH action setCachedShopPageData WITH shopPage<br><br>        // Step 6: If total pages information exists, cache it as well<br>        IF shopPageDataTotalPages EXISTS:<br>            // Implement logic to cache the total number of pages<br>            ...<br>        END IF<br>    END IF<br>END EFFECT 2</pre><p>When the user visits the shop page for the first time, the products are fetched from the server and stored in a Redux cache. As we scroll down the shop page, the products are appended to the cache result. The shop URL param is updated as we scroll down and the new products are fetched from the server and stored.</p><p>2. <strong>On Route Change</strong></p><p>The next step was to save the scroll position whenever the user leaves the shop page. We store the shop page number param so that when a user returns, we can navigate them back to the shop page number.</p><pre>// Define a function to cache the current shop page URL information<br>FUNCTION cacheShopPageUrl():<br>    // Check if the current page number exists (is not null or undefined)<br>    IF pageNum EXISTS THEN:<br>        // Dispatch an action to set/cache the current shop page number in the Redux store<br>        CALL dispatch WITH ACTION setShopPageNumber(pageNum)<br>    END IF<br>    <br>    // Regardless of whether pageNum exists, dispatch an action to set/cache the total number of shop pages<br>    CALL dispatch WITH ACTION setShopTotalPageNumber(totalPages)<br>END FUNCTION<br><br>// Create a memoized version of the cacheShopPageUrl function that only changes when pageNum or totalPages change<br>USE useCallback TO MEMOIZE cacheShopPageUrl WITH DEPENDENCIES [pageNum, totalPages]</pre><p>Now when we come back to the shop page we already have the cache data and shop page number stored in our redux state and it navigates back to the particular shop page number and the data is restored.</p><p><strong>Outcome And User Impact</strong></p><p>By implementing scroll restoration, I significantly improved the user experience on the shop page. Users no longer need to scroll endlessly to find their place after navigating away or refreshing the page. This impactful feature ensures that users can smoothly continue their shopping journey without interruption.</p><p><strong>Conclusion</strong></p><p>Scroll restoration is a simple yet effective way to improve user experience on e-commerce sites. By caching product data and restoring scroll positions, We have made the NewMe website more intuitive and user-friendly.</p><p><strong>Contact Us</strong></p><p>You can reach out to us on LinkedIn at <a href="http://linkedin.com/in/kushagra-agarwal-3a2709127">@kushagra</a>, @<a href="https://www.linkedin.com/in/chiraag-arun-kumar-a959441a4?lipi=urn%3Ali%3Apage%3Ad_flagship3_profile_view_base_contact_details%3BztOUraMcQwaYC3IQuK2D3Q%3D%3D">chiraag</a> or ,@<a href="https://www.linkedin.com/in/sagnik-pal-4437b2209/">sagnik</a>, for any questions that you might have.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf189bf5398e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[User Authentication Using JWT Tokens With IP Bound Sessions]]></title>
            <link>https://medium.com/@palsagnik2001/authentication-and-renewal-of-jwt-tokens-with-ip-bound-sessions-51613156f32b?source=rss-bf53a7123a68------2</link>
            <guid isPermaLink="false">https://medium.com/p/51613156f32b</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Palsagnik]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 13:36:47 GMT</pubDate>
            <atom:updated>2024-02-26T18:50:11.821Z</atom:updated>
            <content:encoded><![CDATA[<p>In the modern web development landscape, securing your application’s authentication mechanism is paramount. JSON Web Tokens (JWT) offer a robust and stateless solution to manage user sessions in a secure, scalable way. This blog post walks you through implementing JWT authentication in an Express.js application, focusing on handling refresh tokens securely and efficiently.</p><h3><strong>Understanding JWT</strong></h3><p>JWTs are compact, URL-safe tokens that encode JSON objects. They are digitally signed, ensuring the integrity of the data they contain. A typical JWT consists of three parts: a header, a payload, and a signature. The header specifies the token type and the signing algorithm. The payload contains the claims (data about the user and additional metadata), and the signature verifies the token’s authenticity.</p><p>JWTs are used in authentication and authorization processes. After a user logs in, the server generates a JWT and sends it back to the client. For subsequent requests, the client includes this token, allowing the server to verify the user’s identity without querying the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FDD-csat0TGwYv7eSGB9DA.jpeg" /><figcaption>Showing the authentication using jwt</figcaption></figure><h3><strong>The Challenges Of Security</strong></h3><p>While JWTs are secure, their static nature poses a challenge. Once issued, a JWT’s information cannot be altered without invalidating the token. This immutability means that if a token is stolen, the attacker can use it until it expires.</p><p>To prevent this we have to make sure that the token is short-lived. Using the method of <strong>IP binding </strong>to enhance the security of the application. By tying sessions to device IPs, we add another layer of verification, ensuring that a stolen token can only be used from the original device.</p><p>We create two models now one for the user and one for the session of each user mapped with tokens.</p><pre>npm install express mongoose jsonwebtoken bcryptjs dotenv crypto request-ip</pre><p><strong>Creating the models</strong></p><pre>const mongoose = require(&quot;mongoose&quot;)<br><br>const TokenSchema = new mongoose.Schema({<br>    token: {<br>        type: String,<br>        required: true,<br>    },<br>    expiresAt: {<br>        type: Date,<br>        required: true,<br>    }<br>})<br><br>const SessionSchema = new mongoose.Schema({<br>    userId: {<br>        type: mongoose.Schema.Types.ObjectId,<br>        ref: &#39;Users&#39;,<br>        required: true<br>    },<br>    deviceId: {<br>        type: String,<br>        required: true<br>    },<br>    accessTokens: [TokenSchema]<br>}, { timestamps: true })<br><br>module.exports = mongoose.model(&quot;Session&quot;, SessionSchema)</pre><p>The above is the session Schema where the userId is mapped with the deviceId and the array of access tokens. We store the tokens for security purposes if someone gets misused, we can manually expire the token.</p><p><strong>Step 1: </strong>Verifying the User Credentials</p><p>We first verify the existence of the user in our database and then confirm that the provided password matches the one stored in our records. This process is crucial for establishing the legitimacy of the login attempt.</p><pre>const user = await Users.findOne({ email: req.body.email });<br>if (!user) return res.status(404).json(&quot;User Not Found&quot;);<br><br>const password = await bcrypt.compare(req.body.password, user.password);<br>if (!password) return res.status(403).json(&quot;Password Doesn&#39;t Match&quot;);</pre><p><strong>Step 2: </strong>Generating the JWT and IP Binding and Session Management</p><p>Upon successful authentication, we proceed to generate a JWT. This token is crafted to include the user’s ID as the payload and is set to expire in one hour. Next, we hash the client’s IP address to serve as a unique identifier for the session. This hashed IP, along with the newly generated token, is stored in our Sessions collection. If a session with the same user ID and device ID already exists, we update it by appending the new token; otherwise, we create a new session document.</p><pre>const jwttoken = jwt.sign({ _id: user._id }, process.env.JWT_SECRET_KEY, { expiresIn: &quot;1h&quot; });<br>const clientIp = requestIp.getClientIp(req);<br>const hashedDeviceId = hashDeviceId(clientIp);<br><br>let session = await Sessions.findOne({ userId: user._id, deviceId: hashedDeviceId });<br>if (session) {<br>    session.accessTokens.push({ token: jwttoken, expiresAt: new Date(new Date().getTime() + (60 * 60 * 1000)) });<br>} else {<br>    session = new Sessions({<br>        userId: user._id,<br>        deviceId: hashedDeviceId,<br>        accessTokens: [{ token: jwttoken, expiresAt: new Date(new Date().getTime() + (60 * 60 * 1000)) }]<br>    });<br>}<br>await session.save();</pre><p>We then respond to the client with the token and the user details.</p><p>Now you might wonder what happens when the token expires right??</p><h3><strong>Renewal of the Tokens</strong></h3><p>The jwt token expires after a set duration to minimize security risks. However, this presents a challenge: users would be forced to log in repeatedly once their tokens expire. A refresh token system allows users to seamlessly continue their sessions by obtaining new access tokens without constant re-authentication.</p><p>Our approach involves validating the expired token against the user’s session stored in MongoDB, which includes an array of tokens and a hashed device ID (the client’s IP address). By doing so, we ensure that the token refresh request originates from the same device, adding an extra layer of security.</p><p><strong>Step1</strong>: Setting Up the Refresh Token Endpoint</p><p>Our journey begins with the creation of a dedicated endpoint for handling token refresh requests. This endpoint checks for the presence of an authorization header and extracts the expired token.</p><pre>const authHeader = req.headers[&#39;authorization&#39;];<br>if (!authHeader) return res.status(400).json(&quot;Auth token is not provided&quot;);<br>const token = authHeader.split(&quot; &quot;)[1];</pre><p><strong>Step2: </strong>Decoding and Validating the Token</p><p>Next, we decode the token to extract the user ID and verify its legitimacy. Importantly, we proceed even if the token has expired, focusing on whether it was issued to the requesting device. Before issuing a new token, we confirm that the current one has indeed expired. This step is crucial to prevent unnecessary token issuance and ensure that the refresh mechanism isn’t abused.</p><pre>const decodedtoken = jwt.decode(token);<br>if (!decodedtoken) {<br>  return res.status(400).json(&quot;Wrong Auth token&quot;);<br>}<br><br>const session = await Sessions.findOne({ userId: decodedtoken._id, deviceId: hashedDeviceId });<br>if (!session) {<br>  return res.status(401).send({ message: &#39;Session not found. Please sign in again.&#39; });<br>}<br><br>const decoded = jwt.verify(token, process.env.JWT_SECRET_KEY, { ignoreExpiration: true });<br>const date = Date.now().valueOf() / 1000;<br>if (typeof decoded.exp !== &#39;undefined&#39; &amp;&amp; decoded.exp &gt;= date) {<br>  return res.status(401).send({ message: &quot;Token has not already expired.&quot; });<br>}</pre><p>Upon validating the expiration, we generate a new access token for the user and update the session document in MongoDB to include this new token, along with its expiration time. Finally, we respond to the client with the newly generated access token, thereby extending the user’s session seamlessly and securely.</p><p>We can remove the expired tokens daily from our database by writing a cron job so that our database does not get filled with so many expired tokens.</p><pre>cron.schedule(&#39;0 0 * * *&#39;, async () =&gt; {<br>  try {<br>    await Sessions.updateMany({}, {<br>      $pull: {<br>        accessTokens: {<br>          expiresAt: { $lt: new Date() } // Remove tokens where expiresAt is less than the current date<br>        }<br>      }<br>    })<br>    console.log(&quot;Expired tokens cleanup completed&quot;)<br>  } catch (error) {<br>    console.error(&quot;Error during expired tokens cleanup&quot;, error)<br>  }<br>})</pre><h3>Conclusion</h3><p>So in this way, our jwt tokens get generated and renewed securely, now even if the client stores the tokens somewhere if the token gets stolen the application cannot be used by any other devices.</p><p>For code access</p><p><strong>GitHub Link: </strong><a href="https://github.com/sagnik2001/ClinicClickBackend">https://github.com/sagnik2001/ClinicClickBackend</a></p><p>Thank You</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51613156f32b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is SetState Function in ReactJs Asynchronous Or Synchronous]]></title>
            <link>https://medium.com/@palsagnik2001/is-setstate-function-in-reactjs-asynchronous-or-synchronous-370808bc1c2b?source=rss-bf53a7123a68------2</link>
            <guid isPermaLink="false">https://medium.com/p/370808bc1c2b</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[usestate]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[synchronous]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Palsagnik]]></dc:creator>
            <pubDate>Sun, 16 Jul 2023 16:41:51 GMT</pubDate>
            <atom:updated>2023-07-16T18:52:36.205Z</atom:updated>
            <content:encoded><![CDATA[<p>Before we dive into the topic let&#39;s first get familiar with synchronous and asynchronous.</p><p>The term ‘asynchronous’ refers to the operations and functions which do not block the execution of the program while waiting for a certain task to complete, whereas ‘synchronous’ operations are typically blocking meaning the program execution is paused until the operation is finished.</p><p>So let&#39;s see an example :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/042811525407643f02d879b1d2c74b2c/href">https://medium.com/media/042811525407643f02d879b1d2c74b2c/href</a></iframe><p>What will be the output over here :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*xdvKbgzGcPuvfSjfkMz1iw.png" /></figure><p>So, we found out that the output it has printed is 0 and 2, which justifies that when we update the state it does not get modified rather the program executes completely, and then when the value is modified it renders the state and prints 2, which is the property of asynchronous functions.</p><p>But does it means the setState function is asynchronous, the answer will be <strong>NO. </strong>For this, we have to look into how React rerenders an updated state. When a component in React has an updated state React finds all the elements flagged for update. For each flagged element it converts JSX to React element by a compiler called Babel, and then executes to produce Virtual Dom. This vdom is not rendered directly but it&#39;s converted to fiber and then rendered. The process of converting from vdom to fiber is called reconcile, which creates the corresponding dom elements in the process, and then commits to dom at once after all the conversions are done. This process is not a one-time process but is executed by the scheduler, so it can be done in batches.The specific time it takes for React to update a batch depends on various factors, including the complexity of the component tree, the number of state updates, and the performance of the underlying JavaScript engine in the browser or runtime environment.</p><p>React batches state updates and performs them at a later time for performance optimizations. This allows React to optimize the rendering process.</p><p>However, even though setState is asynchronous, it does not mean it behaves in an asynchronous manner from the perspective of the JavaScript program execution. The setState function itself is still synchronous, meaning that the next line of code after the setState call will not be executed until the state update is complete.</p><pre>console.log(&#39;Before setState&#39;);<br>this.setState({ count: 1 });<br>console.log(&#39;After setState&#39;);</pre><p>In this example, the console.log statement after setState will not be executed until the state update is finished. However, the state update itself may be processed asynchronously by React.</p><p>So we conclude that setState updates the state asynchronously but from the perspective of Javascript program execution it is synchronous.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=370808bc1c2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Toggle Between List View And Grid View Using React Js]]></title>
            <link>https://medium.com/@palsagnik2001/toggle-between-list-view-and-grid-view-using-react-js-3b6e28b526bd?source=rss-bf53a7123a68------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b6e28b526bd</guid>
            <category><![CDATA[react-bootstrap-cards]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[usestate-hook]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Palsagnik]]></dc:creator>
            <pubDate>Sun, 31 Oct 2021 20:25:23 GMT</pubDate>
            <atom:updated>2021-10-31T20:25:23.964Z</atom:updated>
            <content:encoded><![CDATA[<h3>Setting Up The Scene</h3><h4>• Creating The Project</h4><p>Open the terminal Window Of your editor and create a project using npx create-react-app project name. Once you create a react app change the directory to your app by using cd project-name. Open Visual Studio or any editor and click npm start to start the page on your localhost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PxX2QXMa9Pm3Zbt2xVV1oQ.png" /><figcaption>Local page</figcaption></figure><p>Let’s make some changes in App.js and remove the given context and logo.SVG and other files.</p><h3>Creating Components</h3><h4>• Creating Table component</h4><p>Let’s first make a table view of a given data. We make a react component under the src folder and named it Table.js. Under table.js we create a react boiler plater function. We build a basic table UI using <a href="https://react-table.tanstack.com/docs/quick-start"><strong>React Table</strong></a><strong>.</strong> We did some styling using bootstrap which we import by using npm install bootstrap</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/733d397568910a1a6370c6c780d7b8c0/href">https://medium.com/media/733d397568910a1a6370c6c780d7b8c0/href</a></iframe><p>We import the component in our App.js and run the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ev-eSSy0KcqKDLZ6RGEQWA.png" /></figure><h4>• Creating Card component</h4><p>Now moving on we create a similar Card view of our given data. For this, we go to our terminal and install <a href="https://www.npmjs.com/package/react-bootstrap"><strong>npm react-bootstrap</strong></a>. We create a component Card.js in our src folder and implement Card from <a href="https://react-bootstrap.github.io/components/cards/"><strong>React Bootstrap Cards</strong></a><strong>. </strong>We import Card from “react-bootstrap/Card”</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69c462430098f84d229e1eac190c8bea/href">https://medium.com/media/69c462430098f84d229e1eac190c8bea/href</a></iframe><p>We create three cards like our Table.js and add some inline CSS to make it look good.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69c462430098f84d229e1eac190c8bea/href">https://medium.com/media/69c462430098f84d229e1eac190c8bea/href</a></iframe><p>Like earlier we import the card component in our app.js.</p><h4>• Creating Toggle Icons</h4><p>Now we have our table and card view both we want to toggle between our grid view and list view for that we need some buttons. We import <a href="https://react-icons.github.io/react-icons/icons?name=di"><strong>React icons</strong></a> inside our button components to make them look nicer. For that, we visit the react icons and search for our suitable icons, and import them into our App.js.</p><p>We create two buttons and inside them placed the desired icons and do some styling like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6392944c2d48452bd4673929e7eaaeb5/href">https://medium.com/media/6392944c2d48452bd4673929e7eaaeb5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9xwzWpdtXVB88LUfI4VT5A.png" /></figure><h3>Implementing Toggling</h3><p>To implement toggling between the buttons we import a react hook call useState to maintain the visibility of the grid view and list view. To declare the state variable, a pair of values needs to be set equal to the useState method. The pair of values is the current state and a function that updates the current state. useState will always return this pair of values. The state of the variable is initialized by passing an initial value of false in the useState method. Then set on Click function on our buttons to trigger two functions that toggle between two views. After that, we set a condition to view the required view by clicking the required button.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3db53928a3e78ebdfc1071241443a0d7/href">https://medium.com/media/3db53928a3e78ebdfc1071241443a0d7/href</a></iframe><p>Now if we click the first list button it will show the list view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tqjDEoo8tb6JMHjuZz-pQA.png" /></figure><p>And the second button shows the grid view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lZy7GMUHfji60hYOSn6sgA.png" /></figure><p>Link to Github Repo: <a href="https://github.com/sagnik2001/BlogWebMedium/tree/master/Tutorials/Blogs/viewtoggle">https://github.com/sagnik2001/BlogWebMedium/tree/master/Tutorials/Blogs/viewtoggle</a></p><p>Cheers!</p><h4>Sagnik :)</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b6e28b526bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>