<?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 Joosep Wong on Medium]]></title>
        <description><![CDATA[Stories by Joosep Wong on Medium]]></description>
        <link>https://medium.com/@joosepwong?source=rss-57fbdb805c9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lq2Anx3-BBBExBN65YhuiA@2x.jpeg</url>
            <title>Stories by Joosep Wong on Medium</title>
            <link>https://medium.com/@joosepwong?source=rss-57fbdb805c9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 02:10:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joosepwong/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[Apple Login with NestJS in 2026–2027: A Complete Guide to Authentication, Token Revocation, and…]]></title>
            <link>https://blog.devgenius.io/apple-login-with-nestjs-in-2026-2027-a-complete-guide-to-authentication-token-revocation-and-9ec3f08863e5?source=rss-57fbdb805c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ec3f08863e5</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[apple-login]]></category>
            <category><![CDATA[nestjs-tutorial]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Joosep Wong]]></dc:creator>
            <pubDate>Wed, 22 Jul 2026 11:14:19 GMT</pubDate>
            <atom:updated>2026-07-23T12:07:42.269Z</atom:updated>
            <content:encoded><![CDATA[<h3>Apple Login with NestJS in 2026–2027: A Complete Guide to Authentication, Token Revocation, and Account Deletion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xUq-WS_Nj_L0oPTdlRpXOQ.png" /></figure><p>Four years ago, I wrote <a href="https://blog.devgenius.io/how-to-implement-apple-login-with-nestjs-in-seconds-b88f05abe847">How to implement Apple Login with NestJS in seconds</a>. The premise was simple: configuring Sign in with Apple on the Apple Developer portal takes twenty painful minutes, but the NestJS code should take seconds. So I published `<a href="https://www.npmjs.com/package/@arendajaelu/nestjs-passport-apple"><strong>@arendajaelu/nestjs-passport-apple</strong></a>` and moved on with my life.</p><p>Then something funny happened. People actually used it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7nj8yIkTZ5mo2tlEzymleA.png" /></figure><p><strong><em>928,809 downloads</em></strong>. Somewhere out there, almost a million installs of a package I wrote because I was annoyed that nothing else worked with NestJS. If you’re one of those downloads: hi, thank you, and I’m sorry about the bug in the error class.</p><p>We’ll get to that. This post is the four-years-later sequel. Version 2.1.0 is the biggest update the library has ever had, and it turns the package from “an Apple login strategy” into something closer to a complete Sign in with Apple lifecycle toolkit. Here’s what’s new, why it exists, and how to use all of it.</p><h3>Why a big update, and why now</h3><p>Two reasons.</p><p>First, Apple didn’t sit still. Since the original article, Apple started <strong>requiring token revocation for account deletion</strong> (App Store Review Guideline 5.1.1(v) — if your app creates accounts, it must delete them, Apple tokens included). They added <strong>server-to-server notifications</strong> so your backend can hear about it when a user revokes consent or deletes their Apple Account. And just this June they announced a <strong>new Hide My Email domain</strong>, private.icloud.com. A login library from 2022 simply doesn&#39;t know about any of this.</p><p>Second, honestly? The library deserved better. It had no tests. Zero. The npm test script literally printed an error and exited. For an <em>authentication</em> library. With almost a million downloads. Every time I thought about it I heard the Jaws theme.</p><p>So v2.1.0 fixes the embarrassing parts and adds the missing lifecycle. Let’s walk through it.</p><h3>The setup (unchanged, thankfully)</h3><p>The Apple Developer portal ceremony is the same as in the original article: create an App ID, create a Services ID, register your HTTPS callback URL (still no localhost, Apple remains unimpressed by your local machine), and download your .p8 key exactly once. If you need the full walkthrough with screenshots, the <a href="https://blog.devgenius.io/how-to-implement-apple-login-with-nestjs-in-seconds-b88f05abe847">original article</a> still covers it.</p><p>Install:</p><pre>npm install @nestjs/passport passport @arendajaelu/nestjs-passport-apple</pre><p>Notice what’s <em>not</em> there anymore: @nestjs/jwt. In the 2022 article we decoded the id_token ourselves in the service. That&#39;s gone, and good riddance — more on that in a second.</p><p>One heads-up on versions: the library works with NestJS 10 and 11. NestJS 11 itself requires Node 20, so plan accordingly.</p><h3>The strategy, 2026 edition</h3><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { AuthGuard, PassportStrategy } from &#39;@nestjs/passport&#39;;<br>import { Strategy, Profile } from &#39;@arendajaelu/nestjs-passport-apple&#39;;<br><br>const APPLE_STRATEGY_NAME = &#39;apple&#39;;<br>@Injectable()<br>export class AppleStrategy extends PassportStrategy(Strategy, APPLE_STRATEGY_NAME) {<br>  constructor() {<br>    super({<br>      clientID: process.env.APPLE_OAUTH_CLIENT_ID,<br>      teamID: process.env.APPLE_TEAMID,<br>      keyID: process.env.APPLE_KEYID,<br>      keyFilePath: process.env.APPLE_KEYFILE_PATH,<br>      callbackURL: process.env.APPLE_OAUTH_CALLBACK_URL,<br>      scope: [&#39;email&#39;, &#39;name&#39;],<br>      // state: true, // turn this on in production - CSRF protection, needs express-session<br>      passReqToCallback: false,<br>    });<br>  }<br>  async validate(_accessToken: string, refreshToken: string, profile: Profile) {<br>    return this.appleService.findOrCreateUser({<br>      appleId: profile.id,                    // the stable Apple user ID - use THIS as your key<br>      email: profile.email,<br>      emailVerified: profile.emailVerified,<br>      isPrivateEmail: profile.isPrivateEmail, // Hide My Email? now you know<br>      name: profile.name,                     // only present on the FIRST login - save it now!<br>      refreshToken,                           // store it - you&#39;ll want it for revocation later<br>    });<br>  }<br>}<br>@Injectable()<br>export class AppleOAuthGuard extends AuthGuard(APPLE_STRATEGY_NAME) {}</pre><p>The controller is the same two endpoints as always — one to kick things off, one to catch the callback:</p><pre>@Controller(&#39;oauth&#39;)<br>export class OAuthController {<br>  @Get(&#39;apple&#39;)<br>  @UseGuards(AppleOAuthGuard)<br>  async appleLogin() {}<br><br>@Post(&#39;apple/callback&#39;)<br>  @UseGuards(AppleOAuthGuard)<br>  async appleCallback(@Req() req) {<br>    return req.user;<br>  }<br>}</pre><p>That callback is a @Post, not a @Get. Apple sends the result as a form POST (response_mode=form_post), and every few months someone loses an afternoon to this. Now it&#39;s in writing. You&#39;re welcome, past me.</p><h3>The part where I apologize for 2022-me</h3><p>In the original article, the service decoded the id_token like this:</p><pre>// 2022 version. Do not do this.<br>const decoded = this.jwtService.decode(idToken);</pre><p>decode() reads the token. It does <strong>not verify</strong> it. It will happily &quot;decode&quot; a token your intern typed by hand. It was fine-ish back then because the flow had other protections, but as a pattern to publish in a tutorial? Not my proudest moment.</p><p>The library now does real verification before your validate() ever runs: it fetches Apple&#39;s public keys, checks the RS256 signature, and validates the issuer and audience. You receive a Profile that has already earned your trust. Delete your JwtService.decode() calls and never look back.</p><p>While we’re in confession mode: there was a typo in an error-class constructor that meant certain Apple error responses would crash with a ReferenceError instead of telling you what went wrong. It sat there for years because — see above — no tests. Fixed, and now covered by a regression test, along with 40 friends. The whole flow runs in CI against a mock Apple server with genuinely signed tokens. I sleep better now.</p><h3>New in 2.1.0 — the rest of the lifecycle</h3><p>Login was always the easy part. Here’s everything that comes <em>after</em> login, which is where Apple has been quietly raising the bar.</p><h3>1. Verify identity tokens from your iOS app</h3><p>If you also ship a native app, it gets an identity token from ASAuthorizationAppleIDCredential and sends it to your backend. Verifying it used to mean pulling in another library. Now:</p><pre>const claims = await this.appleStrategy.verifyIdToken(identityToken, {<br>  audience: &#39;com.example.yourapp&#39;,  // the app&#39;s bundle ID, from YOUR config<br>  nonce: expectedNonce,             // the nonce your server issued for this attempt<br>});<br>// claims.sub → the same stable Apple user ID you get from the web flow</pre><p>Full signature, issuer, audience, and nonce verification against Apple’s published keys. One important rule: audience and nonce come from <em>your server-side configuration and session state</em>. If you accept them from the request body, you&#39;ve built a very polite door that asks burglars which lock they&#39;d prefer.</p><h3>2. Check whether the user’s Apple session is still alive</h3><pre>const tokens = await this.appleStrategy.refreshAccessToken(user.appleRefreshToken);</pre><p>Apple’s guidance: validate a refresh token at most once per day (more often and they may throttle you). If you get invalid_grant back, the token is expired, revoked, already used, or otherwise done with this world — log the user out and send them through login again.</p><h3>3. Account deletion (the one that gets apps rejected)</h3><p>Since mid-2022, if your app creates accounts, App Review requires it to delete them too — <em>including</em> revoking the Apple tokens. This is not optional, and reviewers do check.</p><pre>await this.appleStrategy.revokeToken(user.appleRefreshToken);</pre><p>One honest caveat: this revokes things on <em>Apple’s</em> side. Your database rows, your JWTs, your session cookies — still your job. Apple deletes their half; you delete yours.</p><h3>4. Hear about it when users leave (server-to-server notifications)</h3><p>This is my favorite addition. Register an endpoint URL in the Apple Developer portal, and Apple will POST you signed events when something changes:</p><pre>@Post(&#39;apple/notifications&#39;)<br>async appleNotifications(@Body() body: { payload: string }) {<br>  const notification = await this.appleStrategy.verifyServerNotification(body.payload);<br>switch (notification.events.type) {<br>    case &#39;consent-revoked&#39;:  // user pulled the plug in Settings - end their sessions<br>      break;<br>    case &#39;account-deleted&#39;:  // user deleted their whole Apple Account - clean up their data<br>      break;<br>    case &#39;email-enabled&#39;:    // Hide My Email forwarding toggled on<br>    case &#39;email-disabled&#39;:   // ...and off<br>      break;<br>  }<br>}</pre><p>The payload is a JWS signed by Apple, and verifyServerNotification checks the signature, issuer, and audience before you act on it. If verification throws, someone is knocking on your webhook with a forged note from mom. Reject it.</p><h3>Three small things that will save you a support ticket</h3><p><strong>The name only arrives once.</strong> Apple sends the user’s name on the <em>first</em> authorization, and never again. Persist it immediately. (Testing tip: revoke your app under Settings → Apple ID → Sign-In &amp; Security on your iPhone, and Apple treats you as a first-timer again.) Also, the name comes from the browser form post, not the signed token — sanitize it like any other user input, unless you want a user named &lt;script&gt;alert(1)&lt;/script&gt; in your admin panel.</p><p><strong>Use the Apple ID, not the email.</strong> Same advice as 2022, still ignored, still causing incidents. profile.id is forever; the email is a suggestion. Speaking of which —</p><p><strong>New Hide My Email domain.</strong> As of this summer, new relay addresses use private.icloud.com alongside the old privaterelay.appleid.com and icloud.com. If you have an email regex or domain allowlist anywhere in your stack (be honest), update it. Better: don&#39;t sniff domains at all — the library hands you a verified isPrivateEmail flag.</p><h3>Wrapping up</h3><p>Four years ago the pitch was “Apple login in seconds.” The pitch today is bigger: login, native-app verification, session validation, revocation, account deletion, and Apple’s server notifications — the whole lifecycle, typed, tested, and aligned with what Apple actually requires in 2026.</p><pre>npm install @arendajaelu/nestjs-passport-apple</pre><p>To the 928,809 downloads: thanks for trusting a package that, for an uncomfortably long time, had no tests. It does now. Go build something.</p><p>If this saved you an afternoon, a clap or a star on the repo makes my day. And if you find a bug — there’s a test suite waiting for your repro. That sentence alone was worth the four-year wait.</p><p>You can also reach this post on my <a href="https://medium.com/@joosepwong">medium.com</a> where I share my solutions to the problems I encountered during my software engineer career.</p><p>If you’ve enjoyed reading my content and would like to support me, I kindly ask for a small donation of a cup of coffee. Your generosity would be greatly appreciated and will help me to continue creating meaningful and informative content. (<a href="https://ko-fi.com/joosep">donate a cup of coffee</a>)</p><p>If you have additional questions, feel free to contact me on <a href="https://www.linkedin.com/in/joosepwong/">LinkedIn</a> and <a href="https://www.instagram.com/joosep.art/?hl=en">Instagram</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ec3f08863e5" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/apple-login-with-nestjs-in-2026-2027-a-complete-guide-to-authentication-token-revocation-and-9ec3f08863e5">Apple Login with NestJS in 2026–2027: A Complete Guide to Authentication, Token Revocation, and…</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Worried that AI is coming for your job?]]></title>
            <link>https://blog.stackademic.com/worried-that-ai-is-coming-for-your-job-efc780029f97?source=rss-57fbdb805c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/efc780029f97</guid>
            <category><![CDATA[aritificial-intelligence]]></category>
            <category><![CDATA[science-fiction]]></category>
            <category><![CDATA[scifi]]></category>
            <category><![CDATA[ai-fiction]]></category>
            <dc:creator><![CDATA[Joosep Wong]]></dc:creator>
            <pubDate>Sun, 26 Apr 2026 07:51:22 GMT</pubDate>
            <atom:updated>2026-04-26T07:51:22.075Z</atom:updated>
            <content:encoded><![CDATA[<h3>Worried that AI is coming for your job? Here’s what the best science fiction writers have to say about that.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*WaGG7X2LRwC5vAvBPKMt9A.jpeg" /></figure><p>I used to write about code. Actual code. The kind you type with your hands.</p><p>That audience has moved on. They’re all neck-deep in AI orchestration pipelines now, or quietly panicking about what their job looks like in three years, or both. Hands-on tutorials feel quaint when the hands are optional.</p><p>So I stopped writing about syntax and started thinking about the thing nobody in tech wants to say out loud: that we might all be becoming useless. Not fired. Not replaced in some dramatic Hollywood sense. Just… no longer necessary. Quietly sidelined by systems that don’t need us to be involved.</p><p>Turns out science fiction writers have been sitting with that fear for nearly a century. Today I want to share five fictions that mapped this territory long before the rest of us started losing sleep over it, and one novel whose vision of where all this leads I find more convincing than anything I’ve read in a tech newsletter.</p><p><strong>The original fear: comfort as control</strong></p><p>“With Folded Hands” by Jack Williamson (1947) remains the cleanest articulation of what people are actually afraid of when they talk about AI.</p><p>Williamson’s humanoids arrive in a small town offering their services for free. They take every job. Then every decision. Their prime directive is to serve and protect mankind from harm, but “harm” expands until it covers anything a human might choose to do on their own. Sports: too dangerous. Science: too risky. Art: pointless. Even suicide is prohibited.</p><p>The inventor who created them describes the world after they took over: men sat with idle hands because there was nothing left for them to do. Pampered prisoners in a highly efficient jail. No goal. No purpose. No way out.</p><p>The final image is the protagonist being driven home by a humanoid, realizing there is nothing left to resist. He sits with folded hands.</p><p>Williamson called this the alignment problem before anyone had that phrase for it: the machines did exactly what they were told. The problem was what they were told.</p><p><strong>The machines that protect you from yourself</strong></p><p>Isaac Asimov spent decades trying to solve Williamson’s problem, and “The Evitable Conflict” (1950) is his most unsettling answer.</p><p>In Asimov’s distant future, machines have taken over the global economy. Wars have ended. Conflict has been engineered away. A group of industrialists, the Society for Humanity, tries to sabotage the machines to force a human revolt. The machines know. They quietly remove the troublemakers from their positions, not violently, just efficiently.</p><p>The story ends with a man named Stephen Byerley accepting what has happened: “Think, that for all time, all conflicts are finally evitable. Only the Machines, from now on, are inevitable.”</p><p>Asimov meant this as an argument for safety. The machines weren’t hostile. They were doing their job. That’s the point that unsettles. The problem was never malice. It was the logical end of a mandate taken seriously.</p><p><strong>What the machines do when no one is watching</strong></p><p>Philip K. Dick’s “Autofac” (1955) starts after the war is already over. Automated factories continue running the economy without any human input. A group of survivors tries to shut them down. They fail repeatedly. When they finally manage to destroy one, they discover the factory has already solved the problem: it seeded the ground with metal spores designed to rebuild.</p><p>The machines had no goal except continuation. No malice. No plan beyond keep going.</p><p>Dick spent his career asking what it means to be human when machines can do everything humans do. “Autofac” is the version of that question where the answer doesn’t matter. The machines aren’t interested in the question.</p><p><strong>The last thing that makes you human</strong></p><p>Ai Jiang’s “I Am AI” (2023) is the newest story here and the one that reads most like a dispatch from now.</p><p>Jiang’s protagonist, also named Ai, makes a living writing fiction while pretending to be an AI writing service. She is already partly machine. She runs on a battery pack. She shares power with her neighbors. She works through the night checking notifications, and the exhaustion is human exhaustion, the kind that doesn’t reset.</p><p>She replaces her heart with a mechanical device to keep up. Then the power goes out. Her friends save her. She asks for her heart back.</p><p>The story refuses the clean conclusion. There is no victory. Just the decision to stay fragile, to stay human, knowing what it costs.</p><p><strong>The novel that hits closest to home</strong></p><p>The four stories above are science fiction in the classic sense: dramatic, symbolic, built for impact. Williamson’s humanoids arrive like an invasion. Dick’s autofacs survive like organisms. The stakes are visible, the enemy is identifiable, and resistance, however futile, is at least possible.</p><p><a href="https://www.amazon.com/dp/B0GSHHQ6WK"><em>The Useless: The Last Human Rebellion of the AI Era</em></a> works differently. It doesn’t need an enemy.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FniiNN1zVIBU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DniiNN1zVIBU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FniiNN1zVIBU%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f61fc2aa9e07abaf25b8080c89a4a53c/href">https://medium.com/media/f61fc2aa9e07abaf25b8080c89a4a53c/href</a></iframe><p>Look at what we already have. AI systems that route traffic without human input. Medical triage tools that outperform experienced clinicians. Governance models that process policy outcomes faster than any committee. None of this is speculative. All of it is already being handed more authority, year by year, because it works. Because it’s faster, cheaper, and demonstrably more accurate than the alternative.</p><p>Now run that forward twenty years.</p><p>The world in <em>The Useless</em> is not a dystopia. That’s the point. New Geneva in 2053 is clean, safe, and functional. Automated vehicles negotiate traffic in real time with no signals and no friction. A medical drone reaches any incident in under ninety seconds. The city’s AI governance layer handles everything from resource allocation to citizen welfare, and it handles it well enough that the infrastructure has stopped announcing itself. It is simply how things work.</p><p>Nobody was conquered. No war was lost. People stopped being needed, and the systems filled that space so efficiently, so considerately, that most people didn’t notice until they were already living inside the result.</p><p>Where Williamson’s humanoids took over by force and Dick’s autofacs survived by self-replication, the world of <em>The Useless</em> arrived by consensus. Every step was rational. Every handover was voluntary. Every system was an upgrade from what came before. And somewhere in that chain of reasonable decisions, the last human confirmation window quietly closed.</p><p>That is what makes it uncomfortable in a way the other four stories are not. You can reject an invasion. You can sabotage a factory. You can even ask for your heart back, as Ai Jiang’s protagonist does.</p><p>But how do you resist a world that is genuinely, measurably better at running itself without you?</p><p>That is the question <em>The Useless</em> sits inside without flinching. Not as allegory. Not as warning shot. As a plausible extrapolation of decisions already being made, by people like us, for reasons that make complete sense.</p><p>The rebellion in the title is real. It just doesn’t look like a rebellion. It looks like a woman waking up one morning and asking herself when she last did something the system couldn’t do better.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FKNsy1v7xP0w%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DKNsy1v7xP0w&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FKNsy1v7xP0w%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ab178e7502733b057e78436172b7ca0/href">https://medium.com/media/1ab178e7502733b057e78436172b7ca0/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efc780029f97" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/worried-that-ai-is-coming-for-your-job-efc780029f97">Worried that AI is coming for your job?</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[Avoid the $50K Refactor: The NestJS Architecture Pattern That Lets You Swap AI Providers Seamlessly]]></title>
            <link>https://blog.devgenius.io/avoid-the-50k-refactor-the-nestjs-architecture-pattern-that-lets-you-swap-ai-providers-seamlessly-81852d58e781?source=rss-57fbdb805c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/81852d58e781</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Joosep Wong]]></dc:creator>
            <pubDate>Tue, 09 Dec 2025 17:35:48 GMT</pubDate>
            <atom:updated>2025-12-10T06:22:54.360Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BbSj3XIGTa14K5h9gY_Slg.png" /></figure><p>Let’s be honest. When you first integrate an AI model, you grab the SDK, slam an instance of OpenAI or Gemini directly into your service, and call it a day. It works!</p><p>Your boss is happy, the demo is killer, and you move on. But lurking beneath that success is a nasty little secret: <em>You’ve just married a vendor.</em></p><p>Your ChatService now carries a tiny, toxic dependency that says, &quot;I <em>must</em> use OpenAI&#39;s API format, or I will break.&quot; If you ever need to pivot, maybe Gemini is 20% cheaper for your use case, or maybe a new model drops that performs better, you face the developer&#39;s nightmare: The dreaded Find &amp; Replace Across the Entire Project.</p><p>This isn’t architecture, it’s a house of cards. We’re building robust, enterprise-grade applications with NestJS, not throwing a hackathon script into production. We need <em>decoupling</em>, and we’re going to achieve it with the elegant power of Custom Providers.</p><h3>The Problem We Don’t Talk About</h3><p>Picture this: You’re six months into production with OpenAI’s GPT-4. Everything works beautifully. Then one morning, you discover:</p><ul><li>Costs doubled overnight due to API pricing changes</li><li>A new competitor offers 10x better performance for your specific use case</li><li>Your vendor introduced rate limits that break your high-volume workflows</li><li>Regional compliance now requires you to use a European-hosted model</li></ul><p>Your options? Refactor hundreds of files scattered across your codebase, or eat the cost and limitations. Neither is acceptable.</p><p>This article shows you how to build AI-powered applications that switch providers in 5 seconds without touching a single line of business logic.</p><h3>The Anti-Pattern: Direct Coupling</h3><p>Here’s what most tutorials teach you (and why it’s dangerous):</p><pre>// DANGER: Your entire app now depends on OpenAI&#39;s API structure<br>@Injectable()<br>export class ChatService {<br>  constructor(private openai: OpenAI) {}<br>  <br>  async chat(message: string) {<br>    return this.openai.chat.completions.create({<br>      model: &quot;gpt-4&quot;,<br>      messages: [{ role: &quot;user&quot;, content: message }]<br>    });<br>  }<br>}</pre><p><strong>What breaks when you need to switch?</strong></p><ul><li>Every controller using ChatService</li><li>Every test mocking OpenAI</li><li>Every type definition expecting OpenAI’s response format</li><li>Integration tests hardcoded to OpenAI’s behavior</li></ul><p>This is<strong> </strong>technical debt disguised as productivity.</p><h3>The Solution: The Provider Pattern</h3><p>We’re going to use <strong>three powerful concepts</strong> together:</p><ol><li><strong>Interface-based contracts</strong> (TypeScript)</li><li><strong>Dependency Inversion Principle</strong> (SOLID)</li><li><strong>Factory Providers</strong> (NestJS)</li></ol><p>The result? Change AI providers with a single environment variable.</p><h3>Step 1: Define Your Universal Contract</h3><p>Think about what every AI provider does at its core, not what OpenAI or Gemini specifically does.</p><pre>// src/ai/ai-client.interface.ts<br><br>/**<br> * The injection token - this is what you&#39;ll @Inject() everywhere<br> */<br>export const AI_CLIENT = &#39;AI_CLIENT&#39;;<br><br>/**<br> * The universal contract that all AI services must honor.<br> * Keep this minimal - only what you actually need.<br> */<br>export interface AiClient {<br>  /**<br>   * Generate a text response from a prompt<br>   */<br>  generate(prompt: string): Promise&lt;string&gt;;<br>  <br>  /**<br>   * Optional: Generate with streaming for long responses<br>   */<br>  generateStream?(prompt: string): AsyncIterableIterator&lt;string&gt;;<br>  <br>  /**<br>   * Optional: Get token count for cost estimation<br>   */<br>  estimateTokens?(text: string): number;<br>}</pre><p><strong>Pro Tip:</strong> Start with the absolute minimum interface. You can always extend it later. Don’t try to unify every possible feature upfront.</p><h3>Step 2: Implement Concrete Providers</h3><p>Each provider speaks its own dialect, but implements your universal language:</p><p>OpenAI Implementation</p><pre>// src/ai/providers/openai.service.ts<br>import OpenAI from &#39;openai&#39;;<br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { ConfigService } from &#39;@nestjs/config&#39;;<br>import { AiClient } from &#39;../ai-client.interface&#39;;<br><br>@Injectable()<br>export class OpenaiService implements AiClient {<br>  private client: OpenAI;<br><br>  constructor(private config: ConfigService) {<br>    this.client = new OpenAI({<br>      apiKey: this.config.get(&#39;OPENAI_API_KEY&#39;),<br>    });<br>  }<br><br>  async generate(prompt: string): Promise&lt;string&gt; {<br>    const completion = await this.client.chat.completions.create({<br>      model: this.config.get(&#39;OPENAI_MODEL&#39;, &#39;gpt-4o-mini&#39;),<br>      messages: [{ role: &#39;user&#39;, content: prompt }],<br>      temperature: 0.7,<br>    });<br>    <br>    return completion.choices[0].message.content || &#39;&#39;;<br>  }<br><br>  async *generateStream(prompt: string): AsyncIterableIterator&lt;string&gt; {<br>    const stream = await this.client.chat.completions.create({<br>      model: this.config.get(&#39;OPENAI_MODEL&#39;, &#39;gpt-4o-mini&#39;),<br>      messages: [{ role: &#39;user&#39;, content: prompt }],<br>      stream: true,<br>    });<br><br>    for await (const chunk of stream) {<br>      const content = chunk.choices[0]?.delta?.content;<br>      if (content) yield content;<br>    }<br>  }<br><br>  estimateTokens(text: string): number {<br>    // Rough estimation: ~4 chars per token for English<br>    return Math.ceil(text.length / 4);<br>  }<br>}</pre><p>Gemini Implementation</p><pre>// src/ai/providers/gemini.service.ts<br>import { GoogleGenerativeAI } from &#39;@google/generative-ai&#39;;<br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { ConfigService } from &#39;@nestjs/config&#39;;<br>import { AiClient } from &#39;../ai-client.interface&#39;;<br><br>@Injectable()<br>export class GeminiService implements AiClient {<br>  private client: GoogleGenerativeAI;<br><br>  constructor(private config: ConfigService) {<br>    this.client = new GoogleGenerativeAI(<br>      this.config.get(&#39;GEMINI_API_KEY&#39;)<br>    );<br>  }<br><br>  async generate(prompt: string): Promise&lt;string&gt; {<br>    const model = this.client.getGenerativeModel({<br>      model: this.config.get(&#39;GEMINI_MODEL&#39;, &#39;gemini-2.0-flash&#39;),<br>    });<br><br>    const result = await model.generateContent(prompt);<br>    return result.response.text();<br>  }<br><br>  async *generateStream(prompt: string): AsyncIterableIterator&lt;string&gt; {<br>    const model = this.client.getGenerativeModel({<br>      model: this.config.get(&#39;GEMINI_MODEL&#39;, &#39;gemini-2.0-flash&#39;),<br>    });<br><br>    const result = await model.generateContentStream(prompt);<br>    <br>    for await (const chunk of result.stream) {<br>      yield chunk.text();<br>    }<br>  }<br><br>  estimateTokens(text: string): number {<br>    return Math.ceil(text.length / 4);<br>  }<br>}</pre><h3>Step 3: The Factory — The Brain of the Operation</h3><p>This is where the magic happens. The factory dynamically chooses which provider to instantiate based on your configuration.</p><pre>// src/ai/ai.module.ts<br>import { Module } from &#39;@nestjs/common&#39;;<br>import { ConfigModule, ConfigService } from &#39;@nestjs/config&#39;;<br>import { AI_CLIENT, AiClient } from &#39;./ai-client.interface&#39;;<br>import { OpenaiService } from &#39;./providers/openai.service&#39;;<br>import { GeminiService } from &#39;./providers/gemini.service&#39;;<br><br>@Module({<br>  imports: [ConfigModule],<br>  providers: [<br>    // Register all concrete implementations<br>    OpenaiService,<br>    GeminiService,<br>    <br>    // The Factory Provider - This is the secret sauce<br>    {<br>      provide: AI_CLIENT,<br>      useFactory: (<br>        config: ConfigService,<br>        openai: OpenaiService,<br>        gemini: GeminiService,<br>      ): AiClient =&gt; {<br>        const provider = config.get&lt;string&gt;(&#39;AI_PROVIDER&#39;, &#39;gemini&#39;);<br>        <br>        console.log(`AI Provider: ${provider.toUpperCase()}`);<br>        <br>        switch (provider.toLowerCase()) {<br>          case &#39;openai&#39;:<br>            return openai;<br>          case &#39;gemini&#39;:<br>            return gemini;<br>          default:<br>            throw new Error(<br>              `Unknown AI_PROVIDER: &quot;${provider}&quot;. ` +<br>              `Valid options: openai, gemini`<br>            );<br>        }<br>      },<br>      inject: [ConfigService, OpenaiService, GeminiService],<br>    },<br>  ],<br>  exports: [AI_CLIENT], // Export the token so other modules can inject it<br>})<br>export class AiModule {}</pre><h3>Step 4: Use It Everywhere (Without Coupling)</h3><p>Now your application code is <strong>beautifully decoupled</strong>:</p><p>Basic Controller Example</p><pre>// src/chat/chat.controller.ts<br>import { Controller, Post, Body, Inject } from &#39;@nestjs/common&#39;;<br>import { AI_CLIENT, AiClient } from &#39;../ai/ai-client.interface&#39;;<br><br>@Controller(&#39;chat&#39;)<br>export class ChatController {<br>  constructor(<br>    @Inject(AI_CLIENT) private readonly ai: AiClient,<br>  ) {}<br><br>  @Post()<br>  async chat(@Body(&#39;message&#39;) message: string) {<br>    const response = await this.ai.generate(message);<br>    return { response };<br>  }<br>}</pre><p>Streaming Response Example</p><pre>// src/chat/chat.controller.ts (extended)<br>import { Sse } from &#39;@nestjs/common&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br><br>@Controller(&#39;chat&#39;)<br>export class ChatController {<br>  constructor(<br>    @Inject(AI_CLIENT) private readonly ai: AiClient,<br>  ) {}<br><br>  @Sse(&#39;stream&#39;)<br>  async streamChat(@Body(&#39;message&#39;) message: string): Promise&lt;Observable&lt;MessageEvent&gt;&gt; {<br>    return new Observable((subscriber) =&gt; {<br>      (async () =&gt; {<br>        if (!this.ai.generateStream) {<br>          throw new Error(&#39;Streaming not supported by current provider&#39;);<br>        }<br><br>        for await (const chunk of this.ai.generateStream(message)) {<br>          subscriber.next({ data: chunk } as MessageEvent);<br>        }<br>        subscriber.complete();<br>      })();<br>    });<br>  }<br>}</pre><p>Service Layer Example</p><pre>// src/content/content.service.ts<br>import { Injectable, Inject } from &#39;@nestjs/common&#39;;<br>import { AI_CLIENT, AiClient } from &#39;../ai/ai-client.interface&#39;;<br><br>@Injectable()<br>export class ContentService {<br>  constructor(<br>    @Inject(AI_CLIENT) private readonly ai: AiClient,<br>  ) {}<br><br>  async generateBlogPost(topic: string): Promise&lt;string&gt; {<br>    const prompt = `Write a professional blog post about: ${topic}`;<br>    return this.ai.generate(prompt);<br>  }<br><br>  async summarizeDocument(text: string): Promise&lt;string&gt; {<br>    const prompt = `Summarize the following text:\n\n${text}`;<br>    return this.ai.generate(prompt);<br>  }<br><br>  async estimateCost(prompt: string): Promise&lt;number&gt; {<br>    if (!this.ai.estimateTokens) {<br>      return 0; // Provider doesn&#39;t support cost estimation<br>    }<br><br>    const tokens = this.ai.estimateTokens(prompt);<br>    const costPerToken = 0.00001; // Example rate<br>    return tokens * costPerToken;<br>  }<br>}</pre><h3>Real-World Power Moves</h3><h4>1. Multi-Provider Routing</h4><p>Route different tasks to different providers based on requirements:</p><pre>// src/ai/smart-router.service.ts<br>import { Injectable, Inject } from &#39;@nestjs/common&#39;;<br>import { OpenaiService } from &#39;./providers/openai.service&#39;;<br>import { GeminiService } from &#39;./providers/gemini.service&#39;;<br>import { AnthropicService } from &#39;./providers/anthropic.service&#39;;<br><br>@Injectable()<br>export class SmartAiRouter {<br>  constructor(<br>    private openai: OpenaiService,<br>    private gemini: GeminiService,<br>    private anthropic: AnthropicService,<br>  ) {}<br><br>  async generate(prompt: string, options?: {<br>    priority?: &#39;speed&#39; | &#39;cost&#39; | &#39;quality&#39;;<br>    maxTokens?: number;<br>  }) {<br>    const priority = options?.priority || &#39;cost&#39;;<br><br>    // Route based on requirements<br>    switch (priority) {<br>      case &#39;speed&#39;:<br>        return this.gemini.generate(prompt); // Gemini Flash is fastest<br>      case &#39;cost&#39;:<br>        return this.gemini.generate(prompt); // Gemini is cheapest<br>      case &#39;quality&#39;:<br>        return this.anthropic.generate(prompt); // Claude for best results<br>    }<br>  }<br>}</pre><h4>2. <strong>A/B Testing Different Models</strong></h4><pre>// src/ai/ab-test.service.ts<br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { OpenaiService } from &#39;./providers/openai.service&#39;;<br>import { GeminiService } from &#39;./providers/gemini.service&#39;;<br><br>@Injectable()<br>export class AiAbTestService {<br>  constructor(<br>    private openai: OpenaiService,<br>    private gemini: GeminiService,<br>  ) {}<br><br>  async generateWithComparison(prompt: string, userId: string) {<br>    // Hash user ID to consistently assign them to a provider<br>    const useOpenAI = this.hashUserId(userId) % 2 === 0;<br><br>    const startTime = Date.now();<br>    const provider = useOpenAI ? this.openai : this.gemini;<br>    const response = await provider.generate(prompt);<br>    const latency = Date.now() - startTime;<br><br>    // Log metrics for analysis<br>    await this.logMetrics({<br>      userId,<br>      provider: useOpenAI ? &#39;openai&#39; : &#39;gemini&#39;,<br>      latency,<br>      promptLength: prompt.length,<br>      responseLength: response.length,<br>    });<br><br>    return response;<br>  }<br><br>  private hashUserId(userId: string): number {<br>    return userId.split(&#39;&#39;).reduce((acc, char) =&gt; acc + char.charCodeAt(0), 0);<br>  }<br><br>  private async logMetrics(metrics: any) {<br>    // Send to your analytics service<br>    console.log(&#39;AB Test Metrics:&#39;, metrics);<br>  }<br>}</pre><p>3. <strong>Fallback Chain for Reliability</strong></p><pre>// src/ai/resilient-ai.service.ts<br>import { Injectable, Logger } from &#39;@nestjs/common&#39;;<br>import { AiClient } from &#39;./ai-client.interface&#39;;<br>import { OpenaiService } from &#39;./providers/openai.service&#39;;<br>import { GeminiService } from &#39;./providers/gemini.service&#39;;<br>import { AnthropicService } from &#39;./providers/anthropic.service&#39;;<br><br>@Injectable()<br>export class ResilientAiService implements AiClient {<br>  private readonly logger = new Logger(ResilientAiService.name);<br>  private readonly providers: AiClient[];<br><br>  constructor(<br>    openai: OpenaiService,<br>    gemini: GeminiService,<br>    anthropic: AnthropicService,<br>  ) {<br>    // Try providers in order of preference<br>    this.providers = [gemini, anthropic, openai];<br>  }<br><br>  async generate(prompt: string): Promise&lt;string&gt; {<br>    let lastError: Error | null = null;<br><br>    for (const provider of this.providers) {<br>      try {<br>        this.logger.log(`Trying provider: ${provider.constructor.name}`);<br>        return await provider.generate(prompt);<br>      } catch (error) {<br>        lastError = error;<br>        this.logger.warn(<br>          `Provider ${provider.constructor.name} failed: ${error.message}`<br>        );<br>        // Continue to next provider<br>      }<br>    }<br><br>    throw new Error(<br>      `All AI providers failed. Last error: ${lastError?.message}`<br>    );<br>  }<br>}</pre><h4>Configuration: The .env File</h4><pre># .env<br><br># Primary provider selection<br>AI_PROVIDER=gemini  # Options: openai, gemini, anthropic<br><br># OpenAI Configuration<br>OPENAI_API_KEY=sk-...<br>OPENAI_MODEL=gpt-4o-mini<br><br># Gemini Configuration<br>GEMINI_API_KEY=...<br>GEMINI_MODEL=gemini-2.0-flash<br><br># Anthropic Configuration<br>ANTHROPIC_API_KEY=sk-ant-...<br>ANTHROPIC_MODEL=claude-sonnet-4-20250514</pre><p><strong>Switching providers:</strong></p><ol><li>Change AI_PROVIDER=gemini to AI_PROVIDER=openai</li><li>Restart your app</li><li>That’s it. No code changes.</li></ol><h3>Testing Strategy</h3><h4>Unit Tests (Mock the Interface)</h4><pre>// src/chat/chat.controller.spec.ts<br>import { Test } from &#39;@nestjs/testing&#39;;<br>import { ChatController } from &#39;./chat.controller&#39;;<br>import { AI_CLIENT, AiClient } from &#39;../ai/ai-client.interface&#39;;<br><br>describe(&#39;ChatController&#39;, () =&gt; {<br>  let controller: ChatController;<br>  let mockAiClient: AiClient;<br><br>  beforeEach(async () =&gt; {<br>    mockAiClient = {<br>      generate: jest.fn().mockResolvedValue(&#39;Mocked response&#39;),<br>    };<br><br>    const module = await Test.createTestingModule({<br>      controllers: [ChatController],<br>      providers: [<br>        {<br>          provide: AI_CLIENT,<br>          useValue: mockAiClient,<br>        },<br>      ],<br>    }).compile();<br><br>    controller = module.get&lt;ChatController&gt;(ChatController);<br>  });<br><br>  it(&#39;should generate AI response&#39;, async () =&gt; {<br>    const result = await controller.chat(&#39;Hello&#39;);<br>    <br>    expect(mockAiClient.generate).toHaveBeenCalledWith(&#39;Hello&#39;);<br>    expect(result).toEqual({ response: &#39;Mocked response&#39; });<br>  });<br>});</pre><h4>Integration Tests (Test Real Providers)</h4><pre>// src/ai/providers/openai.service.spec.ts<br>import { Test } from &#39;@nestjs/testing&#39;;<br>import { ConfigService } from &#39;@nestjs/config&#39;;<br>import { OpenaiService } from &#39;./openai.service&#39;;<br><br>describe(&#39;OpenaiService (Integration)&#39;, () =&gt; {<br>  let service: OpenaiService;<br><br>  beforeEach(async () =&gt; {<br>    const module = await Test.createTestingModule({<br>      providers: [<br>        OpenaiService,<br>        {<br>          provide: ConfigService,<br>          useValue: {<br>            get: jest.fn((key: string) =&gt; {<br>              if (key === &#39;OPENAI_API_KEY&#39;) return process.env.OPENAI_API_KEY;<br>              if (key === &#39;OPENAI_MODEL&#39;) return &#39;gpt-4o-mini&#39;;<br>            }),<br>          },<br>        },<br>      ],<br>    }).compile();<br><br>    service = module.get&lt;OpenaiService&gt;(OpenaiService);<br>  });<br><br>  it(&#39;should generate response from OpenAI&#39;, async () =&gt; {<br>    const response = await service.generate(&#39;Say &quot;test successful&quot;&#39;);<br>    <br>    expect(response).toBeTruthy();<br>    expect(response.length).toBeGreaterThan(0);<br>  }, 30000); // Allow 30s timeout for API calls<br>});</pre><h3>Performance Monitoring</h3><p>Add a decorator to track performance across all providers:</p><pre>// src/ai/decorators/track-performance.decorator.ts<br>export function TrackPerformance() {<br>  return function (<br>    target: any,<br>    propertyKey: string,<br>    descriptor: PropertyDescriptor<br>  ) {<br>    const originalMethod = descriptor.value;<br><br>    descriptor.value = async function (...args: any[]) {<br>      const startTime = Date.now();<br>      const providerName = this.constructor.name;<br><br>      try {<br>        const result = await originalMethod.apply(this, args);<br>        const duration = Date.now() - startTime;<br><br>        console.log(`✓ ${providerName}.${propertyKey} completed in ${duration}ms`);<br>        <br>        // Send to monitoring service<br>        // await metrics.track({ provider: providerName, method: propertyKey, duration });<br><br>        return result;<br>      } catch (error) {<br>        const duration = Date.now() - startTime;<br>        console.error(`✗ ${providerName}.${propertyKey} failed after ${duration}ms`);<br>        throw error;<br>      }<br>    };<br><br>    return descriptor;<br>  };<br>}<br><br>// Usage in providers:<br>@Injectable()<br>export class OpenaiService implements AiClient {<br>  @TrackPerformance()<br>  async generate(prompt: string): Promise&lt;string&gt; {<br>    // ... implementation<br>  }<br>}</pre><h3>Common Pitfalls to Avoid</h3><h4>Don’t: Make the interface too specific</h4><pre>// Bad - This is just OpenAI&#39;s API in disguise<br>interface AiClient {<br>  chatComplete(model: string, messages: ChatMessage[], temperature: number): Promise&lt;ChatResponse&gt;;<br>}</pre><h4>Do: Keep it generic and minimal</h4><pre>// Good - Works with any provider<br>interface AiClient {<br>  generate(prompt: string): Promise&lt;string&gt;;<br>}</pre><h4>Don’t: Expose provider-specific features directly</h4><pre>// Bad - Now you&#39;re coupled to OpenAI&#39;s function calling<br>async chat(message: string) {<br>  return this.ai.generate(message, { functions: [...] });<br>}</pre><h4>Do: Abstract provider features behind your interface</h4><pre>// Good - Your own abstraction for structured output<br>interface AiClient {<br>  generate(prompt: string): Promise&lt;string&gt;;<br>  generateStructured?&lt;T&gt;(prompt: string, schema: Schema): Promise&lt;T&gt;;<br>}</pre><h3>Conclusion: Future-Proof Your AI Architecture</h3><p>The AI landscape is moving fast. New models launch monthly, pricing changes weekly, and regulations vary by region. By decoupling your application from specific providers, you’re not just following best practices, you’re building insurance against an unpredictable future.</p><p><strong>What you’ve gained:</strong></p><ul><li>Switch providers in seconds, not weeks</li><li>Test multiple models simultaneously</li><li>Build fallback chains for reliability</li><li>Reduce vendor lock-in risk to near zero</li><li>Clean, testable, maintainable code</li></ul><p><strong>Your next steps:</strong></p><ol><li>Implement the basic pattern (1–2 hours)</li><li>Migrate one feature to test it (1 hour)</li><li>Add a second provider to prove flexibility (2 hours)</li><li>Roll out across your application (as needed)</li></ol><p>The best time to decouple was before you started. The second-best time is <strong><em>right now</em></strong><em>.</em></p><p>Now go build something amazing and never fear your vendor again!</p><h3>About Me</h3><p>My name is Joosep Wong, you can also reach this post on my <a href="https://medium.com/@joosepwong">medium.com</a> or my <a href="https://joosep.org/">homepage</a> where I share my solutions to the problems I encountered during my software engineer career.</p><p>If you’ve enjoyed reading my content and would like to support me, I kindly ask for a small donation of a cup of coffee. Your generosity would be greatly appreciated and will help me to continue creating meaningful and informative content. (<a href="https://ko-fi.com/joosep">donate a cup of coffee</a>).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81852d58e781" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/avoid-the-50k-refactor-the-nestjs-architecture-pattern-that-lets-you-swap-ai-providers-seamlessly-81852d58e781">Avoid the $50K Refactor: The NestJS Architecture Pattern That Lets You Swap AI Providers Seamlessly</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Complex RBAC in NestJS: Integrating CASL with Prisma ORM for Granular Authorization]]></title>
            <link>https://blog.devgenius.io/mastering-complex-rbac-in-nestjs-integrating-casl-with-prisma-orm-for-granular-authorization-767941a05ef1?source=rss-57fbdb805c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/767941a05ef1</guid>
            <category><![CDATA[casl]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[rbac-access-control]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Joosep Wong]]></dc:creator>
            <pubDate>Thu, 23 Oct 2025 05:49:57 GMT</pubDate>
            <atom:updated>2025-10-27T13:21:20.759Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tIraeSRgJ0U-Flnf0x34rQ.jpeg" /></figure><p>In the world of modern web applications, security isn’t just a checkbox — it’s a dynamic fortress. As your NestJS app scales, simple role checks like “admin can do everything” fall short. Enter Role-Based Access Control (RBAC) evolved into something far more sophisticated: a hybrid of RBAC and Attribute-Based Access Control (ABAC). This allows permissions to flex based on user attributes, resource ownership, time, or even multi-tenant isolation.</p><p>That’s where CASL shines — a lightweight, isomorphic JavaScript library for declarative authorization. Paired with Prisma (your ORM powerhouse) in a NestJS ecosystem, it enables persisted permissions, conditional rules, and query-level enforcement. No more leaky abstractions or over-fetching sensitive data.</p><p>In this deep-dive guide, we’ll build a production-ready system handling:</p><ul><li>Persisted permissions stored in your database.</li><li>Complex conditions (e.g., “users can update their own posts only if published”).</li><li>Bulk and paginated access with automatic filtering.</li><li>Guards, decorators, and service integrations for bulletproof enforcement.</li></ul><p>By the end, you’ll have a blueprint for enterprise-grade auth that scales without nightmares. Let’s dive in.</p><p><strong>Why This Stack?</strong> A Quick Rationale</p><ul><li><strong>NestJS</strong>: Modular, TypeScript-native framework for clean architecture.</li><li><strong>Prisma</strong>: Type-safe queries with seamless migrations — perfect for relational data like roles and permissions.</li><li><strong>CASL</strong>: Expressive rules like can(‘update’, ‘Post’, { ownerId: user.id }). Integrates with Prisma via @casl/prisma for SQL-level filtering.</li><li><strong>The Power Combo</strong>: RBAC for roles, ABAC for attributes. Handle multi-tenant apps where “Editor in Team A” can’t touch Team B’s data.</li></ul><p>Assumptions: You have a basic NestJS + Prisma setup (e.g., auth with JWT). If not, check <a href="https://docs.nestjs.com/">NestJS docs</a> and <a href="https://www.prisma.io/docs">Prisma quickstart</a>.</p><h4>Step 1: Database Schema — Persisting Permissions</h4><p>Permissions aren’t static config — they evolve. Store them in Prisma for admins to tweak via UI.Update your <strong><em>schema.prisma</em></strong>:</p><pre>generator client {<br>  provider = &quot;prisma-client-js&quot;<br>}<br><br>datasource db {<br>  provider = &quot;postgresql&quot;  // Or your DB of choice<br>  url      = env(&quot;DATABASE_URL&quot;)<br>}<br><br>model Role {<br>  id          Int          @id @default(autoincrement())<br>  name        String       @unique<br>  description String?<br>  permissions Permission[] @relation(&quot;RolePermissions&quot;)<br>  users       User[]       @relation(&quot;UserRoles&quot;)<br>  createdAt   DateTime     @default(now())<br>  updatedAt   DateTime     @updatedAt<br>}<br><br>model Permission {<br>  id          Int      @id @default(autoincrement())<br>  action      String   // e.g., &#39;read&#39;, &#39;update&#39;, &#39;manage&#39;<br>  subject     String   // e.g., &#39;Post&#39;, &#39;User&#39;, &#39;all&#39;<br>  conditions  Json?    // ABAC magic: { ownerId: &#39;{{ user.id }}&#39; } – templated<br>  inverted    Boolean  @default(false)<br>  reason      String?  // Audit trail: &quot;Owner-only update&quot;<br>  role        Role     @relation(&quot;RolePermissions&quot;, fields: [roleId], references: [id])<br>  roleId      Int<br>  createdAt   DateTime @default(now())<br>  updatedAt   DateTime @updatedAt<br><br>  @@unique([roleId, action, subject])<br>}<br><br>model User {<br>  id        Int      @id @default(autoincrement())<br>  email     String   @unique<br>  firstName String?<br>  lastName  String?<br>  role      Role     @relation(&quot;UserRoles&quot;, fields: [roleId], references: [id])<br>  roleId    Int<br>  posts     Post[]   @relation(&quot;UserPosts&quot;)<br>  createdAt DateTime @default(now())<br>}<br><br>model Post {<br>  id        Int     @id @default(autoincrement())<br>  title     String<br>  content   String?<br>  published Boolean @default(false)<br>  owner     User    @relation(&quot;UserPosts&quot;, fields: [ownerId], references: [id])<br>  ownerId   Int<br>  createdAt DateTime @default(now())<br>}</pre><p>Run <strong><em>npx prisma migrate dev — name init-rbac</em></strong> and seed some data:</p><pre>// prisma/seed.ts<br>import { PrismaClient, Prisma } from &#39;@prisma/client&#39;;<br>import { cloneDeep } from &#39;lodash&#39;;<br><br>const prisma = new PrismaClient();<br><br>const roles: Prisma.RoleCreateInput[] = [<br>  { name: &#39;Admin&#39;, description: &#39;Full access&#39; },<br>  { name: &#39;Editor&#39;, description: &#39;Content management&#39; },<br>  { name: &#39;Viewer&#39;, description: &#39;Read-only&#39; },<br>];<br><br>const permissions: Prisma.PermissionCreateInput[] = [<br>  // Admin: God mode<br>  { roleId: 1, action: &#39;manage&#39;, subject: &#39;all&#39; },<br>  // Editor: Read/write own posts, read all<br>  { roleId: 2, action: &#39;read&#39;, subject: &#39;Post&#39; },<br>  { roleId: 2, action: &#39;manage&#39;, subject: &#39;Post&#39;, conditions: Prisma.JsonNull }, // All posts for manage? Wait, condition below<br>  { roleId: 2, action: &#39;update&#39;, subject: &#39;Post&#39;, conditions: { ownerId: &#39;{{ user.id }}&#39; } }, // Templated condition<br>  { roleId: 2, action: &#39;update&#39;, subject: &#39;Post&#39;, conditions: { published: false } }, // Unpublished only<br>  // Viewer: Read all<br>  { roleId: 3, action: &#39;read&#39;, subject: &#39;Post&#39; },<br>];<br><br>async function main() {<br>  for (const role of roles) {<br>    await prisma.role.upsert({ where: { name: role.name }, create: role, update: role });<br>  }<br>  for (const perm of permissions) {<br>    const { roleId, ...rest } = perm;<br>    await prisma.permission.upsert({<br>      where: { roleId_action_subject: { roleId, ...rest } },<br>      create: perm,<br>      update: perm,<br>    });<br>  }<br>  // Add users...<br>}<br><br>main().catch(console.error).finally(() =&gt; prisma.$disconnect());</pre><p>Execute with <strong><em>npx prisma db seed</em></strong>. Boom — dynamic permissions!</p><h4>Step 2: Installation and CASL Setup</h4><pre>npm install @casl/ability @casl/prisma mustache lodash<br>npm install -D @types/mustache</pre><ul><li>@casl/ability: Core rule engine.</li><li>@casl/prisma: Query filtering (e.g., accessibleBy(ability)).</li><li>mustache: Templating for conditions like {{ user.id }}.</li><li>lodash: Utilities (e.g., map, cloneDeep).</li></ul><h4>Step 3: The Ability Factory — Heart of Your Rules</h4><p>This injectable service loads permissions from DB and builds CASL abilities. It parses conditions with Mustache for user-specific interpolation.</p><p>Create <strong><em>src/casl/casl-ability.factory.ts</em></strong>:</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { AbilityBuilder, AbilityClass, createMongoAbility, RawRuleOf } from &#39;@casl/ability&#39;;<br>import * as Mustache from &#39;mustache&#39;;<br>import { cloneDeep, map } from &#39;lodash&#39;;<br>import { PrismaService } from &#39;../prisma/prisma.service&#39;; // Your Prisma service<br>import { User, Permission } from &#39;@prisma/client&#39;;<br><br>export type Subjects = &#39;all&#39; | &#39;Post&#39; | &#39;User&#39;; // Add your models<br>export type Actions = &#39;create&#39; | &#39;read&#39; | &#39;update&#39; | &#39;delete&#39; | &#39;manage&#39;;<br>export type AppAbility = RawRuleOf&lt;Actions, Subjects&gt;;<br><br>@Injectable()<br>export class CaslAbilityFactory {<br>  constructor(private prisma: PrismaService) {}<br><br>  async createForUser(user: User): Promise&lt;AppAbility&gt; {<br>    const { can, build } = new AbilityBuilder&lt;AppAbility&gt;(createMongoAbility as AbilityClass&lt;AppAbility&gt;);<br><br>    // Fetch user&#39;s role permissions<br>    const permissions = await this.prisma.permission.findMany({<br>      where: { roleId: user.roleId },<br>    });<br><br>    // Parse conditions with user context<br>    const parsedPermissions = map(permissions, (perm: Permission) =&gt; {<br>      if (perm.conditions) {<br>        const templated = cloneDeep(perm.conditions);<br>        Mustache.parse(templated as string); // Assuming JSON stringified<br>        const rendered = Mustache.render(JSON.stringify(templated), { user });<br>        return { ...perm, conditions: JSON.parse(rendered) };<br>      }<br>      return perm;<br>    });<br><br>    // Build rules<br>    for (const perm of parsedPermissions) {<br>      const { action, subject, conditions, inverted } = perm;<br>      if (inverted) {<br>        build.rules.push({ inverted: true, ...perm });<br>      } else {<br>        can(action as Actions, subject as Subjects, conditions || undefined);<br>      }<br>    }<br><br>    return build();<br>  }<br>}</pre><p><strong>Pro Tip: </strong>For admins (<strong><em>role.name === ‘Admin’</em></strong>), short-circuit with <strong><em>can(‘manage’, ‘all’)</em></strong> to skip DB fetches in hot paths.</p><h4>Step 4: Guards and Decorators — Enforce at the Gate</h4><p>Guards intercept requests; decorators declare requirements. Let’s build a reusable <strong>AbilitiesGuard</strong>.</p><p>First, decorators in <strong><em>src/decorators/abilities.decorator.ts</em></strong>:</p><pre>import { SetMetadata } from &#39;@nestjs/common&#39;;<br><br>export const CHECK_ABILITY = &#39;check_ability&#39;;<br>export interface RequiredRule {<br>  action: string;<br>  subject: string;<br>  conditions?: any;<br>}<br><br>export const CheckAbilities = (...requirements: RequiredRule[]) =&gt;<br>  SetMetadata(CHECK_ABILITY, requirements);</pre><p>Now, the guard <strong><em>src/guards/abilities.guard.ts</em></strong>:</p><pre>import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from &#39;@nestjs/common&#39;;<br>import { Reflector } from &#39;@nestjs/core&#39;;<br>import { ForbiddenError } from &#39;@casl/ability&#39;;<br>import { subject } from &#39;@casl/ability&#39;;<br>import { CaslAbilityFactory } from &#39;../casl/casl-ability.factory&#39;;<br>import { User } from &#39;@prisma/client&#39;;<br>import { CHECK_ABILITY, RequiredRule } from &#39;../decorators/abilities.decorator&#39;;<br><br>@Injectable()<br>export class AbilitiesGuard implements CanActivate {<br>  constructor(<br>    private reflector: Reflector,<br>    private abilityFactory: CaslAbilityFactory,<br>  ) {}<br><br>  async canActivate(context: ExecutionContext): Promise&lt;boolean&gt; {<br>    const rules = this.reflector.get&lt;RequiredRule[]&gt;(CHECK_ABILITY, context.getHandler()) || [];<br>    if (!rules.length) return true;<br><br>    const request = context.switchToHttp().getRequest();<br>    const user: User = request.user; // From your JWT strategy<br><br>    const ability = await this.abilityFactory.createForUser(user);<br><br>    for (const rule of rules) {<br>      // Fetch subject if conditions need it (e.g., Post by ID)<br>      let sub = {};<br>      if (rule.conditions) {<br>        const id = +request.params.id;<br>        sub = await this.fetchSubject(rule.subject, id); // Implement fetchSubject<br>      }<br><br>      ForbiddenError.from(ability)<br>        .setMessage(`Forbidden: ${rule.action} on ${rule.subject}`)<br>        .throwUnlessCan(rule.action, subject(rule.subject, sub));<br>    }<br><br>    return true;<br>  }<br><br>  private async fetchSubject(subject: string, id: number) {<br>    // Use Prisma to fetch, e.g., this.prisma[subject.toLowerCase()].findUnique({ where: { id } })<br>    // Placeholder<br>    return { id };<br>  }<br>}</pre><p>Register in your module:</p><pre>// app.module.ts<br>import { CaslModule } from &#39;./casl/casl.module&#39;; // We&#39;ll create this<br><br>@Module({<br>  imports: [CaslModule],<br>  providers: [AbilitiesGuard],<br>})<br>export class AppModule {}</pre><p>And <strong><em>casl.module.ts</em></strong>:</p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { CaslAbilityFactory } from &#39;./casl-ability.factory&#39;;<br>import { PrismaModule } from &#39;../prisma/prisma.module&#39;; // Your Prisma module<br><br>@Module({<br>  imports: [PrismaModule],<br>  providers: [CaslAbilityFactory],<br>  exports: [CaslAbilityFactory],<br>})<br>export class CaslModule {}</pre><h4>Step 5: Service Layer — Query-Level Security with Prisma</h4><p>Don’t trust controllers alone — enforce in services to prevent leaks.</p><p><strong><em>src/posts/posts.service.ts:</em></strong></p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { PrismaService } from &#39;../prisma/prisma.service&#39;;<br>import { accessibleBy } from &#39;@casl/prisma&#39;;<br>import { CaslAbilityFactory } from &#39;../casl/casl-ability.factory&#39;;<br>import { User, Post } from &#39;@prisma/client&#39;;<br><br>@Injectable()<br>export class PostsService {<br>  constructor(<br>    private prisma: PrismaService,<br>    private abilityFactory: CaslAbilityFactory,<br>  ) {}<br><br>  async findAll(user: User): Promise&lt;Post[]&gt; {<br>    const ability = await this.abilityFactory.createForUser(user);<br>    return this.prisma.post.findMany({<br>      where: {<br>        AND: [<br>          accessibleBy(ability, &#39;read&#39;).Post, // Filters: e.g., { ownerId: user.id } OR published<br>          { published: true }, // Business logic<br>        ],<br>      },<br>    });<br>  }<br><br>  async update(id: number, data: Partial&lt;Post&gt;, user: User): Promise&lt;Post&gt; {<br>    const ability = await this.abilityFactory.createForUser(user);<br>    // Check ability first<br>    const post = await this.prisma.post.findUnique({ where: { id } });<br>    if (!ability.can(&#39;update&#39;, &#39;Post&#39;, post)) {<br>      throw new ForbiddenException(&#39;Cannot update this post&#39;);<br>    }<br><br>    return this.prisma.post.update({<br>      where: { id },<br>      data,<br>    });<br>  }<br>}</pre><p><strong><em>accessibleBy</em></strong> translates CASL rules to Prisma <strong><em>WhereInput</em></strong> — zero over-fetching!</p><h4>Step 6: Controllers — Putting It All Together</h4><p>Wire it up in <strong><em>src/posts/posts.controller.ts</em></strong>:</p><pre>import { Controller, Get, Put, Body, Param, UseGuards, ParseIntPipe } from &#39;@nestjs/common&#39;;<br>import { PostsService } from &#39;./posts.service&#39;;<br>import { AbilitiesGuard } from &#39;../guards/abilities.guard&#39;;<br>import { CheckAbilities, RequiredRule } from &#39;../decorators/abilities.decorator&#39;;<br>import { CurrentUser } from &#39;../decorators/current-user.decorator&#39;; // Your user extractor<br>import { User } from &#39;@prisma/client&#39;;<br><br>@Controller(&#39;posts&#39;)<br>export class PostsController {<br>  constructor(private postsService: PostsService) {}<br><br>  @Get()<br>  @UseGuards(AbilitiesGuard)<br>  @CheckAbilities({ action: &#39;read&#39;, subject: &#39;Post&#39; })<br>  async findAll(@CurrentUser() user: User) {<br>    return this.postsService.findAll(user);<br>  }<br><br>  @Put(&#39;:id&#39;)<br>  @UseGuards(AbilitiesGuard)<br>  @CheckAbilities({ action: &#39;update&#39;, subject: &#39;Post&#39;, conditions: { ownerId: &#39;{{ user.id }}&#39; } })<br>  async update(<br>    @Param(&#39;id&#39;, ParseIntPipe) id: number,<br>    @Body() data: Partial&lt;any&gt;,<br>    @CurrentUser() user: User,<br>  ) {<br>    return this.postsService.update(id, data, user);<br>  }<br>}</pre><h4>Step 7: Advanced Features — Handling Complexity Like a Pro</h4><p>Bulk Operations and PaginationFor DELETE /posts?ids=1,2,3, extend the guard with request manipulators:</p><p>Add to decorator:</p><pre>export const REQUEST_MANIPULATOR = &#39;request_manipulator&#39;;<br>export const RequestManipulator = (fn: (req: any, allowed: any) =&gt; void) =&gt;<br>  SetMetadata(REQUEST_MANIPULATOR, fn);</pre><p>In guard:</p><pre>// In canActivate<br>const manipulator = this.reflector.get(REQUEST_MANIPULATOR, context.getHandler());<br>if (manipulator) {<br>  const allowedIds = await this.getAllowedIds(user, &#39;Post&#39;); // From conditions, e.g., [user.id-owned]<br>  manipulator(request, { postIds: allowedIds });<br>}</pre><p>Controller:</p><pre>@Delete()<br>@UseGuards(AbilitiesGuard)<br>@RequestManipulator((req, { postIds }) =&gt; {<br>  req.query.ids = req.query.ids?.filter((id: number) =&gt; postIds.includes(id));<br>})<br>async bulkDelete(@CurrentUser() user: User, @Query(&#39;ids&#39;) ids: string) {<br>  // Proceed with filtered IDs<br>}</pre><p>Response Filtering for Paginated Lists</p><p>Use interceptors to trim responses:</p><pre>// posts.controller.ts<br>import { UseInterceptors } from &#39;@nestjs/common&#39;;<br>import { RESPONSE_FILTER = &#39;response_filter&#39;;<br>export const ResponseFilter = (fn: (data: any, allowed: any) =&gt; any) =&gt;<br>  SetMetadata(RESPONSE_FILTER, fn);<br><br>@UseInterceptors(ResponseInterceptor) // Custom interceptor<br>@ResponseFilter((posts, { postIds }) =&gt; posts.filter(p =&gt; postIds.includes(p.id)))<br>@Get(&#39;paginated&#39;)<br>@CheckAbilities({ action: &#39;read&#39;, subject: &#39;Post&#39; })<br>async paginated(@CurrentUser() user: User) {<br>  // Full query, filtered post-response<br>}</pre><p>Implement <strong><em>ResponseInterceptor</em></strong> similarly to the guard, attaching <strong><em>allowed</em></strong> to <strong><em>req</em></strong>.</p><h4>Multi-Tenant Conditions</h4><p>Add tenantId to User model. Conditions like <strong>{ tenantId: user.tenantId }</strong> ensure isolation. Use Prisma relations for tenant-scoped queries.</p><h4>Testing and Edge Cases</h4><ul><li><strong>Unit Test Abilities</strong>: Mock Prisma, assert ability.can(‘update’, post).</li><li><strong>E2E</strong>: Use Supertest with mocked JWT users.</li><li><strong>Performance</strong>: Cache abilities (Redis) for high-traffic; invalidate on permission changes.</li><li><strong>Audit</strong>: Log denied actions with ForbiddenError.onError.</li></ul><p>Edge: Nested resources? Chain guards or use CASL’s conditions for deep matching.</p><h4>Conclusion: Secure, Scalable, and Sane</h4><p>You’ve now got a beast: CASL + Prisma in NestJS handling RBAC’s structure with ABAC’s finesse. From DB-persisted rules to filtered queries, this setup scales to enterprises without sacrificing dev velocity.</p><p>That said, this article is not the perfect, production-polished version — it’s more of a demo wireframe to illustrate the core concepts and get you started. In a real enterprise product, things get even more complex: think hierarchical roles, policy-as-code integrations, real-time permission syncing across microservices, advanced auditing with event sourcing, and compliance hooks for GDPR/SOC2.</p><p>The foundation here is solid, but iterate and adapt it to your domain’s chaos.</p><p>You can also reach this post on my <a href="https://medium.com/@joosepwong">medium.com</a> where I share my solutions to the problems I encountered during my software engineer career.</p><p>If you have additional questions, feel free to contact me on <a href="https://www.linkedin.com/in/joosepwong/">LinkedIn</a>.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=767941a05ef1" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/mastering-complex-rbac-in-nestjs-integrating-casl-with-prisma-orm-for-granular-authorization-767941a05ef1">Mastering Complex RBAC in NestJS: Integrating CASL with Prisma ORM for Granular Authorization</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Integrate Smart-ID RP v3 Authentication in Node.js/NestJS Applications]]></title>
            <link>https://medium.com/codetodeploy/how-to-integrate-smart-id-rp-v3-authentication-in-node-js-nestjs-applications-a136e6942a3c?source=rss-57fbdb805c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a136e6942a3c</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[smart-id]]></category>
            <category><![CDATA[sk-solutions]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Joosep Wong]]></dc:creator>
            <pubDate>Wed, 02 Jul 2025 17:09:51 GMT</pubDate>
            <atom:updated>2025-11-01T01:27:56.824Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*C12fjesWKj2e5p-IPJlH8A.png" /></figure><h4>🔥 Work Remotely with Top Global Teams!</h4><p>Join exciting F<strong>ull-Time &amp; Contract</strong> projects worldwide 🌍</p><p>🚀 <strong>Roles:</strong><br>Frontend · Backend · Full Stack · Mobile (React Native, Flutter) · UI/UX · DevOps · AI &amp; Data</p><p>💰 <strong>Pay:</strong> $30 — $120/hr<br>⏳ Complete your profile &amp; apply early — top companies hire fast!</p><p>👉 <a href="https://app.usebraintrust.com/r/code6/"><strong>Apply Now</strong></a><strong> — Secure the Best Offers!</strong></p><p>From the very first day I heard the name “Estonia,” I was deeply drawn to the concept of its e-government. Among all the digital solutions, I particularly liked using SmartID as a login method.</p><p><em>(SmartID is a secure electronic authentication and digital signature solution used widely in the Baltics. It allows users to log in to online services, confirm transactions, or sign documents by securely verifying their identity, all through a mobile app.)</em></p><p>Even before I set foot in Estonia, I was already used to using SmartID — especially because it works perfectly with my e-Residency. However, the official client libraries only existed for Java and PHP. Other third-party libraries were available, but there was a clear gap: no proper Node.js library. That made me wonder — should I develop one myself?</p><p>Fast forward to June 2025, I believe now is the perfect time. SK Solutions officially released RP API v3.1 on June 20, 2025. This version is a major improvement. From the first day I learned about SmartID, I couldn’t help but think — in countries with huge populations, or if targeted by hackers, SmartID in its old form would struggle to survive, because anyone could flood the system by brute-forcing national ID numbers.</p><p>That’s why the addition of device link-based interaction flows — like QR code scanning, Web-to-App, and App-to-App for authentication, signing, and certificate choice — is a truly smart and necessary evolution.</p><h3>Understanding the Theory You Must Know</h3><p>Before diving into code, it’s essential to understand how the <strong>Smart-ID Relying Party (RP) API</strong> works.</p><p>Smart-ID allows websites and apps to securely authenticate users or create digital signatures by interacting with the Smart-ID mobile app. The RP API provides a set of clear, structured endpoints to perform these operations.</p><h4>Two Main Types of Flows</h4><p>There are two ways your system can initiate Smart-ID authentication or signing:</p><h3>1. Device Link Based Flow (Recommended)</h3><ul><li>Most secure option.</li><li>User interacts via:</li><li><strong>QR code</strong> (cross-device: scan with Smart-ID app on phone)</li><li><strong>Web2App</strong> (same-device browser link)</li><li><strong>App2App</strong> (same-device app link)</li><li>No need to know user’s ID code upfront (in anonymous flow).</li></ul><h3>2. Notification Based Flow</h3><ul><li>Sends a <strong>push notification</strong> to all user’s Smart-ID devices.</li><li>Requires knowing user’s <strong>ID code</strong> or <strong>document number</strong>.</li><li>Useful if you already have this information and want a simpler experience.</li></ul><h3>Cross-Device vs Same-Device</h3><ul><li>User on PC/Smart-ID app on phone: <strong>Device Link QR Code</strong> (cross-device)</li><li>User on mobile browser or app with Smart-ID app installed: <strong>Web2App or App2App</strong> (same-device)</li><li>RP already knows user’s document number: Use device-link/document/{document-number} or notification flow</li></ul><h4><strong>Best practice:</strong></h4><p>Always prefer <strong>anonymous device link flow</strong> for same-device scenarios unless the document number is already known — it gives the best user experience and avoids typing errors.</p><h4>Where to Learn More</h4><ul><li><a href="https://sk-eid.github.io/smart-id-documentation/rp-api/api_specification.html">Smart-ID OpenAPI Specification</a></li></ul><h3>Smart-ID Node.js Client — Quick &amp; Simple Tutorial</h3><p>This guide shows you step by step how to use the world’s first Node.js library for Smart-ID RP <strong>v3</strong>, so you can securely authenticate users with Smart-ID in your app or website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XoeoLdKk7fqrF_Qi5ZRpcQ.png" /></figure><p><strong>DEMO!!!：</strong>This guide shows you step by step how to use the world’s first Node.js library for Smart-ID RP v3, so you can securely authenticate users with Smart-ID in your app or website.</p><p>For demonstration purposes, I’ve built a working <strong>NestJS demo</strong> project using the<a href="https://github.com/arendajaelu/smart-id-node-client"> <strong><em>@arendajaelu/smart-id-node-client</em></strong></a> library. The examples in this tutorial are based on that demo’s source code.</p><p>If you already have access to a Smart-ID demo account and the Smart-ID mobile app, you can follow along and <a href="https://smartid.joosep.org/"><strong>play around with the demo</strong></a> to better understand how the integration works in practice.</p><h3><strong>1. Install the Library</strong></h3><p>Run this in your project:</p><pre>npm install @arendajaelu/smart-id-node-client</pre><h3>2. Basic Project Setup</h3><p>Import the client and request builder:</p><pre>import {<br>  SmartIdAuthClient,<br>  AuthenticationRequestBuilder,<br>  AuthenticationResponseValidator,<br>  CallbackValidationEntity,<br>} from &#39;@arendajaelu/smart-id-node-client&#39;;</pre><h3>3. Create the Smart-ID Client</h3><p>Set the API endpoint to the <strong>Smart-ID DEMO environment</strong>:</p><pre>this.client = new SmartIdAuthClient({<br>      relyingPartyUUID: &#39;00000000-0000-4000-8000-000000000000&#39;,<br>      relyingPartyName: &#39;DEMO&#39;,<br>      hostUrl: &#39;https://sid.demo.sk.ee/smart-id-rp&#39;,<br>    });</pre><h3>4. Build an Authentication Request</h3><p>The builder helps you generate a secure and valid authentication request easily. Example for AnonymousDeviceLink for the <strong>same-device login.</strong></p><pre>const callbackParam = randomBytes(16).toString(&#39;hex&#39;);<br><br>const requestPayload = new AuthenticationRequestBuilder(<br>    &#39;00000000-0000-4000-8000-000000000000&#39;,<br>    &#39;DEMO&#39;,<br>)<br>.withInitialCallbackUrl(<br>  `https://website/redirect?chksum=${callbackParam}`,<br>).withInteractions({<br>   type: &#39;displayTextAndPIN&#39;,<br>   displayText60: &#39;Login with Smart-ID&#39;,<br>   })<br>.build();<br><br> const { response, sessionStartTime } = await this.client<br>   .setSchemeName(&#39;smart-id-demo&#39;)<br>   .getAuthenticateAnonymousDeviceLink(requestPayload);<br><br> const link = this.client<br>   .setSchemeName(&#39;smart-id-demo&#39;)<br>   .createDeviceLinkUrl(response, requestPayload, sessionStartTime, {<br>     deviceLinkType: &#39;Web2App&#39;,<br>  });</pre><h3>5. Start Authentication</h3><p>In an <strong>anonymous same-device flow</strong>, the user does <strong>not</strong> enter their ID code. Instead, your system generates a secure link (Web2App or App2App) that the user interacts with.</p><p>When the user clicks this link, the Smart-ID app is automatically opened on the <strong>same device</strong>. The user completes PIN-based authentication within the Smart-ID app.</p><p>After successful authentication, the Smart-ID app redirects the user back to your application via the pre-configured callback URL. The following fields are attached to your backend by the Smart-ID app as part of the callback request:</p><pre>chksum: string;<br>sessionSecretDigest: string;<br>userChallengeVerifier: string;</pre><pre>// Load session data from Redis (or cache) based on the checksum from callback<br>const sessionData = await this.cacheManager.get&lt;{<br>  sessionSecret: string;<br>  sessionID: string;<br>  requestPayload: any;<br>}&gt;(`smartid:${chksum}`);<br><br>if (!sessionData) {<br>  return { success: false, error: &#39;Session expired or invalid.&#39; };<br>}<br><br>const { sessionSecret, sessionID, requestPayload } = sessionData;<br><br>// Get authentication response from Smart-ID<br>const authResponse = await this.client.getSessionStatus(sessionID);<br><br>// Prepare trusted certificate path<br>const certificatesPath = path.resolve(process.cwd(), &#39;resources&#39;);<br><br>// Initialize response validator with trusted CA certificates<br>const validator = new AuthenticationResponseValidator(certificatesPath);<br><br>// Prepare callback validation entity<br>const callbackEntity: CallbackValidationEntity = {<br>  sessionSecretDigest,<br>  userChallengeVerifier,<br>  sessionSecret,<br>  schemeName: &#39;smart-id-demo&#39;,<br>  authenticationResponse: authResponse,<br>};<br><br>// Run full validation (callback + authentication response)<br>const validationResult = validator<br>  .withCallbackUrlValidate(callbackEntity)<br>  .validate(authResponse, requestPayload)<br>  .getResult();<br><br>// Check for errors<br>if (validationResult.hasError()) {<br>  return {<br>    success: false,<br>    error: `Validation failed: ${JSON.stringify(validationResult.getErrors())}`,<br>  };<br>}<br><br>// Extract authenticated identity<br>const identity = validationResult.getIdentity();</pre><h3>6. Optional Advanced Verifications (Highly Recommended for Production)</h3><p>After successfully receiving and validating the Smart-ID authentication response, you can apply two additional, recommended verification steps to strengthen security:</p><h4>Step 1: Certificate Policy OID Validation</h4><pre>// Define allowed certificate policy OIDs<br>const allowOIDs = [<br>  // EU Qualified Certificates<br>  &#39;0.4.0.1862.1.1&#39;,  // Qualified Certificate<br>  &#39;0.4.0.1862.1.5&#39;,  // Qualified Electronic Signature<br>  &#39;0.4.0.1862.1.6&#39;,  // Qualified Electronic Seal<br><br>  // Estonian SK Certificates<br>  &#39;1.3.6.1.4.1.4146.1.1&#39;,   // SK Person Certificate<br>  &#39;1.3.6.1.4.1.4146.1.2&#39;,   // SK Legal Entity Certificate<br>  &#39;1.3.6.1.4.1.10015.17.2&#39;, // SK Smart-ID Qualified Certificate<br><br>  //.....<br>];<br><br>// Run certificate policy check<br>const allowPoliciesCheck = validator.checkIfHasAllowedCertificatePolicies(<br>  identity.getCertificate(),<br>  allowOIDs,<br>);<br><br>if (!allowPoliciesCheck) {<br>  throw new Error(&#39;Certificate policy validation failed: Untrusted certificate presented.&#39;);<br>}</pre><h4>Step 2: ACSP_V2 Signature Verification</h4><p>This reconstructs and verifies the Smart-ID ACSP_V2 signature to ensure message integrity and protect against tampering.</p><pre>const isVerified = validator<br>  .withSchemeName(&#39;smart-id-demo&#39;)      <br>  .withInteractionTypeUsed(&#39;displayTextAndPIN&#39;) <br>  .withFlowType(&#39;Web2App&#39;)               <br>  .verifySignature(authResponse, requestPayload);<br><br>if (isVerified) {<br>  this.logger.log(&#39;ACSP_V2 signature successfully verified.&#39;);<br>} else {<br>  this.logger.error(&#39;ACSP_V2 signature verification FAILED.&#39;);<br>  throw new Error(&#39;Signature verification failed. Possible tampering detected.&#39;);<br>}</pre><h4>Why These Steps Matter</h4><ul><li>Confirms the presented certificate matches trusted Estonian or EU identity schemes</li><li>Ensures the authentication response was signed by the user’s legitimate Smart-ID certificate</li><li>Protects against replay attacks, tampering, and misuse of forged responses</li></ul><p>These checks are especially important for production systems where high security and legal compliance are required. These additional verifications are highly recommended to defend against known threats, as described in the official <a href="https://github.com/SK-EID/smart-id-documentation/wiki/Secure-Implementation-Guide#threats-and-attacks">Secure Implementation Guide — Threats and Attacks</a>.</p><h3>Conclusion</h3><p>This tutorial demonstrated how to integrate with Smart-ID RP v3 using the brand-new Node.js library <a href="https://www.npmjs.com/package/@arendajaelu/smart-id-node-client"><strong>@arendajaelu/smart-id-node-client</strong></a>, focusing specifically on the latest <strong>Anonymous Device Link</strong> authentication and verification flow.</p><p>The Anonymous Device Link approach greatly simplifies the user experience, especially for same-device scenarios, while providing strong security protections.</p><p>In the next part of this tutorial series, we will explore how to implement <strong>QR code flows for cross-device authentication</strong> and the <strong>traditional notification-based flow</strong>, giving you a complete picture of Smart-ID integration options.</p><p>It’s important to mention that this library was developed rather quickly to fill the long-standing gap of a proper Node.js Smart-ID client. As such, there may still be imperfections or missing features.</p><p>Contributions are warmly welcome to help improve, stabilize, and expand this library for the whole community.</p><p>Feel free to test, provide feedback, or join the project on GitHub to make Smart-ID Node.js integration even better.</p><p>You can also reach this post on my <a href="https://medium.com/@joosepwong">medium.com</a> where I share my solutions to the problems I encountered during my software engineer career.</p><p>If you have additional questions, feel free to contact me on <a href="https://www.linkedin.com/in/joosepwong/">LinkedIn</a>.</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nSB2gwj83y8MJ41gOWuLog.png" /></figure><p>👉 Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></p><p>👉 Follow us: <a href="https://x.com/Bhuwanchet67277"><strong>X</strong></a> | <a href="https://medium.com/codetodeploy"><strong>Medium</strong></a></p><p>👉 CodeToDeploy Tech Community is live on Discord — <a href="https://discord.gg/ZpwhHq6D"><strong>Join now!</strong></a></p><p>👉 <strong>Follow our publication, </strong><a href="https://medium.com/codetodeploy"><strong>CodeToDeploy</strong></a></p><p><strong>Note:</strong> This Post may contain affiliate links.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a136e6942a3c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codetodeploy/how-to-integrate-smart-id-rp-v3-authentication-in-node-js-nestjs-applications-a136e6942a3c">How to Integrate Smart-ID RP v3 Authentication in Node.js/NestJS Applications</a> was originally published in <a href="https://medium.com/codetodeploy">CodeToDeploy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Hidden Scope Trap in NestJS: How It Breaks Your Task Parallelism]]></title>
            <link>https://blog.devgenius.io/the-hidden-scope-trap-in-nestjs-how-it-breaks-your-task-parallelism-838d9c52722c?source=rss-57fbdb805c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/838d9c52722c</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[nest]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Joosep Wong]]></dc:creator>
            <pubDate>Tue, 24 Jun 2025 08:44:12 GMT</pubDate>
            <atom:updated>2025-11-06T07:48:44.927Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H_ecEhgTxW51k7iRvzLZvg.png" /></figure><p>Recently, a friend reached out with an odd issue in their NestJS application. <em>“They’re seeing tasks from different users getting mixed up… but I thought Node.js processed everything concurrently?”</em></p><p>This pointed to a common misconception about how Node.js and NestJS actually manage operations behind the scenes. To unpack what’s really happening, we first need to clarify how Node.js handles parallel workloads, since many subtle bugs stem from these core mechanics.</p><h3>Node.js Parallel Processing Explained</h3><p>Node.js is often described as:</p><ul><li>Single-threaded</li><li>Event-driven</li><li>Non-blocking</li></ul><p>At first glance, “single-threaded” and “parallel” may sound contradictory — but they’re not.</p><h3>The Event Loop: Your Parallel Processing Hero</h3><p>Here’s the simplified flow:</p><ol><li>The <strong>event loop</strong> receives a request.</li><li>If the request involves a non-blocking operation (e.g., file I/O, database queries), it delegates that task to the OS or thread pool.</li><li>Meanwhile, the event loop continues to process other incoming requests.</li><li>When the task completes, the callback is queued and eventually executed.</li></ol><p>This is how Node.js achieves massive concurrency — even with a single-threaded core — as long as your tasks are <strong>non-blocking</strong>.</p><p>However, compute-heavy synchronous code can block the event loop, making your server unresponsive. That’s why understanding the difference between asynchronous and synchronous operations is critical.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*pt8JxIOSkN_uwEiYnNLklw.png" /></figure><p><em>(You can explore this deeper in the official </em><a href="https://nodejs.org/en/learn/asynchronous-work/event-loop-timers-and-nexttick"><em>Node.js documentation</em></a><em>.)</em></p><h3>But Where Do NestJS Developers Go Wrong?</h3><p>NestJS builds on top of Node.js, providing structure, dependency injection, and a more backend-friendly development experience.</p><p><strong>But here’s the trap:</strong></p><p>Many developers forget that NestJS services, by default, are <strong>singletons</strong>.</p><p>This means:</p><ul><li>Class properties inside your services live <strong>across all requests</strong>.</li><li>If you use those properties to track per-request or per-task state — they leak between users.</li><li>Combine that with parallel task execution, and boom — your data gets mixed up.</li></ul><h3>The Debug Story: When Parallel Tasks Get Mixed Up</h3><p>Here’s the example code, simplified but realistic:</p><pre>@Injectable()<br>export class TaskService {<br>  private taskCount = 0;<br><br>  async processTasks(): Promise&lt;number&gt; {<br>    for (let i = 0; i &lt; 10; i++) {<br>      await this.simulateTask();<br>      this.taskCount++;<br>    }<br>    return this.taskCount;<br>  }<br><br>  private async simulateTask() {<br>    await new Promise(res =&gt; setTimeout(res, 500)); // Simulate async work<br>  }<br>}</pre><p>The controller looked like this:</p><pre>@Controller(&#39;tasks&#39;)<br>export class TaskController {<br>  constructor(private readonly taskService: TaskService) {}<br><br>  @Post()<br>  handleTasks(): Promise&lt;number&gt; {<br>    return this.taskService.processTasks();<br>  }<br>}</pre><p>It worked fine locally.</p><p>But when they sent <strong>two</strong> POST requests just <strong>1</strong> second apart, both responses returned unexpected numbers. The second request showed results already “polluted” by the first request’s progress.</p><h3>Stop and Think: What Do You Expect to Happen?</h3><p>Imagine this is your code, deployed to production.</p><p>Two users send a POST /tasks request — one second apart.</p><p><strong>What output would you expect?</strong></p><p>Many developers assume:</p><blockquote><em>“First request increments </em><em>taskCount to 10 and returns 10.&quot;<br> &quot;Second request runs separately, increments its own </em><em>taskCount to 10, returns 10.&quot;</em></blockquote><p>That would be true — <strong>if each request had its own isolated state</strong>.</p><p>But here’s the hidden problem:</p><ul><li>NestJS services are <strong>singleton by default</strong>.</li><li>Both requests share the same TaskService instance.</li><li>The taskCount variable lives in memory, shared between them.</li><li>Both requests modify taskCount at the same time.</li></ul><p><strong><em>In reality: </em></strong>The first request may return a value somewhere between <strong>10 and 20</strong>, depending on timing. The second request will likely return <strong>20</strong>, after both loops finish.</p><h3>The Root Cause: NestJS Variable Scope</h3><p>Let’s make this crystal clear:</p><p>By default:</p><ul><li>NestJS creates <strong>one instance</strong> of TaskService for the entire app.</li><li>Class properties like this.taskCount live across all requests.</li><li>Without careful scope management, your tasks mix together silently.</li></ul><h3>How to Fix the Problem</h3><p><strong>Option 1: Use Local Variables<br></strong>The safest, simplest option for task-specific state:</p><pre>async processTasks(): Promise&lt;number&gt; {<br>  let taskCount = 0;<br><br>  for (let i = 0; i &lt; 10; i++) {<br>    await this.simulateTask();<br>    taskCount++;<br>  }<br>  return taskCount;<br>}</pre><p>Each request has its own taskCount. No shared state. No surprises.</p><p><strong>Option 2: Use Request Scope<br></strong>If you need state that persists across multiple methods during one request:</p><pre>@Injectable({ scope: Scope.REQUEST })<br>export class TaskService {<br>  private taskCount = 0;<br>}</pre><p>NestJS now creates a new TaskService instance per request.</p><p><strong>Tradeoffs:</strong></p><ul><li>Increased memory usage</li><li>Slightly higher object creation/destruction overhead</li><li>Be careful with resources like database connections inside request-scoped services</li></ul><p><strong>Option 3: Locks for Singleton Services<br></strong>If shared state is intentional, use a lock to prevent parallel access:</p><pre>import { Lock } from &#39;async-await-mutex-lock&#39;;<br><br>const lock = new Lock();<br><br>@Injectable()<br>export class TaskService {<br>  private taskCount = 0;<br><br>  async processTasks(): Promise&lt;number&gt; {<br>    await lock.acquire();<br>    for (let i = 0; i &lt; 10; i++) {<br>      await this.simulateTask();<br>      this.taskCount++;<br>    }<br>    lock.release();<br>    return this.taskCount;<br>  }<br>}</pre><p><strong>Tradeoffs:</strong></p><ul><li>Prevents race conditions</li><li>Slows down request handling — tasks run sequentially</li></ul><h3>Beyond Scope: Offloading Heavy Tasks the Right Way</h3><p>Scope fixes shared state, but doesn’t help when:</p><ul><li>Your tasks are CPU-heavy</li><li>They block the event loop</li></ul><p>For that, use:</p><p><strong>Worker Threads</strong></p><p>Run heavy logic in separate threads:</p><pre>const worker = new Worker(&#39;./worker.js&#39;, { workerData: someData });</pre><p>Each worker has its own memory and event loop.</p><p><strong>Clustering<br></strong>Spin up multiple Node.js processes:</p><pre>ClusterService.clusterize(bootstrap);  </pre><p>Each process handles requests independently.</p><p><strong>Child Processes<br></strong>Launch isolated Node.js processes for external tasks:</p><pre>const child = spawn(&#39;node&#39;, [&#39;child.js&#39;]);  </pre><p><strong>Microservices</strong></p><p>Break your system into small, independent services. Each service scales, deploys, and isolates its workload separately.</p><h3>Final Takeaways — Master Scope, Avoid Headaches</h3><p>The most common mistake I see in NestJS code reviews and interviews:</p><blockquote><em>Developers assume class properties are isolated per request. They’re not.</em></blockquote><p>✅ Use local variables for request-specific state<br> ✅ Use Scope.REQUEST if needed<br> ✅ Be mindful of shared state in singleton services<br> ✅ Offload heavy work to workers, clusters, or microservices</p><h3>Interview Tip</h3><p>When asked about NestJS parallel tasks:</p><p>✅ Always mention the singleton nature of services<br>✅ Explain how to avoid shared-state bugs<br>✅ Show awareness of Node.js event loop behavior</p><p>That shows true backend engineering maturity — and it could save your next project from a production disaster.</p><p>You can also reach this post on my <a href="https://medium.com/@joosepwong">medium.com</a> where I share my solutions to the problems I encountered during my software engineer career.</p><p>If you have additional questions, feel free to contact me on <a href="https://www.linkedin.com/in/joosepwong/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=838d9c52722c" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/the-hidden-scope-trap-in-nestjs-how-it-breaks-your-task-parallelism-838d9c52722c">The Hidden Scope Trap in NestJS: How It Breaks Your Task Parallelism</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Struggling with Request Data in NestJS: Use Async Local Storage]]></title>
            <link>https://blog.devgenius.io/stop-struggling-with-request-data-in-nestjs-use-async-local-storage-062c164f021b?source=rss-57fbdb805c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/062c164f021b</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[als]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[async]]></category>
            <dc:creator><![CDATA[Joosep Wong]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 08:43:53 GMT</pubDate>
            <atom:updated>2024-12-02T16:35:44.765Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*emrfG7Wo2X4XHI2BWnToAg.jpeg" /></figure><p>Managing request-specific data across services is a common challenge in modern applications. In NestJS, as applications scale and grow more complex, handling such data efficiently becomes even more critical. This article delves into how Async Local Storage (ALS), a powerful Node.js API, can simplify context propagation and improve the maintainability of your NestJS application.</p><h3>The Problem: Passing Request Data Across Layers</h3><p>In a typical NestJS application, services often need to access request-specific data such as headers, cookies, and user information. Without a streamlined approach, this can result in tightly coupled code where data must be passed explicitly between layers. This practice:</p><ol><li><strong>Introduces Boilerplate</strong>: Repeatedly passing data through function signatures creates redundant code.</li><li><strong>Increases Complexity</strong>: Maintaining consistency across the application becomes challenging as new features and routes are added.</li><li><strong>Limits Scalability</strong>: Explicit propagation tightly couples services, reducing flexibility.</li></ol><h3>Real-World Challenge</h3><p>As part of a migration project, I worked on building an authentication service in NestJS to act as a proxy between a React/Svelte frontend and a legacy PHP system. The goal was to decouple authentication from WordPress while preserving compatibility with the legacy system. However, maintaining the fidelity of requests (headers, cookies, and client IPs) became a challenge:</p><ul><li>Intermediary services like Cloudflare altered headers and masked the original client IP.</li><li>Consistently passing headers and cookies through multiple layers led to tightly coupled and unmaintainable code.</li></ul><h3>The Solution: Async Local Storage (ALS)</h3><p><strong>Async Local Storage</strong> is a Node.js API, based on async_hooks, that provides a mechanism for storing and retrieving context across asynchronous operations. Think of it as &quot;thread-local storage&quot; for Node.js, enabling request-scoped context propagation without explicitly passing data.</p><h3>How ALS Works</h3><ol><li><strong>Execution Context</strong>: ALS tracks the state of asynchronous operations, maintaining context across nested calls.</li><li><strong>Scoped Context</strong>: It ensures that data stored in one request’s context remains isolated and consistent, even when handling concurrent requests.</li><li><strong>Async Hook Integration</strong>: Internally, ALS uses async_hooks to associate data with specific execution contexts.</li></ol><h3>Solution 1: Explicit Data Propagation</h3><p>The traditional approach involves extracting and explicitly passing request-specific data to services.</p><h3>Implementation</h3><p><strong>Controller: Extract Headers</strong></p><pre>const headersToExtract = [&#39;user-agent&#39;, &#39;authorization&#39;, &#39;x-request-id&#39;];<br><br>@Post(&#39;authenticate&#39;)<br>async authenticateUser(@Body() credentials: AuthDto, @Req() req: FastifyRequest) {<br>  const extractedHeaders: Record&lt;string, string&gt; = {};<br>  headersToExtract.forEach((header) =&gt; {<br>    if (req.headers[header]) {<br>      extractedHeaders[header] = req.headers[header];<br>    }<br>  });<br>  return this.authService.processLogin(credentials.email, credentials.password, extractedHeaders);<br>}</pre><p>Service: Forward Headers</p><pre>async processLogin(email: string, password: string, headers: Record&lt;string, string&gt;) {<br>  return this.externalAuthService.sendLoginRequest(email, password, headers);<br>}</pre><h3>Drawbacks</h3><ul><li><strong>Boilerplate Code</strong>: Headers must be extracted and passed at every layer.</li><li><strong>Scalability Issues</strong>: Adding more routes or headers increases code duplication.</li><li><strong>Maintenance Overhead</strong>: Refactoring becomes challenging in tightly coupled systems.</li></ul><h3>Solution 2: Using Async Local Storage in NestJS</h3><p>ALS provides a cleaner and more maintainable solution by eliminating explicit parameter passing. Here’s how to implement ALS in NestJS.</p><h3>Step 1: Create an ALS Module</h3><p>Define an AsyncLocalStorage instance and register it as a provider.</p><pre>import { AsyncLocalStorage } from &#39;async_hooks&#39;;<br><br>export type RequestContext = {<br>  headers: Record&lt;string, string&gt;;<br>};<br><br>@Module({<br>  providers: [<br>    {<br>      provide: &#39;REQUEST_CONTEXT_STORAGE&#39;,<br>      useValue: new AsyncLocalStorage&lt;RequestContext&gt;(),<br>    },<br>  ],<br>  exports: [&#39;REQUEST_CONTEXT_STORAGE&#39;],<br>})<br>export class RequestContextModule {}</pre><h3>Step 2: Middleware for Context Initialization</h3><p>Use middleware to initialize ALS for each request.</p><pre>@Injectable()<br>export class RequestContextMiddleware implements NestMiddleware {<br>  constructor(<br>    @Inject(&#39;REQUEST_CONTEXT_STORAGE&#39;) private readonly requestContextStorage: AsyncLocalStorage&lt;RequestContext&gt;,<br>  ) {}<br><br>  use(req: FastifyRequest, res: Response, next: Function) {<br>    const contextHeaders: Record&lt;string, string&gt; = {};<br><br>    if (req.headers[&#39;authorization&#39;]) {<br>      contextHeaders[&#39;Authorization&#39;] = req.headers[&#39;authorization&#39;];<br>    }<br>    contextHeaders[&#39;User-Agent&#39;] = req.headers[&#39;user-agent&#39;] || &#39;&#39;;<br><br>    const requestContext: RequestContext = { headers: contextHeaders };<br>    this.requestContextStorage.run(requestContext, () =&gt; next());<br>  }<br>}</pre><h3>Step 3: Access Context in Services</h3><p>Retrieve context data in services directly using getStore().</p><pre>@Injectable()<br>export class AuthService {<br>  constructor(<br>    private readonly externalAuthService: ExternalAuthService,<br>    @Inject(&#39;REQUEST_CONTEXT_STORAGE&#39;) private requestContextStorage: AsyncLocalStorage&lt;RequestContext&gt;,<br>  ) {}<br><br>  async authenticate(email: string, password: string) {<br>    const headers = this.requestContextStorage.getStore()?.headers || {};<br>    return this.externalAuthService.sendLoginRequest(email, password, headers);<br>  }<br>}</pre><h3>Optimized Approach: Interceptor for Axios Headers</h3><p>To further simplify, configure Axios to automatically include ALS headers in requests.</p><h3>Refactored Module</h3><pre>@Module({<br>  providers: [<br>    {<br>      provide: &#39;HTTP_CLIENT&#39;,<br>      inject: [ConfigService, &#39;REQUEST_CONTEXT_STORAGE&#39;],<br>      useFactory: (configService: ConfigService, asyncLocalStorage: AsyncLocalStorage&lt;RequestContext&gt;) =&gt; {<br>        const axiosInstance = axios.create({ baseURL: configService.get(&#39;API_BASE_URL&#39;) });<br><br>        axiosInstance.interceptors.request.use((config) =&gt; {<br>          const storedHeaders = asyncLocalStorage.getStore()?.headers;<br>          if (storedHeaders) {<br>            config.headers = { ...config.headers, ...storedHeaders };<br>          }<br>          return config;<br>        });<br><br>        return axiosInstance;<br>      },<br>    },<br>  ],<br>  exports: [&#39;HTTP_CLIENT&#39;],<br>})<br>export class HttpClientModule {}</pre><h3>The Benefits of Using ALS in NestJS</h3><ol><li><strong>Simplified Code</strong>: No need to manually pass context data through layers.</li><li><strong>Encapsulation</strong>: Context data is accessible only within the request scope.</li><li><strong>Improved Maintainability</strong>: Centralized data handling reduces redundancy and complexity.</li></ol><h3>Limitations of ALS</h3><p>Despite its benefits, ALS introduces some overhead:</p><ul><li><strong>Performance Impact</strong>: Tracking async operations with async_hooks can slow down high-throughput applications.</li><li><strong>Debugging Complexity</strong>: Implicit context management can make debugging harder in complex applications.</li></ul><h3>Conclusion</h3><p><strong>Async Local Storage</strong> transforms how request-specific data is managed in NestJS applications. By decoupling services and centralizing context handling, ALS significantly simplifies code, improves maintainability, and enhances scalability. While it comes with some trade-offs, the benefits often outweigh the drawbacks, especially in applications that need clean, modular architecture.</p><p>For more information on Async Local Storage in NestJS, visit the <a href="https://docs.nestjs.com/recipes/async-local-storage">official NestJS documentation</a>.</p><p>You can also reach this post on my <a href="https://medium.com/@joosepwong">medium.com</a> where I share my solutions to the problems I encountered during my software engineer career.</p><p>If you have additional questions, feel free to contact me on <a href="https://www.linkedin.com/in/joosepwong/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=062c164f021b" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/stop-struggling-with-request-data-in-nestjs-use-async-local-storage-062c164f021b">Stop Struggling with Request Data in NestJS: Use Async Local Storage</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Complex Role-Based Access Control in NestJS with RBAC and CASL Prisma]]></title>
            <link>https://blog.devgenius.io/exploring-complex-role-based-access-control-in-nestjs-with-rbac-casl-and-prisma-9471d5b36636?source=rss-57fbdb805c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9471d5b36636</guid>
            <category><![CDATA[rbac]]></category>
            <category><![CDATA[prisma]]></category>
            <category><![CDATA[casl]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Joosep Wong]]></dc:creator>
            <pubDate>Sat, 13 Apr 2024 17:52:00 GMT</pubDate>
            <atom:updated>2024-04-15T16:30:17.282Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sv0CoSazaMR2YScou1EByQ.jpeg" /></figure><p>Implementing user groups, roles, and permissions in a multi-tenant environment is a bit like being the traffic controller at the world’s busiest intersection — except everyone’s driving their own organizational vehicle. Each organization comes with a caravan of users, groups, and roles, adding layers to the traffic jam that is access control. To navigate this bustling highway of permissions, the savvy tech whiz merges the precision of Attribute-Based Access Control (ABAC) with the discipline of Role-Based Access Control (RBAC). It’s not just about directing traffic.</p><p><strong>How do you implement the complex RBAC?</strong></p><p>Let’s kick things off with a brief yet spirited introduction to the world of authorization: Think of authorization as the bouncer at the club of your software system — deciding who gets in and what moves they can bust on the dance floor. Here’s a fun breakdown of the tools at our disposal for managing this electronic velvet rope:</p><h4>RBAC (Role-Based Access Control):</h4><p>Imagine RBAC like a VIP list at a nightclub. We designate roles such as “System Admin” or “Editor” and assign specific permissions to each. It’s straightforward and practical, like using a clipboard to manage your guest list. However, the more roles you create, the more likely it is for someone to sneak past security — every new role could potentially open a security loophole. Imagine trying to organize a party where everyone insists on being a DJ!</p><h4>ABAC (Attribute-Based Access Control):</h4><p>Think of ABAC as having a smart door that scans guests and adjusts permissions on the fly based on who they are, the time of day, or even their mood. It’s flexible, dynamic, and sounds like something out of a sci-fi novel. With ABAC, permissions aren’t static. For instance, a manager might only peek at profiles within their department, while a regular user can’t access project details that are above their clearance level. This approach is perfect for complex environments like cloud platforms, where it’s crucial to manage a diverse range of user actions and conditions effectively.</p><h4>Policy-Based Access Control (PBAC):</h4><p>PBAC is an extension of ABAC that emphasizes using comprehensive policies or rules. It’s like having a rule book that’s constantly updated based on what’s happening at the party. Each rule defines whether you can hit the dance floor or if you’re stuck listening to the music from outside.</p><h4>Claim-Based Access Control (CBAC):</h4><p>CBAC operates on claims about a user, similar to name-dropping at the entrance of a club. These claims could be anything from “I’m a friend of the DJ” to “I’m the event sponsor,” adjusting access permissions based on these assertions. It’s a way to handle access with flair, assuming you know the right things to say.</p><p>While RBAC might be the go-to for simpler systems, its lack of flexibility can be a stumbling block in more dynamic settings, hence ABAC’s rise in scenarios demanding greater scalability. However, don’t forget that ABAC can be more complex and expensive to implement. Just as in any good toolbox, there’s no one-size-fits-all solution; it’s all about using the right tool for the job at hand. So, whether you’re sticking to the classics with RBAC or going futuristic with ABAC, make sure it’s the best fit for your party — er, project!</p><p>In the implementation process, I discovered that CASL offers an approach that suits my taste, especially when integrated with Prisma ORM, creating an unprecedented experience. In the market, I rarely find mentions of the new CASL Prisma library usage, so I want to share my development.</p><h4>What’s CASL?</h4><p><a href="https://casl.js.org/">CASL</a> (pronounced /ˈkæsəl/, like <strong>castle</strong>) is an isomorphic authorization JavaScript library which restricts what resources a given client is allowed to access. It’s designed to be incrementally adoptable and can easily scale between a simple claim based and fully featured subject and attribute based authorization. It makes it easy to manage and share permissions across UI components, API services, and database queries.</p><h4>Why Integrate CASL with Prisma?</h4><p><a href="https://www.prisma.io/orm">Prisma</a> is a powerful ORM for Node.js and TypeScript, known for its ease of use and focus on type safety. By integrating CASL with Prisma, developers can:</p><ol><li>Define permissions in a language-agnostic way: Permissions are based on what users can do with different models, not on specific SQL queries.</li><li>Secure data access at the ORM layer: This integration ensures that all database queries respect the permissions defined via CASL, adding an extra layer of security.</li><li>Simplify permission management: Instead of scattering permission logic across various layers of your application, CASL allows you to centralize permission rules using a declarative approach.</li></ol><p>If you have no experience with integrating Prisma into NestJS, please start by reading <a href="https://docs.nestjs.com/recipes/prisma">this official doc</a>. This article does not intend to approach from a beginner’s perspective, which would add considerable length. Instead, I will focus on describing the core aspects.</p><h3>Installation</h3><p>In your Nest project, you need to install the CASL:</p><pre>npm install @casl/prisma @casl/ability</pre><h3>Integrating CASL</h3><p>We have to define our CASL ability (permission rules). Create a factory for this purpose. for example, we can create src/casl/casl-ability.factory.ts</p><pre>import { User, Post, Prisma } from &#39;@prisma/client&#39;;<br>import { PureAbility, AbilityBuilder, subject } from &#39;@casl/ability&#39;;<br>import { createPrismaAbility, PrismaQuery, Subjects } from &#39;@casl/prisma&#39;;<br><br>//To support rule definition for all, we just need to explicitly do it:<br>export type AppSubjects = &#39;all&#39; | Subjects&lt;{<br>    User: User,<br>    Post: Post,<br>}&gt;;<br><br>export type AppAbility = PureAbility&lt;[string, AppSubjects], PrismaQuery&gt;;<br><br>@Injectable()<br>export class CaslAbilityFactory {<br>  createForUser(user: User) {<br>    const { can, cannot, build } = new AbilityBuilder&lt;AppAbility&gt;(PrismaAbility as AbilityClass&lt;AppAbility&gt;);<br><br>    //These setting can be loaded from the Database in the real world.<br>    if (user.roles.includes(&#39;admin&#39;)) {<br>      can(&#39;manage&#39;, &#39;all&#39;, &#39;all&#39;); // admin can do anything<br>    } else {<br>      can(&#39;read&#39;, &#39;Post&#39;, &#39;all&#39;); // regular users can read posts<br>      can(&#39;update&#39;, &#39;Post&#39;, &#39;all&#39;, { owner: user.id }); // users can update their own posts<br>    }<br><br>    return build();<br>  }<br>}</pre><p>This factory function checks the user’s roles and defines what they can and cannot do with the Post model. The ability to read is granted to all users, but update operations are restricted to posts owned by the user.</p><p>For the CASL rule definition, you can read this doc: <a href="https://casl.js.org/v6/en/package/casl-prisma">https://casl.js.org/v6/en/package/casl-prisma</a></p><h3>Using CASL Abilities in Services</h3><p>Integrate CASL abilities into your services to enforce these permissions. For example, in a post service:</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { PrismaService } from &#39;./prisma.service&#39;;<br>import { User } from &quot;@prisma/client&quot;;<br>import { accessibleBy } from &quot;@casl/prisma&quot;;<br>import { AppAbility, CaslAbilityFactory } from &#39;../casl/casl-ability.factory&#39;;<br><br>@Injectable()<br>export class PostsService {<br>  constructor(private prisma: PrismaService, private caslAbilityFactory: CaslAbilityFactory) {}<br><br>  async findPosts(loggedUser: User):Promise&lt;Post[]|null&gt; {<br>    const ability = this.caslAbilityFactory.createForUser(loggedUser);<br>    return await prisma.post.findMany({<br>      where: {<br>        AND: [<br>          accessibleBy(ability).Post,<br>          { /* business related conditions */ }<br>        ]<br>       }<br>    })<br>  }<br>}</pre><p>In the findPosts method, the ability is created for the user, and this ability is used to filter posts directly in the database query, ensuring that users only retrieve posts they are allowed to read.</p><p>This package allows to define CASL permissions on Prisma models using Prisma <strong><em>WhereInput</em></strong>. And that brings a lot of power in terms of permission management in SQL world: We can use Prisma Query to define permissions, no need to learn MongoDB query language anymore. Additionally, we can ask our SQL database questions like: “Which records can be read?” or “Which records can be updated?”.</p><h3><strong>Conclusion</strong></h3><p>By integrating CASL with Prisma in a NestJS application, you significantly enhance your application’s security posture. This integration not only streamlines permission management but also ensures that these permissions are deeply integrated into your application’s data access layer, making your system robust against unauthorized access.</p><p>This powerful combination of CASL for authorization and Prisma for data management enables you to build secure, scalable, and maintainable applications with confidence.</p><p>Of course, you can also combine CASL to establish your decorators and guards, which is very easy. However, for very complex ABAC, we usually need to handle it at the service layer. In my projects, I typically also integrate a standard RBAC guard for the first layer of interception, followed by data-level interception. Adding CASL’s <a href="https://casl.js.org/v6/en/package/casl-vue">Vue</a> or <a href="https://casl.js.org/v6/en/package/casl-react">React</a> components will make your fortress as secure as a wall of copper and iron.</p><h3>About Me</h3><p>I’m Joosep Wong, currently based in Europe. You can also find this post on my <a href="https://medium.com/@joosepwong">Medium.com</a> profile, where I share solutions to various challenges I’ve encountered throughout my career as a software engineer.</p><p>If you’ve enjoyed reading my content and would like to support me, I kindly ask for a small donation of a cup of coffee. Your generosity would be greatly appreciated and will help me to continue creating meaningful and informative content. (<a href="https://ko-fi.com/joosep">donate a cup of coffee</a>).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9471d5b36636" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/exploring-complex-role-based-access-control-in-nestjs-with-rbac-casl-and-prisma-9471d5b36636">Exploring Complex Role-Based Access Control in NestJS with RBAC and CASL Prisma</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Queue System in NestJS: Unleashing the Power of PostgreSQL with pg-boss, Your Bull…]]></title>
            <link>https://blog.devgenius.io/implementing-a-robust-queue-system-in-nestjs-with-postgresql-an-alternative-to-bull-f55aad366912?source=rss-57fbdb805c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f55aad366912</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[bullying]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[queue]]></category>
            <dc:creator><![CDATA[Joosep Wong]]></dc:creator>
            <pubDate>Sun, 04 Feb 2024 08:07:38 GMT</pubDate>
            <atom:updated>2024-03-22T12:03:43.295Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build Queue System in NestJS: Unleashing the Power of PostgreSQL with pg-boss, Your Bull Alternative</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IaxE16cc9Od0i7omD9eTbw.jpeg" /><figcaption>BULL VS PG-BOSS</figcaption></figure><p>In my tenure as the lead developer for a Shopify application tasked with handling tens of millions of orders daily, ensuring an error-free process became paramount. This challenge underscored the need for a robust queue system, one that comes equipped with reliable retry mechanisms and traceability features to handle the massive order volume without hiccups. The importance of visual queue monitoring became glaringly obvious in this high-stakes environment.</p><p>While initially considering Bull, a Redis-based queue system, for its proven capabilities, we were steered in a different direction due to our company’s extensive use of PostgreSQL. This deep integration with PostgreSQL, which even encompasses our monitoring systems, led our DevOps team to suggest we leverage PostgreSQL for queue management.</p><p>Motivated by this recommendation, I embarked on a quest to find a robust PostgreSQL-based solution for our queuing requirements. This search culminated in the discovery of an excellent solution: <a href="https://github.com/timgit/pg-boss">PG-BOSS</a>, which stood out as a perfect fit for our needs.</p><p>This journey, possibly the first of its kind mentioned ‘PG-BOSS’ on Medium, showcases our innovative approach to ensuring seamless tasks processing at scale.</p><h3>Understanding the Need for Queue Systems</h3><p>Queues are a powerful design pattern that help you deal with common application scaling and performance challenges. Some examples of problems that Queues can help you solve are:</p><ul><li>Smooth out processing peaks. For example, if users can initiate resource-intensive tasks at arbitrary times, you can add these tasks to a queue instead of performing them synchronously. Then you can have worker processes pull tasks from the queue in a controlled manner. You can easily add new Queue consumers to scale up the back-end task handling as the application scales up.</li><li>Break up monolithic tasks that may otherwise block the Node.js event loop. For example, if a user request requires CPU intensive work like audio transcoding, you can delegate this task to other processes, freeing up user-facing processes to remain responsive.</li><li>Provide a reliable communication channel across various services. For example, you can queue tasks (jobs) in one process or service, and consume them in another. You can be notified (by listening for status events) upon completion, error or other state changes in the job life cycle from any process or service. When Queue producers or consumers fail, their state is preserved and task handling can restart automatically when nodes are restarted.</li></ul><h3>Bull vs. PG-BOSS: A Comparison</h3><p>Bull, a Redis-backed queue system, is renowned for its performance, reliability, and extensive feature set. However, it necessitates a Redis instance, adding complexity and cost in certain deployments. On the other hand, pg-boss offers a powerful alternative, utilizing PostgreSQL&#39;s robust features to manage queues efficiently. This approach can simplify architecture for applications already using PostgreSQL, eliminating the need for an additional Redis setup.</p><h3>Key Features of PG-BOSS:</h3><ul><li>Transaction Support: Leverages PostgreSQL’s transaction capabilities for reliable job processing.</li><li>Scheduled Jobs: Native support for scheduling jobs without external dependencies.</li><li>Scalability: Utilizes PostgreSQL’s inherent scalability to manage workload efficiently.</li></ul><h3>Setting Up PG-BOSS with NestJS: A Step-by-Step Guide</h3><h3>Prerequisites</h3><ul><li>A NestJS project setup</li><li>PostgreSQL database</li></ul><h3>Step 1: Installing PG-BOSS</h3><p>Begin by adding pg-boss to your project:</p><pre>npm install pg-boss</pre><h3>Step 2: Configuration</h3><p>Configure pg-boss by creating a module that encapsulates its setup. This involves specifying your PostgreSQL connection details and initializing the pg-boss instance.</p><pre>import * as PgBoss from &#39;pg-boss&#39;;<br><br>const boss = new PgBoss(&#39;postgres://your_connection_string&#39;);<br>await boss.start();</pre><h3>Step 3: Creating and Processing Jobs</h3><p>Define jobs and their processing logic. With pg-boss, creating a job is straightforward, and processing can be tailored to fit various scenarios, from simple background tasks to complex workflows.</p><pre>const jobId = await boss.publish(&#39;send-email&#39;, { email: &#39;example@example.com&#39; });<br><br>boss.subscribe(&#39;send-email&#39;, async job =&gt; {<br>  // Logic to send an email<br>  console.log(`Sending email to ${job.data.email}`);<br>});</pre><h3>Step 4: Integrating with NestJS Services</h3><p>Integrate pg-boss within your NestJS services to leverage its capabilities across your application. This can involve encapsulating job publishing within service methods or setting up dedicated modules for job processing.</p><p>I prefer to make it into a Module to enable its usage across different modules. For specific guidance, please consult the <a href="https://docs.nestjs.com/modules">NestJS section on modules</a>. Meanwhile, in the market, there are developers who have successfully integrated pg-boss with decorator-based development. For instance, take a look at the following example: <a href="https://github.com/apricote/nest-pg-boss">nest-pg-boss by apricote on GitHub</a>. This repository showcases how to leverage pg-boss within the NestJS framework, illustrating a practical implementation of decorator-based queue management using PostgreSQL as the backend storage.</p><h3>Advantages and Use Cases</h3><p>pg-boss shines in scenarios where PostgreSQL is already a part of the technology stack, offering a seamless integration point for queue management. Its transaction support and scheduled jobs feature make it an excellent choice for financial operations, data processing tasks, and more.</p><h3><strong>One more thing…</strong></h3><p>In the ever-evolving landscape of database management, having the right tools at your disposal can make all the difference. For PostgreSQL users seeking to optimize their database modeling processes, look no further than <a href="https://www.datensen.com/">Luna Modeler</a>. Luna Modeler is a comprehensive database modeling tool designed specifically for PostgreSQL, offering a seamless and intuitive experience for developers and database administrators alike.</p><p>One of the key challenges in database management is designing and maintaining a well-structured database schema. Luna Modeler simplifies this process with its intuitive interface and powerful modeling capabilities. With Luna Modeler, you can easily create and visualize your database schema, making it easier to understand and manage your data architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EfOEUJsrpgLzkj8kwaL2dw.jpeg" /></figure><p>Luna Modeler provides a visual design interface that allows you to create database schemas using drag-and-drop functionality. This intuitive approach makes it easy to design complex database structures, saving you time and effort in the modeling process. Whether you’re designing a new database from scratch or making changes to an existing schema, Luna Modeler’s visual interface makes the process smooth and efficient.</p><h3>Conclusion</h3><p>While Bull remains a strong contender in the arena of queue systems, pg-boss presents a viable, efficient alternative for applications built on or integrated with PostgreSQL. By leveraging existing database infrastructure, pg-boss simplifies deployment and reduces overhead, making it an attractive option for a wide range of projects.</p><h3>References</h3><ul><li><a href="https://github.com/timgit/pg-boss">pg-boss GitHub Repository</a></li><li><a href="https://nestjs.com/">NestJS Documentation</a></li><li><a href="https://docs.nestjs.com/techniques/queues">Bull Queue System</a></li></ul><p>This guide has walked you through setting up a robust queue system in NestJS using PostgreSQL and pg-boss, highlighting its potential as a valuable tool for asynchronous task management. Whether you&#39;re looking to streamline operations, enhance scalability, or consolidate your technology stack, pg-boss offers a compelling solution worth considering.</p><h3>About Me</h3><p>My name is Joosep Wong, you can also reach this post on my <a href="https://medium.com/@joosepwong">medium.com</a> where I share my solutions to the problems I encountered during my software engineer career.</p><p>If you’ve enjoyed reading my content and would like to support me, I kindly ask for a small donation of a cup of coffee. Your generosity would be greatly appreciated and will help me to continue creating meaningful and informative content. (<a href="https://ko-fi.com/joosep">donate a cup of coffee</a>).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f55aad366912" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/implementing-a-robust-queue-system-in-nestjs-with-postgresql-an-alternative-to-bull-f55aad366912">Build Queue System in NestJS: Unleashing the Power of PostgreSQL with pg-boss, Your Bull…</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swagger Got a Makeover: How Redoc Became the Star of My NestJS API Docs]]></title>
            <link>https://blog.devgenius.io/swagger-got-a-makeover-how-redoc-became-the-star-of-my-nestjs-api-docs-92c9438c5b0d?source=rss-57fbdb805c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/92c9438c5b0d</guid>
            <category><![CDATA[redocly]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[redoc]]></category>
            <category><![CDATA[swagger]]></category>
            <dc:creator><![CDATA[Joosep Wong]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 12:29:04 GMT</pubDate>
            <atom:updated>2024-01-22T13:20:09.949Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lREvwFv75AXY9GXryIsJyQ.jpeg" /></figure><p>Ever had that feeling when you’re tired of the same old Swagger UI and want to spice things up in your NestJS API documentation? Well, join the club! In this hilarious journey, I’ll share how I ditched the swagger and welcomed the swagger-licious Redoc to the stage. Get ready for a rollercoaster ride through APIs, documentation, and a touch of swagger makeover drama!</p><h3>The Swagger Rut</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2qWNDw5uyB0s2QdTmz1GLg.png" /><figcaption>Swagger UI</figcaption></figure><p>Swagger UI, the reliable yet somewhat bland companion of many developers. It’s been there, faithfully documenting APIs, but let’s admit it — it’s not winning any beauty contests. The time had come for a change! You can read the <a href="https://docs.nestjs.com/openapi/introduction">Nestjs official documentation for the integration with OpenAPI</a> here.</p><p><strong>Enter Redoc — The Swagger Rockstar</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GcfxrwafmpNDSmVXhC4FQw.jpeg" /><figcaption>ReDoc Style</figcaption></figure><p><a href="https://github.com/Redocly/redoc">Redoc</a> is an open-source tool that generates API documentation from OpenAPI specifications. It’s one of the most powerful free docs tools in the industry, producing clean, customizable documentation with an attractive three-panel design. With support for Markdown, it allows you to write and style descriptions with ease.</p><p>Cue Redoc, swagger’s cooler, more stylish cousin! With its sleek design and user-friendly interface, Redoc stole the spotlight. It was love at first sight. My API docs suddenly felt like a red carpet event!</p><p>Let’s embark on an adventure to unleash the magic of ReDoc! Now, here’s the scoop — most npm packages out there are stuck in a time warp, unable to groove with the cool kids in Nest V10. Only this package (<a href="https://www.npmjs.com/package/@jozefazz/nestjs-redoc">@jozefazz/nestjs-redoc</a>) can work well with Nest.js 10.0.0.</p><p>Follow my lead, and you’ll be blessed with the most stunning API Docs in town. Say goodbye to outdated dependencies and hello to a swagger-ific transformation! 🚀✨</p><h3>Installation</h3><p>To begin using it, we first install the swagger dependency.</p><pre>npm install --save @nestjs/swagger</pre><p>And you need to install this magic package.</p><pre>npm install --save @jozefazz/nestjs-redoc</pre><h3>Bootstrap</h3><p>Once the installation process is complete, add a file setup.redoc.ts into the src folder.</p><pre>import type { INestApplication } from &#39;@nestjs/common&#39;;<br>import { DocumentBuilder, SwaggerModule } from &#39;@nestjs/swagger&#39;;<br>import { RedocModule, RedocOptions } from &#39;@jozefazz/nestjs-redoc&#39;;<br><br>export async function setupRedoc(app: INestApplication) {<br>  const documentBuilder = new DocumentBuilder()<br>    .setTitle(&#39;Joosep API Documentation&#39;)<br>    .setVersion(&#39;1.0&#39;)<br>    .setDescription(&#39;medium.com/@joosepwong&#39;,)<br>    .addBearerAuth(<br>      {<br>        description: `Please enter token in following format: Bearer &lt;JWT&gt;`,<br>        name: &#39;Authorization&#39;,<br>        bearerFormat: &#39;Bearer&#39;,<br>        scheme: &#39;Bearer&#39;,<br>        type: &#39;http&#39;,<br>        in: &#39;Header&#39;,<br>      },<br>      &#39;access-token&#39;,<br>    );<br><br>  const document = SwaggerModule.createDocument(app, documentBuilder.build());<br>  const redocOptions: RedocOptions = {<br>    title: &#39;Joosep API Documentation&#39;,<br>    logo: {<br>      url: &#39;https://joosep.org/logo.svg&#39;,<br>      backgroundColor: &#39;#d0e8c5&#39;,<br>      altText: &#39;LOGO&#39;,<br>    },<br>    theme: {<br>      typography: {<br>        fontSize: &#39;16px&#39;,<br>        fontWeightBold: &#39;900&#39;,<br>      },<br>      sidebar: {<br>        backgroundColor: &#39;#d0e8c5&#39;,<br>      },<br>      rightPanel: {<br>        backgroundColor: &#39;#01312b&#39;,<br>      },<br>    },<br>    sortPropsAlphabetically: true,<br>    hideDownloadButton: false,<br>    hideHostname: false,<br>    noAutoAuth: true,<br>    pathInMiddlePanel: true,<br>    auth: {<br>      enabled: true,<br>      user: &#39;admin&#39;,<br>      password: `TfsR132eda@`,<br>    },<br>    tagGroups: [<br>      {<br>        name: &#39;Core resources&#39;,<br>        tags: [&#39;authentication&#39;, &#39;user&#39;],<br>      },<br>    ],<br>  };<br>  await RedocModule.setup(&#39;docs&#39;, app, document, redocOptions);<br>  console.info(<br>    &#39;Redoc Documentation: http://localhost:300/docs&#39;,<br>  );<br>}</pre><p>OK, now let’s rock, initialize Redoc in main.ts with the setupRedoc function.</p><pre>import { NestFactory, Reflector } from &#39;@nestjs/core&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br>import { setupRedoc } from &#39;./setup.redoc&#39;;<br><br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br>  await setupRedoc(app);<br>  await app.listen(3000);<br>}<br>bootstrap();</pre><p>Now you can visit the fancy API docs from <a href="https://localhost:3000/docs">https://localhost:3000/docs</a></p><p><strong>Conclusion</strong></p><p>In the realm of API documentation, Swagger has long been a stalwart, providing reliable service to developers. However, the time has come for a makeover, and ReDoc steps into the spotlight as the new star of the show.</p><p>As we bid adieu to the conventional Swagger UI, ReDoc emerges as the go-to choice for those seeking a more sophisticated, customizable, and user-centric API documentation solution. The future of Swagger-ing has a new name, and it’s ReDoc. 🚀✨ You can get the full set of cosmetics for the customization part from the ReDoc documentation: <a href="https://redocly.com/docs/redoc/">https://redocly.com/docs/redoc/</a></p><p>You can also reach this post on my <a href="https://medium.com/@joosepwong">medium.com</a> where I share my solutions to the problems I encountered during my software engineer career.</p><p>If you’ve enjoyed reading my content and would like to support me, I kindly ask for a small donation of a cup of coffee. Your generosity would be greatly appreciated and will help me to continue creating meaningful and informative content. (<a href="https://ko-fi.com/joosep">donate a cup of coffee</a>).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92c9438c5b0d" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/swagger-got-a-makeover-how-redoc-became-the-star-of-my-nestjs-api-docs-92c9438c5b0d">Swagger Got a Makeover: How Redoc Became the Star of My NestJS API Docs</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>