<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Fri, 04 Dec 2026 00:31:38 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Deploy Genkit Apps on Cloudflare Workers ]]>
                </title>
                <description>
                    <![CDATA[ Genkit is an open-source framework built by Google you can use to build AI-powered applications. The framework gives you structured output and tool calling, RAG, streaming, and generative UI. It also  ]]>
                </description>
                <link>https://www.freecodecamp.org/news/deploy-genkit-apps-on-cloudflare-workers/</link>
                <guid isPermaLink="false">6b119ff79e7a3c1966d84f64</guid>
                
                    <category>
                        <![CDATA[ firebase genkit ]]>
                    </category>
                
                    <category>
                        <![CDATA[ cloudflare ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Orim Dominic Adah ]]>
                </dc:creator>
                <pubDate>Thu, 03 Dec 2026 16:59:35 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/21a033d6-82eb-4db5-9a72-29429eee09fd.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Genkit is an open-source framework built by Google you can use to build AI-powered applications. The framework gives you structured output and tool calling, RAG, streaming, and generative UI. It also gives you tools around your AI application for tracing and evaluation, plus a user interface to test and observe the application.</p>
<p>Genkit has support for many model providers through an <code>ai.generate()</code> API, which means you can swap Gemini for OpenAI or Claude without rewriting your application.</p>
<p>Cloudflare Workers is a serverless platform that runs your code close to your users. Workers run your JavaScript app in V8 isolates. These are lightweight sandboxes that start in milliseconds, so you don't have any cold start problems like you would've had in cloud serverless environments.</p>
<p>In this tutorial, you'll build an AI application called Explainer. You'll send it a software engineering topic, and it'll explains the topic to you as if you were a junior engineer.</p>
<p>Genkit applications break on Workers out of the box, so in this tutorial you'll understand why and also learn how to fix it.</p>
<h3 id="heading-what-well-cover">What We'll Cover:</h3>
<ul>
<li><a href="#heading-prerequisites">Prerequisites</a></li>
<li><a href="#heading-why-genkit-breaks-on-cloudflare-workers">Why Genkit Breaks on Cloudflare Workers</a><ul>
<li><a href="#heading-restrictions-on-eval-and-new-function">Restrictions onevalandnew Function()</a></li>
<li><a href="#heading-the-error-from-genkits-reflection-server-express-module">The Error from Genkit's Reflection Server Express Module</a></li>
</ul>
</li>
<li><a href="#heading-how-to-set-up-the-starter-repository">How to Set Up the Starter Repository</a></li>
<li><a href="#heading-how-to-build-the-explainer-flow">How to Build the Explainer Flow</a><ul>
<li><a href="#heading-swap-in-a-different-provider">Swap in a Different Provider</a></li>
<li><a href="#heading-configure-the-genkit-runtime">Configure the Genkit Runtime</a></li>
<li><a href="#heading-stop-the-express-crash">Stop the Express Crash</a></li>
<li><a href="#heading-add-the-http-endpoint">Add the HTTP Endpoint</a></li>
</ul>
</li>
<li><a href="#heading-how-to-test-the-worker-locally">How to Test the Worker Locally</a></li>
<li><a href="#heading-how-to-run-the-app-with-the-genkit-dev-ui">How to Run the App with the Genkit Dev UI</a></li>
<li><a href="#heading-how-to-deploy-to-cloudflare-workers">How to Deploy to Cloudflare Workers</a></li>
<li><a href="#heading-how-to-set-up-groq-as-a-fallback-provider">How to Set Up Groq as a Fallback Provider</a></li>
<li><a href="#heading-troubleshooting-common-errors">Troubleshooting Common Errors</a></li>
<li><a href="#heading-streaming-responses-with-genkit-on-cloudflare-workers">Streaming Responses with Genkit on Cloudflare Workers</a></li>
<li><a href="#heading-limitations-of-genkit-on-cloudflare-workers">Limitations of Genkit on Cloudflare Workers</a></li>
<li><a href="#heading-conclusion">Conclusion</a></li>
<li><a href="#heading-references">References</a></li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To follow along with this tutorial, you need:</p>
<ul>
<li>Working knowledge of TypeScript</li>
<li>Basic knowledge of Genkit (flows and <code>ai.generate()</code>)</li>
<li>A Cloudflare account</li>
<li>A Gemini API key (a Groq key is optional, for the fallback section)</li>
<li><code>pnpm</code> installed</li>
<li><code>curl</code> or Postman for testing</li>
</ul>
<h2 id="heading-why-genkit-breaks-on-cloudflare-workers">Why Genkit Breaks on Cloudflare Workers</h2>
<p>JavaScript doesn't run by itself. Think of JavaScript as a car. Can it move? Yes, but it needs a solid surface on which to move. Similarly, JavaScript needs an environment to run in, and that environment is a program that provides the APIs (or support) that your JavaScript code executes.</p>
<p>The browser is an example of a runtime environment (with <code>fetch</code> and the DOM APIs), while Node.js is another (with <code>fs</code> and <code>net</code> APIs). Bun and Deno are still others.</p>
<p>Cloudflare Workers uses its own runtime (workerd) built on V8, the same engine that powers Chrome tabs. It gives you <code>fetch</code>, <code>crypto</code>, and timers, but it's not Node.js. Building a JavaScript application on Workers that assumes a full Node.js environment can fail.</p>
<p>Genkit relies on two capabilities that the Workers runtime deliberately restricts.</p>
<h3 id="heading-restrictions-on-eval-and-new-function">Restrictions on <code>eval</code> and <code>new Function()</code></h3>
<p>Workers forbids generating code from strings. Both <code>eval()</code> and <code>new Function()</code> throw this error in workerd, Cloudflare's runtime:</p>
<pre><code class="language-text">EvalError: Code generation from strings disallowed for this context
</code></pre>
<p>Genkit uses <code>new Function()</code> in two places:</p>
<ul>
<li><strong>When its schema validator compiles validation code from JSON schemas</strong>: You turn that off with <code>jsonSchemaMode: "interpret"</code>, which makes Genkit validate schema by only going through it instead of compiling it. This mode needs the <code>@cfworker/json-schema</code> package.</li>
<li><strong>When it handles prompts</strong>: If you pass a <strong>string</strong> as the <code>system</code> or <code>prompt</code> value to <code>ai.generate()</code>, Genkit routes it through its dotprompt library. Dotprompt compiles Handlebars templates with <code>new Function()</code>. On Workers, that throws even before your model is ever called. The fix is to pass your prompt explicitly, as an array of message parts instead:</li>
</ul>
<pre><code class="language-ts">// Crashes on Workers: string goes through dotprompt → new Function()
await ai.generate({ system: 'You are a helpful teacher.' });

// Works: parts bypass dotprompt's template compiler
await ai.generate({ system: [{ text: 'You are a helpful teacher.' }] });
</code></pre>
<p>You'll use the parts form everywhere in this tutorial.</p>
<h3 id="heading-the-error-from-genkits-reflection-server-express-module">The Error from Genkit's Reflection Server Express Module</h3>
<img src="https://cdn.hashnode.com/uploads/covers/66e28b713f978a0e2cd2b763/397ec06d-5e35-439d-88d1-c003eee82176.png" alt="Error path for Genkit reflection server on Cloudflare Workers" style="display: block;" width="600" height="400" loading="lazy">

<p>When your Worker imports the <code>genkit</code> module, the module executes <code>setGenkitRuntimeConfig()</code> to set up Genkit's global runtime behaviour. The import chain pulls in Genkit's reflection server code, and that file does <code>require("express")</code> at module load.</p>
<p>Express pulls in <code>body-parser</code>, then <code>raw-body</code>, then <code>iconv-lite</code>, which calls <code>require('stream')</code> in a way workerd (Cloudflare's server runtime) rejects:</p>
<pre><code class="language-text">Uncaught TypeError: require_streams(...) is not a function
  at iconv-lite/lib/index.js ← raw-body ← body-parser ← express
</code></pre>
<p>This shuts down your worker before a request arrives. <a href="https://genkit.dev/docs/js/deployment/any-platform/#environments-that-restrict-eval">Genkit's documented fix</a> for restricted environments is <code>sandboxedRuntime: true</code>, but that flag only prevents the reflection server (Genkit's internal server that exposes your app for the Dev UI) from <em>starting</em>. It doesn't stop express from <em>loading</em>, and a crash then happens at load time.</p>
<p>The solution is to tell wrangler to replace <code>express</code> with a tiny stub that never runs. This way, when any of Express's HTTP method's are invoked during the load, the Express stub methods are invoked instead.</p>
<p>In general, there are three fixes to be made:</p>
<ul>
<li>interpret-mode schemas</li>
<li>message-part prompts</li>
<li>an Express stub</li>
</ul>
<p>Everything else in this tutorial is regular application code.</p>
<h2 id="heading-how-to-set-up-the-starter-repository">How to Set Up the Starter Repository</h2>
<p>Clone the starter repository and install dependencies:</p>
<pre><code class="language-bash">git clone https://github.com/orimdominic/genkit-apps-on-cloudflare-workers
cd genkit-apps-on-cloudflare-workers
pnpm install
</code></pre>
<p>The repository is a barebones application built from Cloudflare's Workers template. It uses <a href="https://hono.dev/docs/">Hono</a>, a lightweight web framework with an Express-like router and middleware API. You declare routes like <code>app.post('/ping', ...)</code>, add middleware between the request and the handler, and then return a response.</p>
<p>Hono runs on Cloudflare Workers, Node.js, Deno, and Bun, and it uses the same code with the same API on each. This portability is key because you'll serve the identical app from the Workers runtime in production and from Node during development.</p>
<p>To test the application, start it:</p>
<pre><code class="language-bash">pnpm dev				
</code></pre>
<p>In a second terminal or in Postman, make a request to the <code>POST /ping</code> endpoint:</p>
<pre><code class="language-bash">curl -X POST http://localhost:8787/ping
</code></pre>
<p>Expected output:</p>
<pre><code class="language-text">pong
</code></pre>
<p><code>pnpm dev</code> runs <code>wrangler dev</code>, which starts a local Workers runtime on port 8787. You can stop it anytime using <code>CTRL + C</code> or <code>CMD + C</code>.</p>
<h2 id="heading-how-to-build-the-explainer-flow">How to Build the Explainer Flow</h2>
<p>Install <code>genkit</code> and <code>@genkit-ai/google-genai</code> as dependencies of the project. In a terminal, run:</p>
<pre><code class="language-bash">pnpm install genkit@latest @genkit-ai/google-genai
</code></pre>
<p>Create a <code>.dev.vars</code> file in the root directory of the project and set <code>GEMINI_API_KEY</code> to your Gemini API key:</p>
<pre><code class="language-txt">GEMINI_API_KEY=your-key-here
</code></pre>
<p>Create <code>src/flows/explainer.ts</code>:</p>
<pre><code class="language-ts">import { googleAI } from '@genkit-ai/google-genai';
import { genkit, z } from 'genkit';

const systemPrompt = `You are an excellent teacher of software engineering concepts. Explain ${topic} to me like I'm a junior software engineer using analogies that I can relate to and understand.`;

export const ai = genkit({
	plugins: [googleAI()],
	model: googleAI.model('gemini-3.5-flash'),
});

export const explainerInputSchema = z.object({ topic: z.string().min(3) });

export const explainerFlow = ai.defineFlow(
	{
		name: 'explainerFlow',
		inputSchema: explainerInputSchema,
		outputSchema: z.object({ explanation: z.string() }),
	},
	async ({ topic }) =&gt; {
		// system and prompt are passed as message parts, not strings, so
		// dotprompt never compiles them with Function() (blocked on Workers).
		const { text } = await ai.generate({
			system: [{ text: systemPrompt }],`
			prompt: [{ text: `Topic: ${topic}` }],
		});

		return { explanation: text };
	},
);
</code></pre>
<p>There are a few decisions here that you should understand:</p>
<ul>
<li>The <code>z</code> you import comes from <code>genkit</code> itself. It re-exports zod, so you don't need a separate <code>zod</code> dependency. You declare <code>explainerInputSchema</code> once and export it. The flow uses it as its input schema and the HTTP layer will use the same object for validation.</li>
<li>The <code>system</code> and <code>prompt</code> values are arrays of objects, so that dotprompt never compiles them with <code>Function()</code> which is blocked on Workers. This is the difference between a Worker that responds and a Worker that throws <code>EvalError</code>.</li>
</ul>
<h3 id="heading-swap-in-a-different-provider">Swap in a Different Provider</h3>
<p>If you don't want to use Gemini, you can swap in a different model provider. Here's how the setup differs for OpenAI and Groq:</p>
<table>
<thead>
<tr>
<th>Provider</th>
<th>Plugin</th>
<th>Model Reference</th>
<th>API key env variable</th>
</tr>
</thead>
<tbody><tr>
<td>Gemini</td>
<td><code>googleAI()</code> from <code>@genkit-ai/google-genai</code></td>
<td><code>googleAI.model("gemini-3.5-flash")</code></td>
<td><code>GEMINI_API_KEY</code></td>
</tr>
<tr>
<td>OpenAI</td>
<td><code>openAI()</code> from <code>@genkit-ai/compat-oai/openai</code></td>
<td><code>"openai/gpt-4o"</code></td>
<td><code>OPENAI_API_KEY</code></td>
</tr>
<tr>
<td>Groq</td>
<td><code>openAICompatible({ name, baseURL })</code> from <code>@genkit-ai/compat-oai</code></td>
<td><code>"groq/openai/gpt-os-12b"</code></td>
<td><code>GROQ_API_KEY</code></td>
</tr>
</tbody></table>
<p>For OpenAI:</p>
<pre><code class="language-bash">pnpm install @genkit-ai/compat-oai/openai			# install the Genkit OpenAI plugin
</code></pre>
<pre><code class="language-ts">import { openAI } from '@genkit-ai/compat-oai/openai';

export const ai = genkit({
	plugins: [openAI()],
	model: 'openai/gpt-4o',
});
</code></pre>
<p><code>openAI()</code> reads <code>OPENAI_API_KEY</code> from the environment automatically. The <a href="#how-to-set-up-groq-as-a-fallback-provider">Groq section</a> below shows how to set up Groq in full.</p>
<p>This tutorial puts environment variables in <code>.dev.vars</code> for local development and in Wrangler secrets for production.</p>
<h3 id="heading-configure-the-genkit-runtime">Configure the Genkit Runtime</h3>
<p>Create <code>src/genkit-runtime.ts</code>:</p>
<pre><code class="language-ts">import { setGenkitRuntimeConfig } from 'genkit';

// workerd forbids eval() and new Function(), which Genkit's schema validator
// and dotprompt rely on, and it cannot host the reflection server the Dev UI
// uses.
const isWorkersRuntime = 'WebSocketPair' in globalThis;

setGenkitRuntimeConfig({
	jsonSchemaMode: 'interpret',
	sandboxedRuntime: isWorkersRuntime,
});
</code></pre>
<p><code>WebSocketPair</code> only exists in the Workers runtime, so <code>src/genkit-runtime.ts</code> behaves correctly in both environments. On Workers, Genkit interprets schemas and skips the reflection server. In Node, it keeps the default behavior for the reflection server.</p>
<p>There are two things to note about <code>src/genkit-runtime.ts</code>:</p>
<ul>
<li>It must be the first import in your entry points, before <code>genkit</code> is used.</li>
<li>On startup you'll see this warning:</li>
</ul>
<pre><code class="language-text">It looks like you're trying to disable schema code generation. Please ensure that the '@cfworker/json-schema' package is installed: `npm i --save @cfworker/json-schema`
</code></pre>
<p>Install the <code>pnpm add @cfworker/json-schema</code> package and ignore the warning. Genkit prints this warning every time you use interpret mode, even when the package is already installed.</p>
<h3 id="heading-stop-the-express-crash">Stop the Express Crash</h3>
<p>Add the alias to <code>wrangler.jsonc</code>:</p>
<pre><code class="language-json">{
  "$schema": "node_modules/wrangler/config-schema.json",
  "name": "deploy-genkit-apps-on-cloudflare-workers",
  "main": "src/index.ts",
  "compatibility_date": "2026-11-13",
  "alias": {
    "express": "./src/stubs/express.js"
  }
}
</code></pre>
<p>Create the Express stub in <code>src/stubs/express.js</code>. It exists only to satisfy the import that Genkit's reflection server performs at module load:</p>
<pre><code class="language-js">function express() {
	const app = () =&gt; app;
	app.use = () =&gt; app;
	app.get = () =&gt; app;
	app.post = () =&gt; app;
	app.put = () =&gt; app;
	app.delete = () =&gt; app;
	app.listen = () =&gt; app;
	app.set = () =&gt; app;
	app.engine = () =&gt; app;
	app.locals = {};
	return app;
}

// Mirrors the express APIs referenced by genkit's reflection server.
const passthrough = () =&gt; (_req, _res, next) =&gt; next?.();

express.json = passthrough;
express.urlencoded = passthrough;
express.raw = passthrough;
express.text = passthrough;
express.static = passthrough;
express.Router = express;

export default express;
</code></pre>
<p>Why a stub is safe: On Workers, <code>sandboxedRuntime: true</code> stops the reflection server from ever starting, so Express is loaded but never called. The stub only needs to survive module load. The <code>alias</code> entry applies only to wrangler's bundle. When you run the app in Node later, Node loads the real Express module from <code>node_modules</code> and nothing is stubbed there.</p>
<h3 id="heading-add-the-http-endpoint">Add the HTTP Endpoint</h3>
<p>Update <code>src/app.ts</code>:</p>
<pre><code class="language-ts">import { Hono } from 'hono';
import { validator } from 'hono/validator';
import { explainerFlow, explainerInputSchema } from './flows/explainer';

const app = new Hono();

app.post('/ping', (c) =&gt; {
	return c.text('pong');
});

const validateTopic = validator('json', (value, c) =&gt; {
	const parsed = explainerInputSchema.safeParse(value);
	if (!parsed.success) {
		return c.json({ error: 'Send a JSON body like {"topic": "microservices"}' }, 400);
	}
	return parsed.data;
});

app.post('/explain', validateTopic, async (c) =&gt; {
	const { topic } = c.req.valid('json');
	const { explanation } = await explainerFlow({ topic });
	return c.json({ explanation });
});

export default app;
</code></pre>
<p><code>validateTopic</code> is a middleware that ensures that <code>topic</code> sent in the payload has a valid value. Inside the handler, <code>c.req.valid('json')</code> hands you an object that's already typed as <code>{ topic: string }</code>.</p>
<p>Point the Worker entry at this app. Replace the contents of <code>src/index.ts</code>:</p>
<pre><code class="language-ts">import './genkit-runtime';
import app from './app';

export default app;
</code></pre>
<p>The bare <code>import './genkit-runtime'</code> line runs the configuration before anything else touches Genkit, to set it up for Workers.</p>
<h2 id="heading-how-to-test-the-worker-locally">How to Test the Worker Locally</h2>
<p>With <code>pnpm dev</code> still running, send a request using curl or Postman.</p>
<pre><code class="language-bash">curl -X POST http://localhost:8787/explain \
  -H 'Content-Type: application/json' \
  -d '{"topic":"microservices"}'
</code></pre>
<p>Expected output (abbreviated):</p>
<pre><code class="language-json">{"explanation":"Welcome! As a junior engineer, you're going to hear the word \"Microservices\" thrown around constantly..."}
</code></pre>
<p>If it fails with <code>FAILED_PRECONDITION: ... set the GEMINI_API_KEY</code>, it means your Gemini API key isn't visible to the Worker. Restart the Worker by stopping the server and starting it again. Also ensure that you've set your Gemini API key in a <code>.dev.vars</code> file at the project root:</p>
<pre><code class="language-text">GEMINI_API_KEY=your-key-here
</code></pre>
<p><code>.dev.vars</code> is local-only and gitignored. Wrangler reads it once at startup. If you add or change a key while <code>pnpm dev</code> is running, restart the dev server.</p>
<h2 id="heading-how-to-run-the-app-with-the-genkit-dev-ui">How to Run the App with the Genkit Dev UI</h2>
<img src="https://cdn.hashnode.com/uploads/covers/66e28b713f978a0e2cd2b763/0844b694-39e3-49b0-ad8c-26cb42b27fe0.png" alt="The Genkit Dev UI" style="display: block;" width="600" height="400" loading="lazy">

<p>The <a href="https://genkit.dev/docs/js/devtools/">Genkit Developer UI</a> is a local web page that lists your flows, shows traces for every run, and lets you run flows from a UI instead of curl. It's one of Genkit's best features and it can't run on Cloudflare Workers. Why?</p>
<p>The UI is a browser page, but it talks to a <strong>reflection server</strong>: a HTTP server inside your process that exposes your registered Genkit components (flows, models, tools). Starting an HTTP server and hosting Express is a Node.js job. Workers can't do it.</p>
<p>So the architecture is this: your app runs in Node for development (where the reflection server lives), and runs in Workers when in production (where it doesn't).</p>
<p>Create <code>src/dev.ts</code> (entry point for the reflection server):</p>
<pre><code class="language-ts">import './genkit-runtime';
import { serve } from '@hono/node-server';
import app from './app';

serve({ fetch: app.fetch, port: 3781 }, (info) =&gt; {
	console.log(`Hono server listening on http://localhost:${info.port}`);
});
</code></pre>
<p>This serves the same <code>app</code>: the same routes, validation, and flow from Node on port 3781, using <code>@hono/node-server</code>. So there are two runtimes each with its own entry point: <code>src/index.ts</code> is the Worker entry point, <code>src/dev.ts</code> is the Node.js entry point, and everything else is shared.</p>
<p>Add the script to <code>package.json</code>:</p>
<pre><code class="language-json">"genkit:dev": "genkit start -- tsx --env-file=.dev.vars --watch src/dev.ts"
</code></pre>
<p>Run it with your key in the environment. This is the simplest way, since you already have <code>.dev.vars</code>:</p>
<pre><code class="language-bash">pnpm run genkit:dev
</code></pre>
<p>Expected output:</p>
<pre><code class="language-text">Genkit Developer UI: http://localhost:4000
Hono server listening on http://localhost:3781
</code></pre>
<p>Open <a href="http://localhost:4000">http://localhost:4000</a>. You should see <code>explainerFlow</code> in the flows list. Run it with <code>{"topic":"recursion"}</code> and you get an explanation back. This is the same response your Worker returns, served this time by Node.</p>
<img src="https://cdn.hashnode.com/uploads/covers/66e28b713f978a0e2cd2b763/9bb22518-a4b3-4e7a-81a9-f4872bcd0d1b.png" alt="Genkit Dev UI after running the flow (explaining recursion)" style="display: block;" width="600" height="400" loading="lazy">

<p>If the flows list is empty, the reflection server probably shut itself down because <code>GEMINI_API_KEY</code> wasn't in the environment when <code>genkit:dev</code> started.</p>
<h2 id="heading-how-to-deploy-to-cloudflare-workers">How to Deploy to Cloudflare Workers</h2>
<p>First, you need to deploy your worker, because the command for setting Worker secrets targets only workers that have been deployed. To deploy your worker:</p>
<pre><code class="language-bash">pnpm run deploy
</code></pre>
<p>Note that the first time you run any <code>wrangler</code> command, it asks you to authenticate. It:</p>
<ul>
<li>prints a URL</li>
<li>opens your browser</li>
<li>asks you to log in to Cloudflare and authorize Wrangler</li>
</ul>
<p>Authorization returns a token and the CLI picks up the token automatically.</p>
<p>In the deployment process, Wrangler bundles your Worker, uploads it, and prints your live URL thereafter:</p>
<pre><code class="language-text">https://deploy-genkit-apps-on-cloudflare-workers.&lt;your-account&gt;.workers.dev
</code></pre>
<p>Secrets are encrypted and injected as environment variables at runtime. Give your deployed Worker the API key as a secret:</p>
<pre><code class="language-bash">pnpm dlx wrangler secret put GEMINI_API_KEY
</code></pre>
<p>Wrangler prompts you to <code>Enter the secret value:</code> and pastes what you type.</p>
<p>Test the deployed endpoint with curl or Postman:</p>
<pre><code class="language-bash">curl -X POST https://deploy-genkit-apps-on-cloudflare-workers.&lt;your-account&gt;.workers.dev/explain \
  -H 'Content-Type: application/json' \
  -d '{"topic":"microservices"}'
</code></pre>
<p>You receive the JSON explanation as a response. Your Genkit app is now running on Cloudflare's edge!</p>
<p>One note on configuration: this project needs no <code>compatibility_flags</code> configuration in <code>wrangler.json</code>. With a <code>compatibility_date</code> of 2026-11-13, Cloudflare enables <code>nodejs_compat</code> by default, which is what puts environment variables like <code>GEMINI_API_KEY</code> on <code>process.env</code> inside the Worker.</p>
<h2 id="heading-how-to-set-up-groq-as-a-fallback-provider">How to Set Up Groq as a Fallback Provider</h2>
<p>If you prefer to use Groq instead, get your Groq API key from the <a href="https://console.groq.com">Groq console</a>. Install <code>@genkit-ai/compat-oai</code> as a dependency in the project:</p>
<pre><code class="language-bash">pnpm add @genkit-ai/compat-oai
</code></pre>
<p>Add your key to <code>.dev.vars</code> and restart <code>pnpm dev</code>, because wrangler only reads that file at startup:</p>
<pre><code class="language-text">GROQ_API_KEY=your-groq-key
</code></pre>
<p>Swap the plugin and model in <code>src/flows/explainer.ts</code>:</p>
<pre><code class="language-ts">import { openAICompatible } from '@genkit-ai/compat-oai';
import { genkit, z } from 'genkit';

export const ai = genkit({
	plugins: [
		openAICompatible({
			name: 'groq',
			apiKey: process.env.GROQ_API_KEY,
			baseURL: 'https://api.groq.com/openai/v1',
		}),
	],
	model: 'groq/openai/gpt-oss-120b',
});
</code></pre>
<p>This is the only change required. <code>ai.generate()</code> is provider-agnostic, which is one of Genkit's selling points. The model reference is namespaced as <code>groq/&lt;model&gt;</code>, using the <code>name</code> you gave the plugin.</p>
<p>Test it locally with the same <code>curl</code> command as before. Expected output (abbreviated, wording may vary because AI is non-deterministic):</p>
<pre><code class="language-json">{"explanation":"## What's a \"Microservice\"?\n\nThink of a big software system as a city..."}
</code></pre>
<p>For production, set the secret the same way: <code>pnpm dlx wrangler secret put GROQ_API_KEY</code>.</p>
<h2 id="heading-troubleshooting-common-errors">Troubleshooting Common Errors</h2>
<p>Here are some tips to help you solve common issues you might encounter:</p>
<table>
<thead>
<tr>
<th>Error message</th>
<th>Cause</th>
<th>Fix</th>
</tr>
</thead>
<tbody><tr>
<td><code>TypeError: require_streams(...) is not a function</code> at startup</td>
<td>Genkit's import chain loads express inside workerd</td>
<td>Add the <code>express</code> alias in <code>wrangler.jsonc</code></td>
</tr>
<tr>
<td><code>EvalError: Code generation from strings disallowed</code></td>
<td>A string <code>system</code>/<code>prompt</code> went through dotprompt</td>
<td>Pass prompts as parts: <code>system: [{ text }]</code></td>
</tr>
<tr>
<td><code>FAILED_PRECONDITION: ... set the GEMINI_API_KEY</code></td>
<td>Key missing from the Worker's environment</td>
<td>Add it to <code>.dev.vars</code>, restart <code>pnpm dev</code></td>
</tr>
<tr>
<td>Dev UI loads but shows no flows</td>
<td>Reflection server stopped: key missing when <code>genkit:dev</code> started</td>
<td>Export the key, restart <code>pnpm run genkit:dev</code></td>
</tr>
<tr>
<td><code>503 ... experiencing high demand</code></td>
<td>Provider capacity, not your code</td>
<td>Retry, or switch to the Groq setup above</td>
</tr>
<tr>
<td><code>@cfworker/json-schema</code> warning at startup</td>
<td>Unconditional reminder from <code>setGenkitRuntimeConfig</code></td>
<td>Install the package. The warning is harmless.</td>
</tr>
</tbody></table>
<h2 id="heading-streaming-responses-with-genkit-on-cloudflare-workers">Streaming Responses with Genkit on Cloudflare Workers</h2>
<p>This tutorial covers non-streaming flow calls: one request returning one JSON response, a request-response cycle. If you want tokens streamed as they are generated, Genkit documents streaming flow calls separately in <a href="https://genkit.dev/docs/js/deployment/any-platform/#streaming-flow-calls">its deployment guide</a>.</p>
<h2 id="heading-limitations-of-genkit-on-cloudflare-workers">Limitations of Genkit on Cloudflare Workers</h2>
<p>Here are a few limitations worth knowing when deploying Genkit on Workers:</p>
<ul>
<li>The Dev UI and reflection server run in Node only. On Workers, <code>sandboxedRuntime</code> disables them by design. This means that you can't access the Dev UI of your app in production.</li>
<li>The Express stub means no Express-based Genkit feature will work inside your Worker. For a regular Genkit application, nothing you need does anyway. The stub only exists to let the import succeed.</li>
<li>Dotprompt string templates are unavailable on Workers. Prompts must be passed as message parts.</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>You built a Genkit flow, validated its input with a shared zod schema, and ran it in three places: the local Workers runtime, Node under the Dev UI, and a live Cloudflare Worker. Along the way, you learned about the hurdles you may experience when deploying Genkit applications on Cloudflare Workers:</p>
<ul>
<li>interpret-mode schema validation</li>
<li>message-part prompts that bypass dotprompt's <code>new Function()</code> and</li>
<li>the Express stub that keeps Genkit's import chain from crashing <code>workerd</code></li>
</ul>
<p>You also learned how to scale through the hurdles.</p>
<p>Go ahead and build with Genkit and deploy it on Cloudflare.</p>
<p>To see the finished version of the project, check the <code>article/deploy-genkit-on-cloudflare</code> branch of the project non GitHub. If you have any questions, or just want to say hi, reach out to <a href="https://linkedin.com/in/orimdominicadah">Orim Dominic on LinkedIn</a>.</p>
<h2 id="heading-references">References</h2>
<ul>
<li><a href="https://genkit.dev/docs/js/deployment/any-platform/#environments-that-restrict-eval">Genkit deployment guide: restricted <code>eval</code> environments</a></li>
<li><a href="https://genkit.dev/docs/js/devtools/">Genkit Developer tools (Developer UI and CLI)</a></li>
<li><a href="https://developers.cloudflare.com/workers/runtime-apis/web-standards/">Cloudflare Workers: <code>eval()</code> and <code>new Function</code> are not allowed</a></li>
<li><a href="https://www.npmjs.com/package/@genkit-ai/compat-oai"><code>@genkit-ai/compat-oai</code> (OpenAI-compatible providers)</a></li>
<li><a href="https://console.groq.com/docs/quickstart">Groq API quickstart</a></li>
<li><a href="https://hono.dev/docs/">Hono</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ AI Agents for Beginners – From Architecture to a Working Sales & Lead Enrichment Agent ]]>
                </title>
                <description>
                    <![CDATA[ An AI agent is an LLM that is given a goal, a set of tools, and the autonomy to decide which tools to use in a loop until the goal is complete. The agent built in this course researches each new sales ]]>
                </description>
                <link>https://www.freecodecamp.org/news/ai-agents-for-beginners-from-architecture-to-a-working-sales-lead-enrichment-agent/</link>
                <guid isPermaLink="false">6b118fdc26a8630a01dc18dc</guid>
                
                    <category>
                        <![CDATA[ ai agents ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Thu, 03 Dec 2026 15:50:52 +0000</pubDate>
                <media:content url="https://i.ytimg.com/vi/5tigibIvyFo/maxresdefault.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>An AI agent is an LLM that is given a goal, a set of tools, and the autonomy to decide which tools to use in a loop until the goal is complete. The agent built in this course researches each new sales lead on the live web, scores it against an ideal customer profile, and drafts a personalized outreach email.</p>
<p>We just published a course on the freeCodeCamp.org YouTube channel that will teach you how AI agents work and how to build a sales and lead enrichment agent from scratch. I created this course, and Oxylabs provided a grant to make it possible.</p>
<p>You'll build the workflow visually in n8n, then see the same agent loop in Python, using the Oxylabs Web API for web search and scraping.</p>
<p>In this course, you will learn:</p>
<ul>
<li><strong>Agent Architecture</strong><br>How the model, instructions, memory, and tools fit together in a loop of thinking, calling a tool, and observing the result.</li>
<li><strong>Live Web Data for Agents</strong><br>Why stale training data and plain HTTP GET requests break down on JavaScript-rendered sites, bot protection, and messy HTML.</li>
<li><strong>Building the Workflow in n8n</strong><br>How to connect a Google Sheets trigger, an AI Agent node, Oxylabs search and scrape tools, and a structured output parser.</li>
<li><strong>The Same Agent in Python</strong><br>How a short loop runs whichever Oxylabs tool the model requests and appends each result to the conversation history.</li>
<li><strong>Testing &amp; Production Reliability</strong><br>How the agent handles Vercel and a local bakery, plus five tips such as capping max iterations and keeping a human in the loop.</li>
<li><strong>MCP &amp; Agent Skills</strong><br>How the Oxylabs remote MCP server and skill.md instruction files fit into a larger agent setup.</li>
</ul>
<p>Watch the full course on the <a href="https://youtu.be/5tigibIvyFo">freeCodeCamp.org YouTube channel</a> (43-minute watch).</p>
<div class="embed-wrapper"><iframe width="560" height="315" src="https://www.youtube.com/embed/5tigibIvyFo" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Math Behind Using LoRA to Fine-Tune LLMs ]]>
                </title>
                <description>
                    <![CDATA[ If you've been following the world of Large Language Models (LLMs), one term you have likely come across is fine-tuning. But what actually happens under the hood? What does it do to the LLM? In this a ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-math-behind-using-lora-to-fine-tune-llms/</link>
                <guid isPermaLink="false">6b105e86d822001f7d611b1a</guid>
                
                    <category>
                        <![CDATA[ llm ]]>
                    </category>
                
                    <category>
                        <![CDATA[ finetuning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ lora-math ]]>
                    </category>
                
                    <category>
                        <![CDATA[ MathJax ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Dev J. Shah ]]>
                </dc:creator>
                <pubDate>Wed, 02 Dec 2026 18:08:06 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/6eb87488-ad56-4063-a57d-c5c19e4d9dcf.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you've been following the world of Large Language Models (LLMs), one term you have likely come across is fine-tuning. But what actually happens under the hood? What does it do to the LLM?</p>
<p>In this article, you'll first start by understanding what an LLM actually outputs. Then you'll learn how fine-tuning works. The method you'll focus on here is LoRA (Low-Rank Adaptation) which is one of the most popular approaches to fine-tuning.</p>
<p>Throughout the article, you'll follow one small example to understand how everything works. You don't need to have any prior machine learning or math background to follow along.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a href="#heading-how-an-llm-picks-the-next-token">How an LLM Picks the Next Token</a></li>
<li><a href="#heading-what-is-fine-tuning">What Is Fine-Tuning?</a></li>
<li><a href="#heading-how-lora-works">How LoRA Works</a><ul>
<li><a href="#heading-low-rank-factorization">Low-Rank Factorization</a></li>
<li><a href="#heading-how-lora-uses-this-idea">How LoRA Uses This Idea</a></li>
</ul>
</li>
<li><a href="#heading-how-to-fine-tune-intern-llm-with-lora">How to Fine-Tune intern-llm with LoRA</a><ul>
<li><a href="#heading-how-to-prepare-the-dataset">How to Prepare the Dataset</a></li>
<li><a href="#heading-the-fine-tuning-loop">The Fine-Tuning Loop</a></li>
<li><a href="#heading-the-adapter-and-scaling">The Adapter and Scaling</a></li>
</ul>
</li>
<li><a href="#heading-conclusion">Conclusion</a></li>
<li><a href="#heading-take-home-exercise">Take-Home Exercise</a></li>
</ul>
<h2 id="heading-how-an-llm-picks-the-next-token">How an LLM Picks the Next Token</h2>
<p>First, what's at the core of an LLM's behavior? It's a token: the single unit that decides the tone, nature, and characteristics of the response the model generates.</p>
<p>Even the basic unit that you use for calculating LLM usage is a token. In general, a token can be a character, sub-word, or word.</p>
<p>Throughout this article, the term token refers to a word. In practice, LLMs often split words into sub-words, but treating each token as a word keeps the example simple.</p>
<p>Now back to what defines the nature of a generated response. To understand this, first you need to understand how the system around an LLM works.</p>
<p>A regular LLM receives a series of tokens (for example, a sentence) and returns a list of possible next tokens, each with a probability. This is the fundamental task of an LLM.</p>
<img src="https://cdn.hashnode.com/uploads/covers/66fd782ea4d5e9315ee67eea/0076803e-a571-4b1b-9e52-d91fc8d6c252.png" alt="This is a diagram of a series of tokens being input to an LLM and 3 tokens are output: Token 1 with 0.64, Token 2 with 0.20 and Token 3 with 0.16 probability." style="display: block;" width="600" height="400" loading="lazy">

<p>It's similar to how the predictive text suggests the next word on your phone as you type. An LLM does the same thing, but at a much larger scale with a probability calculated for every possible next token.</p>
<p>The LLM then adds the token with the highest probability to the initial series of tokens and the loop keeps going until the full response is generated. So the nature of the generated response comes down to a calculation of probability.</p>
<p>A raw base LLM doesn't know how to talk with humans, be polite, or follow instructions. All those behaviors come from extra training and from the systems that wrap it.</p>
<p>Now, assume that I have an LLM called <code>intern-llm</code>. When I pass it a series of tokens that say "Using light mode in your code editor is", it returns the following tokens with their probabilities:</p>
<ul>
<li>"Clean": 0.64</li>
<li>"Crime": 0.20</li>
<li>"Blinding": 0.16</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/66fd782ea4d5e9315ee67eea/72fb86aa-f95e-45a5-93ac-8002392b8486.png" alt="This is the diagram of prompt &quot;Using light mode in your code editor is&quot; being input to the LLM and 3 tokens output by the LLM: Token 1 with 0.64, Token 2 with 0.20 and Token 3 with 0.16 probability." style="display: block;" width="600" height="400" loading="lazy">

<p>In other words, the LLM is completing the sentence, and it thinks the most likely ending is "Using light mode in your code editor is clean."</p>
<p>And, like many of you likely did, I was irritated with this answer.</p>
<p>But then I realized that an LLM doesn't have a personal opinion. All it does is some calculations, which it then uses to come up with these probabilities.</p>
<p>So I pardoned the model and decided to fix this calculation and turn <code>intern-llm</code> into <code>senior-llm</code>. Here, <code>intern-llm</code> is the base LLM, and <code>senior-llm</code> is its fine-tuned version.</p>
<p>In order to do this, my first step was to find out how the LLM calculates these probabilities. This is when I learned that these calculations are the result of the LLM's training.</p>
<p>During the training of the LLM, it stores whatever it learns in the form of numbers. In basic terms, you can call these numbers weights. Essentially, these weights drive the probability calculations.</p>
<p>Then I discovered that the LLM doesn't just have a handful of these weights. Apparently, it has millions or billions of them. And it arranges these weights into grid-like structures called matrices.</p>
<p>$$W = \begin{bmatrix} 0.12 &amp; 0.84 &amp; 0.33 &amp; 0.71 &amp; 0.29 \\ 0.91 &amp; 0.27 &amp; 0.56 &amp; 0.14 &amp; 0.88 \\ 0.44 &amp; 0.69 &amp; 0.11 &amp; 0.93 &amp; 0.37 \\ 0.55 &amp; 0.32 &amp; 0.78 &amp; 0.61 &amp; 0.45 \\ 0.23 &amp; 0.87 &amp; 0.19 &amp; 0.42 &amp; 0.66 \end{bmatrix}$$</p>
<p>All LLMs use multiple such matrices to calculate the probabilities of the next tokens. Above is a miniature 5 x 5 matrix. Each number in it represents a single weight, and this grid arrangement makes it a 25-weight matrix W.</p>
<p>After I learned this, the path became clear. I had to update these weights so that the LLM would calculate probabilities where the tokens "Crime" and "Blinding" scored above "Clean", as they're the more likely answers.</p>
<h2 id="heading-what-is-fine-tuning">What Is Fine-Tuning?</h2>
<p>This process is called fine-tuning: modifying these weights to nudge the LLM to calculate the probability of the next set of tokens differently from what it was trained to do. The process where all the weights of the LLM are updated is called full fine-tuning.</p>
<p>Notice here that you're changing how the LLM calculates the probabilities, not the facts it knows. And because you fine-tune it on hundreds or thousands of examples instead of a single one, the LLM learns a general pattern. It then applies this pattern to new prompts it hasn't seen before.</p>
<p>For this use case, full fine-tuning is one of the options. But as you now know, LLMs usually have billions of weights.</p>
<p>For example, a 7-billion-parameter (7B) LLM has 7 billion weights, which would require massive GPU memory and training time for full fine-tuning. Even for a small change like this one, updating billions of weights would be overkill.</p>
<p>So I started looking for alternatives, because you don't want to reteach the model fundamental knowledge that it already has. All you want is to make a few tweaks so that it calculates the probability of the next tokens differently.</p>
<p>This is when I learned about Parameter-Efficient Fine-Tuning (PEFT), the process in which only a portion of the LLM's weights is changed to nudge its behavior. One of the most widely known PEFT methods is Low-Rank Adaptation, or LoRA.</p>
<h2 id="heading-how-lora-works">How LoRA Works</h2>
<h3 id="heading-low-rank-factorization">Low-Rank Factorization</h3>
<p>LoRA is inspired by a mathematical concept called Low-Rank Factorization, where a big matrix is factorized into two smaller ones with comparatively fewer numbers. Take a look at this 5 x 5 matrix M. It holds 25 numbers.</p>
<p>$$M = \begin{bmatrix} 1 &amp; 2 &amp; 0 &amp; 1 &amp; 3 \\ 0 &amp; 1 &amp; 2 &amp; 1 &amp; 0 \\ 1 &amp; 3 &amp; 2 &amp; 2 &amp; 3 \\ 2 &amp; 4 &amp; 0 &amp; 2 &amp; 6 \\ 1 &amp; 4 &amp; 4 &amp; 3 &amp; 3 \end{bmatrix}$$</p>
<p>Now look at these two smaller matrices below, P (5 x 2) and Q (2 x 5).</p>
<p>$$P = \begin{bmatrix} 1 &amp; 0 \\ 0 &amp; 1 \\ 1 &amp; 1 \\ 2 &amp; 0 \\ 1 &amp; 2 \end{bmatrix} \quad Q = \begin{bmatrix} 1 &amp; 2 &amp; 0 &amp; 1 &amp; 3 \\ 0 &amp; 1 &amp; 2 &amp; 1 &amp; 0 \end{bmatrix}$$</p>
<p>Quick math refresher for anyone who needs it: You can only multiply two matrices if the number of columns of the first matrix is equal to the number of the rows in the second matrix. Also, the size of the product of the multiplication becomes the row of the first matrix and the column of the second.</p>
<p>In simple words, P (5 rows x 2 columns) times Q (2 rows x 5 columns) can be multiplied because P has 2 columns and Q has 2 rows and the size of its product will be 5 x 5.</p>
<p>When you multiply these matrices above, you get M back as a result. But P and Q together hold only 20 numbers, whereas M holds 25 numbers.</p>
<p>Notice that P has 2 columns and Q has 2 rows. This shared number, 2, is called the rank, and it's what the "Rank" term in "Low-Rank Factorization" refers to. The smaller the rank, the fewer numbers you need.</p>
<h3 id="heading-how-lora-uses-this-idea">How LoRA Uses This Idea</h3>
<p>LoRA is <strong>inspired</strong> by this idea with a caveat, as the name suggests. It's not Low-Rank Factorization. It's Low-Rank <strong>Adaptation</strong>.</p>
<p>In simple terms, you don't break the existing matrix W into separate factors. Instead, you create two small matrices next to it. The original matrix is frozen, which means its weights don't change during fine-tuning.</p>
<p>Bringing back the 5 x 5 weight matrix W (from the beginning of the article), you freeze this during fine-tuning to ensure that <code>intern-llm</code> keeps its original knowledge.</p>
<p>$$W_{\text{frozen}} = \begin{bmatrix} 0.12 &amp; 0.84 &amp; 0.33 &amp; 0.71 &amp; 0.29 \\ 0.91 &amp; 0.27 &amp; 0.56 &amp; 0.14 &amp; 0.88 \\ 0.44 &amp; 0.69 &amp; 0.11 &amp; 0.93 &amp; 0.37 \\ 0.55 &amp; 0.32 &amp; 0.78 &amp; 0.61 &amp; 0.45 \\ 0.23 &amp; 0.87 &amp; 0.19 &amp; 0.42 &amp; 0.66 \end{bmatrix}$$</p>
<p>Then, instead of changing W, you add two new weight matrices with the frozen W. The size of these two matrices comes from W's size and the rank you pick:</p>
<ul>
<li>A's number of rows = W's number of rows</li>
<li>B's number of columns = W's number of columns</li>
<li>A's number of columns = B's number of rows = the rank you pick</li>
</ul>
<p>In this example, if you go with:</p>
<ul>
<li>r = 4: A and B together hold 40 weights, which is more than W's 25</li>
<li>r = 3: A and B together hold 30 weights, which is still more than W's 25</li>
<li>r = 2: A and B together hold 20 weights, which is less than W's 25</li>
</ul>
<p>So 2 is the right rank here. In theory, you could go lower, but the lower the rank, the fewer weights A and B have to learn the pattern. So you still want to keep as many as you can afford to grasp most of the pattern.</p>
<p>With r = 2, A is 5 x 2 and B is 2 x 5.</p>
<p>$$A = \begin{bmatrix} 0.3 &amp; 0.7 \\ 0.5 &amp; 0.2 \\ 0.8 &amp; 0.4 \\ 0.1 &amp; 0.6 \\ 0.9 &amp; 0.3 \end{bmatrix} \quad B = \begin{bmatrix} 0 &amp; 0 &amp; 0 &amp; 0 &amp; 0 \\ 0 &amp; 0 &amp; 0 &amp; 0 &amp; 0 \end{bmatrix}$$</p>
<p>Multiplying them, (5 x 2) x (2 x 5), gives a 5 x 5 matrix, which exactly matches the shape of W. Matrix A holds 10 weights and B holds 10 weights, so you train only 20 weights instead of 25.</p>
<p>This miniature example may look like a small saving of a mere 5 weights. But as you know, in real life, LLMs have millions or billions of weights. For example, here's the summary of the <code>gemma3_instruct_1b</code> model before and after enabling LoRA (in this summary, "params" = "weights").</p>
<img src="https://cdn.hashnode.com/uploads/covers/66fd782ea4d5e9315ee67eea/26503679-d5cb-421d-8c8e-2909582e1a8c.png" alt="The metrics of gemma3_instruct_1b before enabling LoRA." style="display: block;" width="600" height="400" loading="lazy">

<p>Before enabling LoRA:</p>
<ul>
<li>Total params: 999,885,952 (3.72 GB)</li>
<li>Trainable params: 999,885,952 (3.72 GB)</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/66fd782ea4d5e9315ee67eea/47d5be25-83cd-4199-a080-04b5f59a0ab7.png" alt="The metrics of gemma3_instruct_1b after enabling LoRA of rank 4." style="display: block;" width="600" height="400" loading="lazy">

<p>After enabling LoRA with rank 4:</p>
<ul>
<li>Total params: 1,000,538,240 (3.73 GB)</li>
<li>Trainable params: 652,288 (2.49 MB)</li>
</ul>
<p>Just by enabling LoRA, the number of trainable weights drops to only 0.065% of the original number of weights. The total goes up slightly because LoRA added the two small matrices A and B, while all the original weights are frozen.</p>
<p>These numbers come from the first notebook that you will find in the <a href="#heading-take-home-exercise">Take-Home Exercise</a> at the end of this article. You can run it and see it yourself.</p>
<h2 id="heading-how-to-fine-tune-intern-llm-with-lora">How to Fine-Tune <code>intern-llm</code> with LoRA</h2>
<h3 id="heading-how-to-prepare-the-dataset">How to Prepare the Dataset</h3>
<p>The first step to fine-tune a model is to have a dataset for fine-tuning. This dataset consists of pairs of prompts and the responses you want the fine-tuned LLM to give.</p>
<p>For general use cases, there are a lot of datasets available on Hugging Face. For specific use cases, you need to create your own data, for example by writing the examples yourself or by generating them with a larger LLM and reviewing them. Either way, each example ends up as a prompt and response pair like this:</p>
<pre><code class="language-json">{
  "Prompt": "Using light mode in your code editor is",
  "Response": "Crime"
}
</code></pre>
<p>You need hundreds or thousands of such examples in your dataset.</p>
<h3 id="heading-the-fine-tuning-loop">The Fine-Tuning Loop</h3>
<h4 id="heading-step-1-forward-pass">Step 1: Forward Pass</h4>
<p>The first step in fine-tuning is called the forward pass. In this step, you only take the "Prompt" from the dataset and let it pass through the LLM.</p>
<p>It's like taking a practice test to understand the baseline and weak areas, which helps to build your strategy for studying before the exam. In short, no weights are updated during the forward pass. It only gets the LLM's current prediction, so you can compare it with the expected Response in the next steps.</p>
<p>The effective weight matrix that the LLM uses is the following:</p>
<p>$$W' = W + (A \times B)$$</p>
<img src="https://cdn.hashnode.com/uploads/covers/66fd782ea4d5e9315ee67eea/bc770f96-f030-41ab-bec2-823e02e68c50.png" alt="This diagram shows how the frozen W of the size 5 x 5 is being added with the product of matrix A of size 5 x 2 and B of size 2 x 5 to get the effective weight." style="display: block;" width="600" height="400" loading="lazy">

<p>If you look at the values in the A and B matrices from earlier, A contains random numbers, while B has all zeros, which is a design choice. This makes the product of A and B zero. Hence, during the first iteration, the effective weight matrix of the LLM becomes W' = W.</p>
<p>So during the first forward pass, when you pass "Using light mode in your code editor is", the LLM still calculates the highest probability for "Clean". However, from the next iterations, A and B would get some values or change in value to nudge the behavior of the LLM.</p>
<h4 id="heading-step-2-calculate-the-loss">Step 2: Calculate the Loss</h4>
<p>The next step of fine-tuning is calculating the loss. As per the dataset, the LLM should have predicted "Crime", but instead it predicted "Clean". So now, you'll calculate the loss.</p>
<p>Since the "Response" in the dataset is "Crime", the target probability for "Crime" is 1 and for every other token it is 0. The probabilities the LLM calculated are 0.64 for Clean, 0.20 for Crime, and 0.16 for Blinding. So the difference from the target for each token is:</p>
<ul>
<li>Clean: 0 - 0.64 = -0.64</li>
<li>Crime: 1 - 0.20 = +0.80</li>
<li>Blinding: 0 - 0.16 = -0.16</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/66fd782ea4d5e9315ee67eea/3c9ad0e9-8c34-4c24-bc86-57e857a29c92.png" alt="Bar chart of the loss for each token. Red shows the distance from the target: 0.64 for Clean and 0.16 for Blinding, which need to drop to 0, and 0.80 for Crime, which needs to rise to 1." style="display: block;" width="600" height="400" loading="lazy">

<p>These differences are combined into a single number, called the loss, which shows how far the LLM's prediction is from the expected Response. The closer the probability for "Crime" gets to 1, the closer the loss gets to 0, and vice versa.</p>
<p>In the above image, red bars are the distance from the target. For Clean and Blinding, you need to reduce the red bar to 0, whereas for Crime, you need to eliminate the red bar by increasing its probability towards 1.</p>
<h4 id="heading-step-3-backward-pass">Step 3: Backward Pass</h4>
<p>In the next step, you take the loss and do a backward pass. This means you pass the loss back through the LLM so it can adjust its weights to compensate for the error.</p>
<p>Because the original weight matrix W of the LLM is frozen, it updates the values stored in the matrices A and B. These weights are updated to minimize the loss the next time it gets the same prompt. In a way, A and B only store the weights that fill the gap. The gap is the change the LLM's original weight matrix W needs to reduce the red parts in the diagram in Step 2.</p>
<p>Notice that I used the phrase "weights are updated to minimize the loss". This is because, in practice, the probabilities never become exactly 1 or 0. If they get too close, that means the model is memorizing the dataset instead of learning the pattern. This is because a training dataset usually contains more than one valid response for similar prompts, so the LLM learns to give high probabilities to all of them instead of just one.</p>
<h4 id="heading-step-4-repeat">Step 4: Repeat</h4>
<p>All the examples from the dataset go through this loop of forward pass, calculate loss, and backward pass. One complete pass of the whole dataset through this loop is called 1 epoch. In practice, you perform multiple epochs until A and B closely learn the gap to turn <code>intern-llm</code> into <code>senior-llm</code>.</p>
<img src="https://cdn.hashnode.com/uploads/covers/66fd782ea4d5e9315ee67eea/dfc16a6d-b220-4d69-83dc-dd43868b6930.png" alt="The flowchat of the fine-tuning loop that shows the dataset going through forward pass, loss calculation, backward pass, updates value of A and B and back to the dataset." style="display: block;" width="600" height="400" loading="lazy">

<h3 id="heading-the-adapter-and-scaling">The Adapter and Scaling</h3>
<p>Once the fine-tuning is done, the matrices A and B are stored in an adapter. An adapter is a small, separate file that holds the weights in A and B. It's like an extension for <code>intern-llm</code>.</p>
<p>Later, when you want to use <code>senior-llm</code> to generate the responses, you'll attach this adapter to <code>intern-llm</code>. Since the adapter is a separate file from <code>intern-llm</code>, <code>intern-llm</code> can have multiple compatible adapters, which give it its fine-tuned capabilities.</p>
<p>For example, you could fine-tune one adapter that makes the LLM prefer dark mode (the "Crime" adapter) and another adapter that makes it answer in short bullet points. The base LLM stays the same, and you swap whichever adapter the task needs.</p>
<img src="https://cdn.hashnode.com/uploads/covers/66fd782ea4d5e9315ee67eea/c7286f16-253e-491b-9142-c362e2dd04bf.png" alt="A diagram showing how the fine-tuned model consist of the base model with frozen original W and the adapter A and B." style="display: block;" width="600" height="400" loading="lazy">

<p>There's one more factor in the formula. So far, you've simply added A x B to W to get the effective weight. But, in practice, LoRA also multiplies A x B with a scaling factor that controls how much the adapter changes the LLM's probability calculation. So the correct formula is</p>
<p>$$W' = W + \frac{\alpha}{r}(A \times B)$$</p>
<p>Here,</p>
<ul>
<li>r = The rank, which is 2 in this example</li>
<li>α = A volume knob controlling how strongly the adapter influences the base LLM</li>
<li>Dividing α by r keeps that volume balanced even if you increase the rank later, so <code>senior-llm</code> doesn't lose <code>intern-llm</code>'s core skills</li>
</ul>
<p>Now, once fine-tuning is done, when you pass "Using light mode in your code editor is" to <code>senior-llm</code>, it calculates higher probabilities for "Crime" and "Blinding" than for "Clean".</p>
<img src="https://cdn.hashnode.com/uploads/covers/66fd782ea4d5e9315ee67eea/46bf366e-9065-4f79-9b16-958531548f65.png" alt="Two bar charts showing the next token prediction by the LLM before and after fine-tuning." style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-conclusion">Conclusion</h2>
<p>When using LoRA, you freeze the original weight matrix W and train two small matrices instead. This helps reduce the number of weights you need to change. At the same time, the LLM still keeps everything that it learned during its original training, and A and B only learn the gap between <code>intern-llm</code> and <code>senior-llm</code>.</p>
<p>With fewer weights, you can fine-tune an LLM without needing a big GPU and also make the process faster. And since each adapter is separate, you can swap adapters to use the same base LLM for different tasks.</p>
<h2 id="heading-take-home-exercise">Take-Home Exercise</h2>
<p>I don't understand a new concept unless I see and run the code myself. So I encourage you to try the following two notebooks:</p>
<ol>
<li><a href="https://github.com/busycaesar/LoRA/blob/Master/google-gemma/gemma.ipynb">The first notebook</a> fine-tunes the <code>gemma3_instruct_1b</code> model using LoRA and stores the adapter on <a href="https://huggingface.co/busycaesar/gemma3-adapter">Hugging Face</a>.</li>
<li><a href="https://github.com/busycaesar/LoRA/blob/Master/google-gemma/gemma-adaptor.ipynb">The second notebook</a> shows how you can directly attach an adapter trained for the same model and, in a few steps, get its fine-tuned version.</li>
</ol>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use SQLAlchemy ORM to Work with Databases in Python ]]>
                </title>
                <description>
                    <![CDATA[ Python applications often store their data in relational databases. When you write the SQL yourself, you also have to turn rows into objects, link related records, and protect queries against SQL inje ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-sqlalchemy-orm-to-work-with-databases-in-python/</link>
                <guid isPermaLink="false">6b1049f4ae28eaa526daa1aa</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ orm ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Databases ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Bala Priya C ]]>
                </dc:creator>
                <pubDate>Wed, 02 Dec 2026 16:40:20 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/280fa6d1-8f81-4073-9ce0-4748bc308a83.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Python applications often store their data in relational databases. When you write the SQL yourself, you also have to turn rows into objects, link related records, and protect queries against SQL injection. Each schema change then means finding and updating the affected queries by hand.</p>
<p>An <strong>Object Relational Mapper (ORM)</strong> takes much of this work off your hands by mapping Python classes to database tables. A class describes a table, an object stands for a row, and an attribute holds a column value. <a href="https://www.sqlalchemy.org/">SQLAlchemy</a>, a widely used Python database library, includes an ORM that writes the SQL for you and still lets you inspect it.</p>
<p>In this tutorial, you'll build a small library database with SQLAlchemy ORM. You'll define models, add and query records, load related data efficiently, and handle failed transactions. Let's get started!</p>
<p>You can get the <a href="https://github.com/balapriyac/python-basics/blob/main/sqlalchemy-orm/sqlalchemy_orm_tutorial_v1.ipynb">Colab notebook</a> for this tutorial and follow along.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a href="#heading-prerequisites">Prerequisites</a></li>
<li><a href="#heading-how-to-install-sqlalchemy">How to Install SQLAlchemy</a></li>
<li><a href="#heading-how-to-define-your-models">How to Define Your Models</a><ul>
<li><a href="#heading-how-to-create-the-author-model">How to Create the Author Model</a></li>
<li><a href="#heading-how-to-create-the-book-model">How to Create the Book Model</a></li>
</ul>
</li>
<li><a href="#heading-how-to-connect-to-the-database">How to Connect to the Database</a></li>
<li><a href="#heading-how-to-add-records">How to Add Records</a></li>
<li><a href="#heading-how-to-query-data">How to Query Data</a><ul>
<li><a href="#heading-how-to-filter-and-sort-results">How to Filter and Sort Results</a></li>
<li><a href="#heading-how-to-fetch-a-single-record">How to Fetch a Single Record</a></li>
<li><a href="#heading-how-to-join-and-aggregate-tables">How to Join and Aggregate Tables</a></li>
</ul>
</li>
<li><a href="#heading-how-to-load-related-data-efficiently">How to Load Related Data Efficiently</a></li>
<li><a href="#heading-how-to-update-and-delete-records">How to Update and Delete Records</a></li>
<li><a href="#heading-how-to-handle-transactions">How to Handle Transactions</a></li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To follow along, you'll need:</p>
<ul>
<li>Python 3.11 or later</li>
<li>Familiarity with Python classes and type hints</li>
<li>Basic SQL knowledge: tables, primary keys, foreign keys, and joins</li>
<li>SQLAlchemy 2.1 or later in a virtual environment (the installation steps are covered next)</li>
</ul>
<p>SQLAlchemy is the library your code will use, and SQLite is the database it will talk to. SQLite works through Python's built-in <code>sqlite3</code> module, so you don't have to set up a database server.</p>
<h2 id="heading-how-to-install-sqlalchemy">How to Install SQLAlchemy</h2>
<p>Create and activate a virtual environment:</p>
<pre><code class="language-bash">python -m venv .venv
source .venv/bin/activate
</code></pre>
<p>On Windows, activate it with <code>.venv\Scripts\activate</code>. Then install SQLAlchemy:</p>
<pre><code class="language-bash">pip install "sqlalchemy&gt;=2.1"
</code></pre>
<p>The code in this tutorial was tested with SQLAlchemy 2.1.9. Create a file named <code>main.py</code>, and add each Python snippet to the bottom of it as you go.</p>
<h2 id="heading-how-to-define-your-models">How to Define Your Models</h2>
<p>Every model inherits from a shared base class. Start by creating one:</p>
<pre><code class="language-python">from sqlalchemy import ForeignKey, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship


class Base(DeclarativeBase):
    pass
</code></pre>
<p><code>Base</code> keeps a record of every table you declare through its subclasses.</p>
<h3 id="heading-how-to-create-the-author-model">How to Create the Author Model</h3>
<p>Add an <code>Author</code> class:</p>
<pre><code class="language-python">class Author(Base):
    __tablename__ = "authors"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(100))
    email: Mapped[str] = mapped_column(unique=True)

    books: Mapped[list["Book"]] = relationship(
        back_populates="author", cascade="all, delete-orphan"
    )
</code></pre>
<p>Let's parse the definition:</p>
<ul>
<li><code>__tablename__</code> sets the name of the table.</li>
<li><code>Mapped[...]</code> declares the Python type of each attribute.</li>
<li><code>mapped_column()</code> adds database details such as the primary key, length, or a unique constraint.</li>
<li><code>relationship()</code> links an author to a list of books. The <code>cascade</code> option saves, and deletes, those books along with their author.</li>
</ul>
<h3 id="heading-how-to-create-the-book-model">How to Create the Book Model</h3>
<p>Each book belongs to one author:</p>
<pre><code class="language-python">class Book(Base):
    __tablename__ = "books"

    id: Mapped[int] = mapped_column(primary_key=True)
    title: Mapped[str] = mapped_column(String(200))
    year: Mapped[int]
    rating: Mapped[float | None]
    author_id: Mapped[int] = mapped_column(ForeignKey("authors.id"))

    author: Mapped["Author"] = relationship(back_populates="books")
</code></pre>
<p><code>ForeignKey("authors.id")</code> connects the two tables. The <code>back_populates</code> arguments keep both sides of the relationship in sync in Python.</p>
<p>The type hints also control nullability. <code>year</code> is a required column, while <code>float | None</code> allows <code>rating</code> to be empty.</p>
<img src="https://cdn.hashnode.com/uploads/covers/61c33020c0206b3f41f54194/c7ae39f2-f9f8-409c-bf40-311e4e967a6c.png" alt="Diagram showing the Author and Book Python classes mapped to the authors and books database tables, with a one-to-many relationship between the classes and a foreign key from books.author_id to authors.id. Created on diagrams.net (draw.io)" style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-how-to-connect-to-the-database">How to Connect to the Database</h2>
<p>An <strong>engine</strong> manages connections to your database. Create one, then create the tables:</p>
<pre><code class="language-python">from sqlalchemy import create_engine

engine = create_engine("sqlite://")
Base.metadata.create_all(engine)

print(list(Base.metadata.tables))
</code></pre>
<p>Output:</p>
<pre><code class="language-text">['authors', 'books']
</code></pre>
<p>The URL <code>sqlite://</code> creates an in-memory database, so every run starts fresh. To keep your data on disk, use <code>sqlite:///library.db</code>.</p>
<p><code>create_all()</code> creates only the tables that don't exist yet. It leaves existing tables unchanged, so use a migration tool such as Alembic when your schema changes.</p>
<h2 id="heading-how-to-add-records">How to Add Records</h2>
<p>You talk to the database through a <strong>session</strong>. Think of it as a shopping cart: you put objects in, and <code>commit()</code> is the checkout.</p>
<pre><code class="language-python">from sqlalchemy.orm import Session

ursula = Author(
    name="Ursula K. Le Guin",
    email="ursula@example.com",
    books=[
        Book(title="A Wizard of Earthsea", year=1968, rating=4.6),
        Book(title="The Dispossessed", year=1974, rating=4.8),
    ],
)
</code></pre>
<p>At this point, <code>ursula</code> is a regular Python object that exists only in memory. Create a second author:</p>
<pre><code class="language-python">octavia = Author(
    name="Octavia E. Butler",
    email="octavia@example.com",
    books=[Book(title="Kindred", year=1979)],
)
</code></pre>
<p>Now save both:</p>
<pre><code class="language-python">with Session(engine) as session:
    session.add_all([ursula, octavia])
    session.commit()
    print(ursula.id, octavia.id)
</code></pre>
<p>Output:</p>
<pre><code class="language-text">1 2
</code></pre>
<p>You added only the authors, and SQLAlchemy saved their books too. It also filled in each <code>author_id</code> for you.</p>
<p>The <code>with</code> block closes the session when you're done, even if an error occurs.</p>
<h2 id="heading-how-to-query-data">How to Query Data</h2>
<p>To read data, build a statement with <code>select()</code> and run it through a session.</p>
<h3 id="heading-how-to-filter-and-sort-results">How to Filter and Sort Results</h3>
<p>Fetch the books published after 1970, oldest first:</p>
<pre><code class="language-python">from sqlalchemy import select

stmt = select(Book).where(Book.year &gt; 1970).order_by(Book.year)

with Session(engine) as session:
    for book in session.scalars(stmt):
        print(book.title, book.year)
</code></pre>
<p>Output:</p>
<pre><code class="language-text">The Dispossessed 1974
Kindred 1979
</code></pre>
<p><code>scalars()</code> returns <code>Book</code> objects you can work with directly. If you're curious about the SQL, print the statement:</p>
<pre><code class="language-python">print(stmt)
</code></pre>
<p>Output:</p>
<pre><code class="language-text">SELECT books.id, books.title, books.year, books.rating, books.author_id 
FROM books 
WHERE books.year &gt; :year_1 ORDER BY books.year
</code></pre>
<p>The <code>:year_1</code> placeholder shows that the value travels separately from the SQL text. This protects your query against SQL injection.</p>
<h3 id="heading-how-to-fetch-a-single-record">How to Fetch a Single Record</h3>
<p>Use <code>get()</code> for a primary key lookup. For any other condition that matches at most one row, use <code>scalar_one_or_none()</code>:</p>
<pre><code class="language-python">with Session(engine) as session:
    first_book = session.get(Book, 1)
    print(first_book.title)

    stmt = select(Author).where(Author.email == "nobody@example.com")
    print(session.execute(stmt).scalar_one_or_none())
</code></pre>
<p>Output:</p>
<pre><code class="language-text">A Wizard of Earthsea
None
</code></pre>
<h3 id="heading-how-to-join-and-aggregate-tables">How to Join and Aggregate Tables</h3>
<p>Suppose you want to count the books by each author. Join the tables and group the rows:</p>
<pre><code class="language-python">from sqlalchemy import func

stmt = (
    select(Author.name, func.count(Book.id))
    .join(Author.books)
    .group_by(Author.id)
    .order_by(Author.name)
)
</code></pre>
<p><code>join(Author.books)</code> uses the relationship to work out the join condition. Since you're selecting individual columns, call <code>execute()</code> to get rows back:</p>
<pre><code class="language-python">with Session(engine) as session:
    for name, total in session.execute(stmt):
        print(f"{name}: {total}")
</code></pre>
<p>Output:</p>
<pre><code class="language-text">Octavia E. Butler: 1
Ursula K. Le Guin: 2
</code></pre>
<h2 id="heading-how-to-load-related-data-efficiently">How to Load Related Data Efficiently</h2>
<p>By default, SQLAlchemy loads a relationship when you first access it. This is called <strong>lazy loading</strong>.</p>
<p>To see its cost, add a query counter:</p>
<pre><code class="language-python">from sqlalchemy import event

queries = []


@event.listens_for(engine, "before_cursor_execute")
def track_query(conn, cursor, statement, *args):
    queries.append(statement)
</code></pre>
<p><strong>The problem</strong>: loop over the authors and access their books.</p>
<pre><code class="language-python">with Session(engine) as session:
    for author in session.scalars(select(Author)):
        print(author.name, len(author.books))

print("Queries:", len(queries))
</code></pre>
<p>Output:</p>
<pre><code class="language-text">Ursula K. Le Guin 2
Octavia E. Butler 1
Queries: 3
</code></pre>
<p>One query fetched the authors, and each author triggered another. With 500 authors, you'd send 501 queries. This is the <strong>N+1 query problem</strong>.</p>
<p><strong>The solution</strong>: ask for the books up front with <code>selectinload()</code>.</p>
<pre><code class="language-python">from sqlalchemy.orm import selectinload

queries.clear()
stmt = select(Author).options(selectinload(Author.books))

with Session(engine) as session:
    for author in session.scalars(stmt):
        print(author.name, len(author.books))

print("Queries:", len(queries))
</code></pre>
<p>Output:</p>
<pre><code class="language-text">Ursula K. Le Guin 2
Octavia E. Butler 1
Queries: 2
</code></pre>
<p>The second query loads the books for all the authors in one batch. I generally go for <code>selectinload()</code> first for collections. For many-to-one links such as <code>Book.author</code>, <code>joinedload()</code> is a good fit.</p>
<h2 id="heading-how-to-update-and-delete-records">How to Update and Delete Records</h2>
<p>To update a row, load the object and change its attribute:</p>
<pre><code class="language-python">with Session(engine) as session:
    stmt = select(Book).where(Book.title == "Kindred")
    kindred = session.scalars(stmt).one()

    kindred.rating = 4.7
    session.commit()
    print(kindred.title, kindred.rating)
</code></pre>
<p>Output:</p>
<pre><code class="language-text">Kindred 4.7
</code></pre>
<p>The session tracks the change and sends an <code>UPDATE</code> statement when you commit.</p>
<p>To delete a row, pass the object to <code>delete()</code>:</p>
<pre><code class="language-python">with Session(engine) as session:
    author = session.get(Author, 2)
    session.delete(author)
    session.commit()

    remaining = session.scalar(select(func.count(Book.id)))
    print("Books left:", remaining)
</code></pre>
<p>Output:</p>
<pre><code class="language-text">Books left: 2
</code></pre>
<p>Deleting Octavia also deleted <em>Kindred</em>, thanks to the cascade rule on <code>Author.books</code>.</p>
<p>No worries if you can't recall what <code>cascade</code> does. The <code>cascade="all, delete-orphan"</code> setting on <code>Author.books</code> tells SQLAlchemy that when you delete an author, it should delete that author's books too.</p>
<p>Before the deletion, the database has three books: Ursula wrote A Wizard of Earthsea and The Dispossessed, and Octavia wrote Kindred. The code deletes one author, Octavia, whose ID is 2, so SQLAlchemy also removes her only book, Kindred. Three books minus one leaves two, both by Ursula, which is why the output shows <code>Books left: 2</code>.</p>
<h2 id="heading-how-to-handle-transactions">How to Handle Transactions</h2>
<p>A <strong>transaction</strong> groups changes so that they all succeed or all fail.</p>
<p><strong>The problem</strong>: add a new author along with an email address that's already taken.</p>
<pre><code class="language-python">duplicate = Author(name="Another Ursula", email="ursula@example.com")

with Session(engine) as session:
    session.add(duplicate)
    session.commit()
</code></pre>
<p>Output:</p>
<img src="https://cdn.hashnode.com/uploads/covers/61c33020c0206b3f41f54194/da6886e5-fc9e-4e71-9003-ff19faa6c25c.png" alt="da6886e5-fc9e-4e71-9003-ff19faa6c25c" style="display: block;" width="600" height="400" loading="lazy">

<p><strong>The solution</strong>: replace that last <code>with</code> block with the code below, which opens the transaction using <code>session.begin()</code> and catches the error.</p>
<pre><code class="language-python">from sqlalchemy.exc import IntegrityError

try:
    with Session(engine) as session, session.begin():
        session.add(Author(name="N. K. Jemisin", email="nora@example.com"))
        session.add(Author(name="Another Ursula", email="ursula@example.com"))
except IntegrityError:
    print("That email already exists. Nothing was saved.")
</code></pre>
<p>Output:</p>
<pre><code class="language-text">That email already exists. Nothing was saved.
</code></pre>
<p><code>session.begin()</code> commits when the block succeeds and rolls back when it raises an exception. The first author in the block was valid, but the rollback discarded that insert too:</p>
<pre><code class="language-python">with Session(engine) as session:
    print(session.scalars(select(Author.name)).all())
</code></pre>
<p>Which is why you can't find N.K. Jemisin in the output:</p>
<pre><code class="language-text">['Ursula K. Le Guin']
</code></pre>
<p>If you call <code>commit()</code> yourself and want to keep using the same session after a failure, call <code>session.rollback()</code> first.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, you defined two related models, saved and queried records, fixed an N+1 problem, and rolled back a failed transaction.</p>
<p>The table below maps each task to the tool you used for it:</p>
<table>
<thead>
<tr>
<th>Task</th>
<th>What to use</th>
</tr>
</thead>
<tbody><tr>
<td>Define a table</td>
<td>A subclass of <code>Base</code> with <code>mapped_column()</code></td>
</tr>
<tr>
<td>Link two tables</td>
<td><code>ForeignKey</code> and <code>relationship()</code></td>
</tr>
<tr>
<td>Add records</td>
<td><code>session.add()</code> or <code>session.add_all()</code></td>
</tr>
<tr>
<td>Fetch by primary key</td>
<td><code>session.get()</code></td>
</tr>
<tr>
<td>Fetch many objects</td>
<td><code>session.scalars(select(...))</code></td>
</tr>
<tr>
<td>Fetch columns</td>
<td><code>session.execute(select(...))</code></td>
</tr>
<tr>
<td>Load collections up front</td>
<td><code>selectinload()</code></td>
</tr>
<tr>
<td>Delete a record</td>
<td><code>session.delete()</code></td>
</tr>
<tr>
<td>Commit or roll back automatically</td>
<td><code>session.begin()</code></td>
</tr>
</tbody></table>
<p>The ORM is a good choice when your application creates, reads, and updates related objects. For large bulk operations or complex reports, SQLAlchemy Core or handwritten SQL gives you tighter control.</p>
<p>As a next step, switch the engine to a database file and add Alembic to manage schema changes. The <a href="https://docs.sqlalchemy.org/en/21/orm/">official SQLAlchemy ORM documentation</a> covers relationships and loading strategies in more depth. Keep learning!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Social Engineering Attacks work and How to Defend Against Them ]]>
                </title>
                <description>
                    <![CDATA[ Developers spend a lot of time making sure their code is secure. They check dependencies, fix vulnerabilities, review pull requests, and try to catch anything that could put their applications at risk ]]>
                </description>
                <link>https://www.freecodecamp.org/news/social-engineering-attacks-developers/</link>
                <guid isPermaLink="false">6b0efd53f95e25e6b6366733</guid>
                
                    <category>
                        <![CDATA[ social engineering ]]>
                    </category>
                
                    <category>
                        <![CDATA[ cybersecurity ]]>
                    </category>
                
                    <category>
                        <![CDATA[ developer security ]]>
                    </category>
                
                    <category>
                        <![CDATA[ #PhishingAttacks  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Online Scams ]]>
                    </category>
                
                    <category>
                        <![CDATA[ OnlineScamsPrevention ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Reetain Raina ]]>
                </dc:creator>
                <pubDate>Tue, 01 Dec 2026 17:01:07 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/7f7ae38b-b209-4d2f-8e21-dedd40aaaba4.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Developers spend a lot of time making sure their code is secure. They check dependencies, fix vulnerabilities, review pull requests, and try to catch anything that could put their applications at risk.</p>
<p>But there is one security problem that a perfectly written application can't fix: a developer being tricked into running something they shouldn't.</p>
<p>Consider a developer who receives a message from a recruiter offering an exciting job opportunity. The conversation goes well, the company sounds genuine, and the recruiter shares a GitHub repository containing a small coding assessment. It looks like a typical hiring process, so the developer clones the repository and runs the setup command.</p>
<p>But a few minutes later, that innocent-looking coding test could be doing something very different from what its README file said it would do. Suddenly, the job opportunity is the least of the developer's problems.</p>
<p>This is how social engineering works. Instead of breaking into a system by exploiting a software vulnerability, attackers manipulate people into giving them access or performing actions that compromise security. For developers, the consequences can extend beyond a stolen password to private repositories, API keys, cloud accounts, and even company infrastructure.</p>
<p>In this article, we'll explore how social engineering attacks target developers, why fake recruiters and online identities are becoming useful tools for attackers, how to recognise suspicious requests, and what practical steps developers can take to protect their accounts and development environments.</p>
<h3 id="heading-what-well-cover">What We'll Cover:</h3>
<ul>
<li><a href="#heading-what-is-social-engineering-and-why-are-developers-targeted">What Is Social Engineering and Why Are Developers Targeted?</a></li>
<li><a href="#heading-why-developers-are-particularly-attractive-targets">Why Developers Are Particularly Attractive Targets</a></li>
<li><a href="#heading-five-social-engineering-attacks-developers-should-know-about">Five Social Engineering Attacks Developers Should Know About</a><ul>
<li><a href="#heading-1-fake-recruiters-and-malicious-coding-assessments">1. Fake Recruiters and Malicious Coding Assessments</a></li>
<li><a href="#heading-2-fake-freelance-clients-and-project-invitations">2. Fake Freelance Clients and Project Invitations</a></li>
<li><a href="#heading-3-impersonation-of-maintainers-teammates-and-managers">3. Impersonation of Maintainers, Teammates, and Managers</a></li>
<li><a href="#heading-4-phishing-links-disguised-as-repository-and-package-notifications">4. Phishing Links Disguised as Repository and Package Notifications</a></li>
<li><a href="#heading-5-fake-online-profiles-that-build-trust-over-time">5. Fake Online Profiles That Build Trust Over Time</a></li>
</ul>
</li>
<li><a href="#heading-how-to-verify-whether-someone-online-is-actually-who-they-claim-to-be">How to Verify Whether Someone Online Is Actually Who They Claim to Be</a><ul>
<li><a href="#heading-check-their-profile-history-and-connections">Check Their Profile History and Connections</a></li>
<li><a href="#heading-confirm-their-identity-through-a-second-channel">Confirm Their Identity Through a Second Channel</a></li>
<li><a href="#heading-check-whether-their-profile-photo-appears-elsewhere">Check Whether Their Profile Photo Appears Elsewhere</a></li>
</ul>
</li>
<li><a href="#heading-practical-ways-you-can-protect-yourself">Practical Ways You Can Protect Yourself</a><ul>
<li><a href="#heading-treat-unfamiliar-code-like-an-untrusted-file">Treat Unfamiliar Code Like an Untrusted File</a></li>
<li><a href="#heading-protect-your-credentials-and-development-accounts">Protect Your Credentials and Development Accounts</a></li>
<li><a href="#heading-slow-down-when-someone-creates-urgency">Slow Down When Someone Creates Urgency</a></li>
<li><a href="#heading-keep-your-development-environment-updated">Keep Your Development Environment Updated</a></li>
</ul>
</li>
<li><a href="#heading-what-should-you-do-if-you-think-youve-been-targeted">What Should You Do If You Think You've Been Targeted?</a><ul>
<li><a href="#heading-stop-and-dont-interact-further">Stop and Don't Interact Further</a></li>
<li><a href="#heading-secure-your-accounts-and-development-environment">Secure Your Accounts and Development Environment</a></li>
<li><a href="#heading-report-the-incident">Report the Incident</a></li>
</ul>
</li>
<li><a href="#heading-quick-security-checklist-every-developer-should-follow">Quick Security Checklist Every Developer Should Follow</a></li>
<li><a href="#heading-final-thoughts">Final Thoughts</a></li>
</ul>
<h2 id="heading-what-is-social-engineering-and-why-are-developers-targeted">What Is Social Engineering and Why Are Developers Targeted?</h2>
<p>At its core, social engineering is psychological manipulation. Instead of spending weeks trying to crack a password or find a zero-day exploit, an attacker targets the person sitting behind the keyboard. They rely on basic instincts that we all share: curiosity, helpfulness, fear of making a mistake, and the urge to act fast when something sounds urgent.</p>
<p>There's real cognitive science behind why this works so well. Behavioral psychologists often describe human decision-making as a balance between two modes: a fast, automatic system that reacts on impulse, and a slower, analytical system that checks the facts.</p>
<p>When an attacker creates panic or excitement, they trigger a stress response in your brain that pushes you into that fast, reactive mode. Your analytical brain takes a back seat and you act before you think.</p>
<p>Consider a simple example. Suppose you receive an email claiming your GitHub account has been flagged for suspicious activity and will be suspended in an hour. Instead of hacking GitHub's servers, the attacker just builds a convincing fake login page. If they can get you worried enough to click the link and type in your password, they don't need to break into your account, you just handed them the keys.</p>
<h2 id="heading-why-developers-are-particularly-attractive-targets">Why Developers Are Particularly Attractive Targets</h2>
<p>This isn't just a theoretical risk. According to the <a href="https://www.verizon.com/business/resources/reports/dbir/"><u>Verizon Data Breach Investigations Report</u></a>, the human element (including social engineering, phishing, and credential abuse) was involved in 62% of data breaches. Most security incidents don't start with a Hollywood-style hack. They start with a person being tricked.</p>
<p>Developers are especially high-value targets because of what our accounts can touch. Depending on your role and the company you work for, your machine or accounts might have access to:</p>
<ul>
<li>Private repositories and proprietary source code</li>
<li>GitHub, GitLab, or Bitbucket accounts</li>
<li>API keys, access tokens, and local .env files</li>
<li>Cloud infrastructure and production deployment environments</li>
<li>CI/CD pipelines and package publishing permissions (like npm or PyPI)</li>
<li>Internal wikis, issue trackers, and company chat tools</li>
</ul>
<p>Not every developer has access to all of these, of course. A junior dev or a student won't have the same keys as a senior DevOps engineer. Still, even a single compromised developer account can act as a bridge into connected systems, making you a very appealing entry point for an attacker.</p>
<h2 id="heading-five-social-engineering-attacks-developers-should-know-about">Five Social Engineering Attacks Developers Should Know About</h2>
<p>Rather than memorizing cybersecurity definitions, it's much more useful to look at the actual situations where these attacks show up in your day to day life.</p>
<h3 id="heading-1-fake-recruiters-and-malicious-coding-assessments">1. Fake Recruiters and Malicious Coding Assessments</h3>
<p>Job hunting is stressful and attackers know that developers looking for work are eager to make a good impression. In this setup, someone reaches out on LinkedIn, via email, or using a messaging app claiming to represent a tech company or a well-funded startup. After a brief chat, they send you a repository for a technical test and ask you to clone it and run it locally.</p>
<p>The trap is usually hidden inside the project's setup. It might be a malicious postinstall script in<code>package.json</code>, a trojanized dependency, or a compiled binary disguised as a helper tool. The moment you run <code>npm install</code> or the start script, the payload executes on your machine.</p>
<p>Here are some warning signs to watch for:</p>
<ul>
<li>The recruiter pushes you to run an unfamiliar script or executable right away.</li>
<li>The repository has almost no commit history, strange-looking dependencies, or obfuscated code.</li>
<li>The test asks for unnecessary permissions or access to your personal accounts.</li>
<li>They pressure you with a tight, artificial deadline so you don't have time to inspect the files.</li>
<li>You can't independently verify the recruiter's identity or the company's job listing.</li>
</ul>
<p>Luckily, there are a few things you can do to defend yourself. First, never run untrusted code directly on your main development machine. Before you execute anything, read the <code>package.json</code> scripts, check the dependencies, and scan the setup commands. If you do need to test an unfamiliar repo, open it inside an isolated virtual machine or a disposable container.</p>
<p>For example, when you open a project's <code>package.json</code> file, pay attention to the <code>scripts</code> section. You might find something like this:</p>
<pre><code class="language-json">{
  "scripts": {
    "start": "vite",
    "build": "vite build",
    "test": "vitest",
    "postinstall": "node scripts/setup.js"
  }
}
</code></pre>
<p>These scripts define the commands that run during different stages of the project. While <code>start</code>, <code>build</code>, and <code>test</code> are common in JavaScript projects, <code>postinstall</code> deserves a closer look because it runs automatically after dependencies are installed.</p>
<p>This doesn't automatically make it suspicious, but you should open the referenced <code>setup.js</code> file and understand what it does before proceeding. Also, remember that dependencies can have their own installation scripts, so checking your project's <code>package.json</code> is only the first step.</p>
<h3 id="heading-2-fake-freelance-clients-and-project-invitations">2. Fake Freelance Clients and Project Invitations</h3>
<p>If you take on freelance work through platforms, LinkedIn, or developer communities, you're likely to run into a variation of this tactic.</p>
<p>A "client" reaches out with an unusually well-paying project that sounds like a great fit. Before you even agree on a scope or sign a contract, they send over a ZIP archive, a repository link, or a "project requirements" document and ask you to review it or install a specific tool to view their mockups.</p>
<p>Sometimes they go a step further and ask for access to your GitHub account or cloud environment just to "get things set up quickly."</p>
<p>Here are the warning signs to watch for:</p>
<ul>
<li>They dodge basic questions about the project scope but keep insisting you download their files.</li>
<li>They ask for passwords, API tokens, or broad repository permissions before a contract exists.</li>
<li>Their business name, website, or identity is vague and hard to verify.</li>
<li>They use urgency ("we need to launch this week") to rush you past your normal vetting process.</li>
</ul>
<p>To defend yourself, make sure you keep early discussions and file transfers on trusted freelance platforms where accounts are vetted. Never share personal credentials, and if a legitimate client needs repository access later, give them the bare minimum permissions required for the job.</p>
<h3 id="heading-3-impersonation-of-maintainers-teammates-and-managers">3. Impersonation of Maintainers, Teammates, and Managers</h3>
<p>Humans are wired to defer to authority and help people we recognize, a psychological quirk known as authority bias. Attackers exploit this by pretending to be people you already trust. They might pose as an open-source maintainer asking you to test an urgent patch, a teammate asking to be added to a private repo, or a manager messaging you about a production outage that needs an API key right now.</p>
<p>With public profiles and AI tools, it's surprisingly easy for an attacker to copy a colleague's profile photo, mimic their writing style, and clone their email signature.</p>
<p>Here are some warning signs to watch for:</p>
<ul>
<li>An email address or username that's off by a single character (like rn instead of m).</li>
<li>A request that falls completely outside that person's usual role.</li>
<li>Unexpected requests for credentials, tokens, or elevated access.</li>
<li>Pressure to skip regular approval workflows or pull request reviews.</li>
</ul>
<p>To defend yourself, whenever someone asks for sensitive access or credentials, verify the request through a separate, trusted channel. If your "manager" asks for a deployment key on Slack or email, call them on a known number or check in via an established company channel before doing anything.</p>
<h3 id="heading-4-phishing-links-disguised-as-repository-and-package-notifications">4. Phishing Links Disguised as Repository and Package Notifications</h3>
<p>Developers live in a constant stream of notifications: pull requests, CI/CD build failures, security alerts from npm or PyPI, and cloud billing notices hit our inboxes all day long. Attackers blend right in by sending fake alerts that look identical to the real ones.</p>
<p>You might get an email saying a critical vulnerability was found in one of your packages or that a teammate mentioned you in a pull request. Clicking the link takes you to a lookalike login page or worse, a legitimate-looking OAuth screen asking you to authorize a malicious third-party app that will silently gain access to your repositories.</p>
<p>Here are some warning signs to watch for:</p>
<ul>
<li>An unexpected prompt to log in when you're usually already signed in.</li>
<li>Misspelled, hyphenated, or slightly unfamiliar domain names.</li>
<li>Requests to authorize a third-party app with broad read/write permissions.</li>
<li>Emails that create artificial panic about account suspension or broken builds.</li>
</ul>
<p>To defend yourself, don't click links in unexpected notification emails. Instead, open your browser, go to GitHub, npm or your cloud provider directly using a bookmark or by typing the URL yourself and check your notifications there.</p>
<p>For example, imagine a third-party application asking to connect to your GitHub account. It might request permissions such as:</p>
<ul>
<li><code>repo</code>: Grants access to private repositories, including the ability to make changes.</li>
<li><code>workflow</code>: Allows the application to update GitHub Actions workflow files.</li>
<li><code>read:user</code>: Allows it to read basic information from your GitHub profile.</li>
</ul>
<p>If an application only needs to display your public profile but requests access to private repositories and workflow files, something doesn't add up. These permissions go far beyond what the application actually needs.</p>
<p>Before approving an OAuth request, check whether the requested permissions match the application's purpose. If you can't understand why it needs a particular permission, don't approve it. You can also review and revoke previously authorized applications from your GitHub account settings.</p>
<h3 id="heading-5-fake-online-profiles-that-build-trust-over-time">5. Fake Online Profiles That Build Trust Over Time</h3>
<p>Not every social engineering attack happens in a single rushed email. Some attackers play the long game. They build polished LinkedIn or GitHub profiles, join developer Discord servers, comment thoughtfully on your posts, and chat with you about code over weeks or months.</p>
<p>Psychologically, this takes advantage of familiarity and reciprocity, when someone is friendly and engages with your work, your guard naturally drops. Once that rapport is built, they casually drop a link to a "cool side project" they want you to test or send over a file for feedback.</p>
<p>Warning signs to watch for:</p>
<ul>
<li>A profile claiming years of senior experience but showing almost no meaningful code, commits, or real-world interactions.</li>
<li>Work history that doesn't line up when you check the companies they claim to work for.</li>
<li>A quick push to move the conversation off a public platform and into private DMs.</li>
<li>Repeated attempts to get you to download files or grant access to your accounts.</li>
</ul>
<p>To defend yourself, treat familiarity as a nice gesture, not as proof of identity. Even if you've chatted with someone online for a few weeks, still verify their background and inspect anything they ask you to run.</p>
<h2 id="heading-how-to-verify-whether-someone-online-is-actually-who-they-claim-to-be">How to Verify Whether Someone Online Is Actually Who They Claim to Be</h2>
<p>Because so much of software development happens remotely, we regularly collaborate with people we've never met in person.</p>
<p>The most important rule to remember here is simple: a polished profile is not proof of a real identity. Before you trust someone with code, access or sensitive info, run through three quick checks.</p>
<h3 id="heading-check-their-profile-history-and-connections">Check Their Profile History and Connections</h3>
<p>Take two minutes to look past the surface of their profile. Look at how old the account is and whether their activity looks consistent over time. Do their GitHub contributions, repositories, and past roles actually make sense together? Do their connections look like real peers in the industry?</p>
<p>Keep in mind that a brand-new account isn't automatically a scammer and an old account isn't automatically safe. Accounts get bought and hijacked all the time, so look for the overall picture.</p>
<h3 id="heading-confirm-their-identity-through-a-second-channel">Confirm Their Identity Through a Second Channel</h3>
<p>If a request feels even slightly off, step outside the conversation where it started. If a project maintainer messages you on Discord asking for something unusual, reach out to them via their verified GitHub profile or official project email. If a coworker sends a strange email, ping them on your company's internal chat or give them a quick call. Never use the contact details provided inside the suspicious message itself.</p>
<p>For example, suppose someone contacts you on LinkedIn claiming to be a recruiter from Microsoft and sends you a coding assessment. Before downloading anything, visit Microsoft's official careers website and check whether the position exists. You can also look for the recruiter's profile through the company's official employee directory or contact the company through an independently verified email address.</p>
<p>The same approach works when dealing with GitHub maintainers or potential clients. If someone claims to represent an open-source project, check the project's official website or repository to see whether their account is listed as a maintainer. If a client claims to work for a particular company, verify that connection through an independent source rather than relying entirely on the information they provide.</p>
<h3 id="heading-check-whether-their-profile-photo-appears-elsewhere">Check Whether Their Profile Photo Appears Elsewhere</h3>
<p>Another quick check is to see if the person's profile picture actually belongs to them. You can use traditional reverse image search tools like Google Lens to find identical or visually similar copies of a photograph across websites. You can also try a facial recognition-based <a href="https://face2social.com/catfish-reverse-image-search/"><u>catfish reverse image search</u></a> to investigate whether the same person's face appears across different online profiles, even when they use different photographs.</p>
<p>One example of this approach is Face2social, which uses facial recognition to search for potential matches across supported social media platforms. Unlike traditional reverse image search, which looks for identical or visually similar copies of an image, facial recognition-based search can identify potential matches even when someone uses different photographs across their profiles.</p>
<p>Just keep one nuance in mind: finding the same photo attached to multiple unrelated names is a strong red flag, but finding no matches doesn't prove the person is real. Facial recognition tools can also produce inaccurate matches or miss relevant profiles. Think of a catfish reverse image search and facial recognition results as helpful clues during an investigation, not standalone proof of someone's identity. Always cross-check suspicious profiles through other reliable sources before trusting someone online.</p>
<h2 id="heading-practical-ways-you-can-protect-yourself">Practical Ways You Can Protect Yourself</h2>
<p>Spotting individual scams is great, but the real goal is building everyday habits that protect you even when you're tired or distracted.</p>
<h3 id="heading-treat-unfamiliar-code-like-an-untrusted-file">Treat Unfamiliar Code Like an Untrusted File</h3>
<p>Get into the habit of reading before you run. Inspect package.json scripts, Makefiles, and installation commands before typing them into your terminal. Check unfamiliar dependencies to see who maintains them and whether they look legitimate.</p>
<p>When you do need to test untrusted code, use a virtual machine or a container and avoid running things with sudo or admin privileges. Just remember that while containers add a helpful layer of isolation, they aren't a bulletproof security boundary, so stay cautious even inside one.</p>
<h3 id="heading-protect-your-credentials-and-development-accounts">Protect Your Credentials and Development Accounts</h3>
<p>Use a password manager so every development account has a unique, strong password. Turn on multifactor authentication (MFA) everywhere and whenever possible, choose phishing-resistant MFA like hardware security keys or passkeys rather than SMS codes, as recommended in <a href="https://www.cisa.gov/secure-our-world/recognize-and-report-phishing"><u>CISA's guidance on recognizing and reporting phishing</u></a>. Keep API keys and secrets out of your source code, never paste them into chat or issue comments and periodically review your active sessions and authorized third-party apps.</p>
<h3 id="heading-slow-down-when-someone-creates-urgency">Slow Down When Someone Creates Urgency</h3>
<p>Urgency is an attacker's favorite tool because it short-circuits your critical thinking. Whenever a message makes you feel rushed, panicked, or pressured to skip a step, force yourself to pause. Take a breath, verify the request and stick to your regular approval processes even if the message looks like it came from your boss.</p>
<h3 id="heading-keep-your-development-environment-updated">Keep Your Development Environment Updated</h3>
<p>Keep your operating system, browser, IDE, and CLI tools up to date so known bugs can't be chained with a social engineering lure. Turn on automated dependency alerts and secret scanning in your repositories. Following <a href="https://docs.github.com/en/code-security/tutorials/implement-supply-chain-best-practices/securing-code"><u>GitHub's best practices for securing code in your supply chain</u></a> can help you identify vulnerable dependencies and exposed secrets before they become bigger security problems.</p>
<h2 id="heading-what-should-you-do-if-you-think-youve-been-targeted">What Should You Do If You Think You've Been Targeted?</h2>
<p>Even careful developers slip up sometimes. If you realize you just clicked a bad link or ran a suspicious script, don't panic. Just act methodically.</p>
<h3 id="heading-stop-and-dont-interact-further">Stop and Don't Interact Further</h3>
<p>Cut off contact with the suspicious account immediately. Don't click any more links, open attachments, or run any further commands. Resist the urge to delete the messages or files right away, though. If your company's security team needs to investigate what happened, those artifacts will be valuable.</p>
<h3 id="heading-secure-your-accounts-and-development-environment">Secure Your Accounts and Development Environment</h3>
<p>Your next steps depend on what was exposed. If you typed your password into a fake login page, change that password immediately from a separate, trusted device and revoke any active sessions or suspicious OAuth apps.</p>
<p>If API keys or personal access tokens were exposed, revoke and rotate them right away (as simply changing your account password won't invalidate a leaked token).</p>
<p>If you actually executed malicious code, disconnect that machine from the internet if possible, alert your security team and check your repositories and cloud accounts for unauthorized commits or deployments.</p>
<h3 id="heading-report-the-incident">Report the Incident</h3>
<p>Let the right people know as soon as possible. Report the incident to your company's IT or security team, flag the fake account through the platform's abuse channel (like LinkedIn, GitHub or Discord), or notify the relevant open-source maintainers if it affects a community project.</p>
<p>Speaking up early is nothing to be embarrassed about. It's often what stops a small mistake from turning into a major breach.</p>
<h2 id="heading-quick-security-checklist-every-developer-should-follow">Quick Security Checklist Every Developer Should Follow</h2>
<p>You don't need to become a cybersecurity expert to avoid most social engineering traps. Start with these basic habits and make them part of your everyday development routine:</p>
<ul>
<li>Verify recruiters, clients, maintainers, and teammates before trusting unusual requests.</li>
<li>Inspect unfamiliar repositories, scripts, and dependencies before running their code.</li>
<li>Avoid clicking unexpected login links in emails or chat messages. Navigate to the site directly.</li>
<li>Use unique passwords and phishing-resistant MFA on all development accounts.</li>
<li>Never share API keys, passwords, or access tokens over chat, email, or issue trackers.</li>
<li>Regularly review your repository permissions and authorized third-party OAuth apps.</li>
<li>Use isolated environments like virtual machines or containers to test unfamiliar projects.</li>
<li>Report suspicious messages and unexpected account activity right away.</li>
</ul>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>We put a huge amount of effort into securing our applications, locking down our repositories, and hardening our infrastructure. That work matters and it keeps automated attacks at bay. But at the end of the day, attackers know that the people who build and maintain those systems are often the easiest way in.</p>
<p>Staying safe as a developer doesn't mean that you need to be paranoid. You just need to be deliberate. When you treat unexpected requests with the same healthy skepticism you bring to a messy pull request, you close off one of the biggest security gaps in modern software development.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Standardize Healthcare Data Using OMOP CDM and PySpark ]]>
                </title>
                <description>
                    <![CDATA[ Healthcare data comes from various systems like electronic health records (EHRs), laboratory systems, pharmacies, medical imaging systems, and billing applications. And each system may use different d ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-standardize-healthcare-data-using-omop-cdm-and-pyspark/</link>
                <guid isPermaLink="false">6b0ef9214de318dc98dd0ba7</guid>
                
                    <category>
                        <![CDATA[ healthcaredata ]]>
                    </category>
                
                    <category>
                        <![CDATA[ omop ]]>
                    </category>
                
                    <category>
                        <![CDATA[ PySpark ]]>
                    </category>
                
                    <category>
                        <![CDATA[ dataengineering ]]>
                    </category>
                
                    <category>
                        <![CDATA[ HealthcareAI ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Data standardization ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Lakshmi Mahabaleshwara ]]>
                </dc:creator>
                <pubDate>Tue, 01 Dec 2026 16:43:13 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/91984fb5-8e94-42ee-99ec-d90ab9bd974c.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Healthcare data comes from various systems like electronic health records (EHRs), laboratory systems, pharmacies, medical imaging systems, and billing applications. And each system may use different data structures, naming conventions, and clinical coding standards.</p>
<p>For example, consider two hospitals storing information about patients diagnosed with type 2 diabetes.</p>
<table>
<thead>
<tr>
<th>Hospital A</th>
<th>Hospital B</th>
</tr>
</thead>
<tbody><tr>
<td>patient_id</td>
<td>patient_number</td>
</tr>
<tr>
<td>diagnosis_date</td>
<td>condition_start_date</td>
</tr>
<tr>
<td>diagnosis_code</td>
<td>clinical_code</td>
</tr>
<tr>
<td>E11.9 (ICD-10-CM)</td>
<td>44054006 (SNOMED CT)</td>
</tr>
</tbody></table>
<p>How do we combine data from these hospitals to conduct clinical research or build healthcare AI applications?</p>
<p>The Observational Medical Outcomes Partnership Common Data Model (OMOP CDM) addresses this problem by providing a common structure and standardized clinical vocabularies.</p>
<p>In this tutorial, we'll build an ETL pipeline using PySpark to transform synthetic healthcare data into OMOP CDM tables, validate the transformed data, and perform clinical analytics.</p>
<p>We'll use the synthetic healthcare dataset generated in my previous freeCodeCamp tutorial, <a href="https://www.freecodecamp.org/news/how-to-generate-synthetic-healthcare-data-using-synthea-a-hands-on-tutorial">How to Generate Synthetic Healthcare Data Using Synthea – A Hands-On Tutorial</a>. If you haven't generated the dataset yet, I recommend following that tutorial before proceeding.</p>
<p>You can follow along with the accompanying <a href="https://github.com/lakshmi-mahabaleshwara/healthtech-playground/blob/main/omop-cdm/synthea_to_omop.ipynb">Jupyter notebook</a>, which contains the complete implementation.</p>
<h3 id="heading-what-well-cover">What We'll Cover:</h3>
<ul>
<li><a href="#heading-prerequisites">Prerequisites</a></li>
<li><a href="#heading-what-is-omop-cdm">What is OMOP CDM?</a><ul>
<li><a href="#heading-structural-standardization">Structural Standardization</a></li>
<li><a href="#heading-semantic-standardization">Semantic Standardization</a></li>
</ul>
</li>
<li><a href="#heading-understanding-the-omop-common-data-model">Understanding the OMOP Common Data Model</a><ul>
<li><a href="#heading-what-are-clinical-vocabularies-and-athena">What Are Clinical Vocabularies and ATHENA?</a></li>
<li><a href="#heading-how-to-download-omop-standardized-vocabularies-from-athena">How to Download OMOP Standardized Vocabularies from ATHENA</a></li>
</ul>
</li>
<li><a href="#heading-how-to-build-the-healthcare-data-standardization-pipeline">How to Build the Healthcare Data Standardization Pipeline</a><ul>
<li><a href="#heading-step-1-set-up-the-development-environment">Step 1: Set Up the Development Environment</a></li>
<li><a href="#heading-step-2-load-and-explore-the-synthea-dataset">Step 2: Load and Explore the Synthea Dataset</a></li>
<li><a href="#heading-step-3-load-the-omop-standardized-vocabularies">Step 3: Load the OMOP Standardized Vocabularies</a></li>
<li><a href="#heading-step-4-map-clinical-codes-to-omop-standard-concepts">Step 4: Map Clinical Codes to OMOP Standard Concepts</a></li>
<li><a href="#heading-step-5-how-to-transform-patient-data-into-the-person-table">Step 5: How to Transform Patient Data into the PERSON Table</a></li>
<li><a href="#heading-step-6-transform-the-remaining-clinical-tables">Step 6: Transform the Remaining Clinical Tables</a></li>
<li><a href="#heading-step-7-how-to-validate-the-standardized-healthcare-data">Step 7: How to Validate the Standardized Healthcare Data</a></li>
<li><a href="#heading-step-8-how-to-save-the-omop-tables-in-parquet-format">Step 8: How to Save the OMOP Tables in Parquet Format</a></li>
<li><a href="#heading-step-9-how-to-perform-clinical-analytics-using-omop-cdm">Step 9: How to Perform Clinical Analytics Using OMOP CDM</a></li>
</ul>
</li>
<li><a href="#heading-conclusion">Conclusion</a></li>
<li><a href="#heading-references-for-the-article">References for the article</a></li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To follow along with this tutorial, you should have a basic understanding of Python, SQL, and DataFrame operations. We'll use Synthea, OMOP CDM v5.4, OHDSI ATHENA, PySpark, and Jupyter Notebook.</p>
<p>The entire pipeline runs locally, so you don't need access to real patient data or cloud infrastructure.</p>
<h2 id="heading-what-is-omop-cdm">What is OMOP CDM?</h2>
<p>OMOP CDM stands for <strong>Observational Medical Outcomes Partnership Common Data Model</strong>. It's an open data model maintained by the Observational Health Data Sciences and Informatics (OHDSI) community.</p>
<p>It enables healthcare data from different sources to be represented consistently for clinical research and analytics.</p>
<p>OMOP addresses two types of data standardization: structural and semantic.</p>
<h3 id="heading-structural-standardization">Structural Standardization</h3>
<p>Different healthcare systems may store patient information using different table names, column names, and data types. OMOP provides a common structure for representing this information.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69fd77e89f93a850a46d376f/d0f37893-3aca-4e70-bec4-63c0dda563b9.png" alt="Two hospitals with different patient table structures and column names are mapped to a common OMOP CDM PERSON table, standardizing patient identifiers and birth date fields." style="display: block;" width="600" height="400" loading="lazy">

<p>Regardless of the source structure, the transformed data follows a common model.</p>
<h3 id="heading-semantic-standardization">Semantic Standardization</h3>
<p>Having the same table structure isn't enough if hospitals use different clinical codes to represent the same medical condition. OMOP uses standardized vocabularies to ensure that clinical information can be interpreted consistently across systems. This process is known as semantic standardization.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69fd77e89f93a850a46d376f/217d20c4-2e6d-4afd-9d26-44825294dc39.png" alt="Clinical codes for type 2 diabetes from two hospitals using ICD-10-CM and SNOMED CT are mapped through OMOP standardized vocabularies to a common concept ID in the CONDITION_OCCURRENCE table." style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-understanding-the-omop-common-data-model">Understanding the OMOP Common Data Model</h2>
<p>OMOP CDM organizes healthcare data into several categories, including clinical data, healthcare system data, health economics, standardized vocabularies, and metadata.</p>
<p>For this tutorial, we'll focus primarily on clinical data.</p>
<table>
<thead>
<tr>
<th>OMOP Table</th>
<th>Description</th>
</tr>
</thead>
<tbody><tr>
<td><code>PERSON</code></td>
<td>Patient demographic information</td>
</tr>
<tr>
<td><code>VISIT_OCCURRENCE</code></td>
<td>Healthcare encounters, such as hospital admissions and outpatient visits</td>
</tr>
<tr>
<td><code>CONDITION_OCCURRENCE</code></td>
<td>Diseases, diagnoses, signs and symptoms</td>
</tr>
<tr>
<td><code>DRUG_EXPOSURE</code></td>
<td>Medications prescribed or administered</td>
</tr>
<tr>
<td><code>PROCEDURE_OCCURRENCE</code></td>
<td>Medical and surgical procedures</td>
</tr>
<tr>
<td><code>MEASUREMENT</code></td>
<td>Laboratory results, vital signs, and other measurements</td>
</tr>
<tr>
<td><code>OBSERVATION</code></td>
<td>Other clinical facts, such as smoking status or family history</td>
</tr>
<tr>
<td><code>OBSERVATION_PERIOD</code></td>
<td>Periods during which patient events can be captured</td>
</tr>
</tbody></table>
<p>These tables are connected through identifiers such as <code>person_id</code> and <code>visit_occurrence_id</code>, allowing us to connect a patient's encounters, diagnoses, medications, and laboratory results.</p>
<p>You can explore the complete data model in the official <a href="https://ohdsi.github.io/CommonDataModel/cdm54.html">OMOP CDM v5.4 documentation</a>.</p>
<h3 id="heading-what-are-clinical-vocabularies-and-athena">What Are Clinical Vocabularies and ATHENA?</h3>
<p>A clinical vocabulary is a standardized collection of medical terms and codes used to represent healthcare information.</p>
<p>Some commonly used clinical vocabularies include SNOMED CT for diagnoses and clinical findings, LOINC for laboratory tests, RxNorm for medications, and UCUM for measurement units.</p>
<p>OMOP brings these vocabularies together and assigns each concept a unique identifier called <code>concept_id</code>.</p>
<p><a href="https://athena.ohdsi.org">ATHENA</a> is OHDSI's platform for exploring and downloading these standardized vocabularies. We'll use the downloaded vocabulary files as reference data in our ETL pipeline.</p>
<h3 id="heading-how-to-download-omop-standardized-vocabularies-from-athena">How to Download OMOP Standardized Vocabularies from ATHENA</h3>
<p>Create an account on <a href="https://athena.ohdsi.org">ATHENA</a>, and navigate to the vocabulary download section.</p>
<ol>
<li>Select SNOMED CT, LOINC, RxNorm, RxNorm Extension, UCUM, and the supporting vocabularies for demographics, visit types, and clinical record types.</li>
<li>Create a bundle named <code>synthea_omop_vocabulary</code>. For this tutorial, I'm using release <code>v20260829</code>. Leave the Delta from Older Version option unchecked to download the complete bundle.</li>
<li>Once downloaded, extract the ZIP file. We'll primarily use <code>CONCEPT.csv</code>, which contains clinical concepts, and <code>CONCEPT_RELATIONSHIP.csv</code>, which contains relationships and mappings between concepts.</li>
</ol>
<p>Although these files have a <code>.csv</code> extension, they're tab-separated.</p>
<p><strong>Note</strong>: Due to vocabulary-specific licensing restrictions, the downloaded vocabulary files aren't included in the GitHub repository. Download them directly from ATHENA after accepting the applicable licensing terms.</p>
<h2 id="heading-how-to-build-the-healthcare-data-standardization-pipeline">How to Build the Healthcare Data Standardization Pipeline</h2>
<p>Now that you understand OMOP CDM and have downloaded the standardized vocabularies, let's build our ETL pipeline using PySpark.</p>
<p>The pipeline has four main stages, as shown below: ingestion, transformation, validation, and storage.</p>
<h3 id="heading-step-1-set-up-the-development-environment">Step 1: Set Up the Development Environment</h3>
<p>Create the following directory structure:</p>
<pre><code class="language-plaintext">omop-cdm/
├── synthea_to_omop.ipynb
├── requirements.txt
├── .gitignore
└── data/
    ├── synthea/
    ├── vocabulary/
    └── omop/
</code></pre>
<p>The <code>synthea</code> directory contains the source healthcare data, the <code>vocabulary</code> directory contains the downloaded OMOP standardized vocabularies, and the <code>omop</code> directory will contain the transformed healthcare data.</p>
<p>Ensure that Python and a compatible Java version are installed on your machine. Install the required dependencies:</p>
<pre><code class="language-python">python -m pip install notebook pyspark pandas matplotlib
</code></pre>
<p>Launch Jupyter Notebook:</p>
<pre><code class="language-python">jupyter notebook
</code></pre>
<p>Let's start by initializing a Spark session.</p>
<pre><code class="language-python">from pyspark.sql import SparkSession
from pyspark.sql import functions as F
from pathlib import Path

spark = (
    SparkSession.builder
    .appName("SyntheaToOMOP")
    .master("local[*]")
    .getOrCreate()
)

spark
</code></pre>
<p>Define the paths for our source data, vocabulary files, and transformed data.</p>
<pre><code class="language-python">DATA_DIR = Path("data")

SYNTHEA_DIR = DATA_DIR / "synthea"
VOCABULARY_DIR = DATA_DIR / "vocabulary"
OMOP_DIR = DATA_DIR / "omop"
</code></pre>
<h3 id="heading-step-2-load-and-explore-the-synthea-dataset">Step 2: Load and Explore the Synthea Dataset</h3>
<p>Copy the CSV files generated using Synthea into the <code>data/synthea/</code> directory. For this tutorial, we'll work with six source tables: <strong>patients, encounters, conditions, medications, procedures,</strong> and <strong>observations.</strong></p>
<p>Let's load these files into PySpark DataFrames.</p>
<pre><code class="language-python">source_tables = [
    "patients",
    "encounters",
    "conditions",
    "medications",
    "procedures",
    "observations"
]

synthea = {}

for table in source_tables:
    synthea[table] = (
        spark.read
        .option("header", True)
        .csv(str(SYNTHEA_DIR / f"{table}.csv"))
    )
</code></pre>
<p>We initially load the CSV columns as strings. This helps preserve clinical codes and identifiers without losing leading zeros or introducing unintended type conversions.</p>
<p>Let's check the number of records in each table.</p>
<pre><code class="language-python">for table, df in synthea.items():
    print(f"{table}: {df.count():,} records")
</code></pre>
<p>The record counts may vary depending on the synthetic dataset used.</p>
<p>Let's explore the patient data.</p>
<pre><code class="language-python">synthea["patients"].printSchema()

synthea["patients"].select(
    "Id",
    "BIRTHDATE",
    "GENDER",
    "RACE",
    "ETHNICITY"
).show(5, truncate=False)
</code></pre>
<p>Similarly, let's examine the conditions table.</p>
<pre><code class="language-python">synthea["conditions"].select(
    "PATIENT",
    "START",
    "CODE",
    "DESCRIPTION"
).show(5, truncate=False)
</code></pre>
<p>Notice that each condition has a clinical code and a description. In the following sections, we'll use OMOP standardized vocabularies to map these clinical codes to standard concept IDs.</p>
<h3 id="heading-step-3-load-the-omop-standardized-vocabularies">Step 3: Load the OMOP Standardized Vocabularies</h3>
<p>Now that we've loaded the Synthea dataset, let's load the standardized vocabulary files downloaded from ATHENA.</p>
<p>For our transformation, we'll primarily use two vocabulary tables:</p>
<ul>
<li>CONCEPT: Contains clinical codes, concept identifiers, vocabulary names, and clinical domains.</li>
<li>CONCEPT_RELATIONSHIP: Contains relationships between clinical concepts, including mappings from source concepts to standard concepts. Since the ATHENA vocabulary files are tab separated, we specify <code>\t</code> as the delimiter when loading them into PySpark.</li>
</ul>
<pre><code class="language-python">concept = (
    spark.read
    .option("header", True)
    .option("sep", "\t")
    .csv(str(VOCABULARY_DIR / "CONCEPT.csv"))
    .withColumn("concept_id", F.col("concept_id").cast("int"))
)

concept_relationship = (
    spark.read
    .option("header", True)
    .option("sep", "\t")
    .csv(str(VOCABULARY_DIR / "CONCEPT_RELATIONSHIP.csv"))
    .withColumn("concept_id_1", F.col("concept_id_1").cast("int"))
    .withColumn("concept_id_2", F.col("concept_id_2").cast("int"))
)
</code></pre>
<p>Let's explore a few records from the <code>CONCEPT</code> table.</p>
<pre><code class="language-python">concept.select(
    "concept_id",
    "concept_name",
    "domain_id",
    "vocabulary_id",
    "concept_code",
    "standard_concept"
).show(5, truncate=False)
</code></pre>
<p>Now that we have loaded both the source healthcare data and the standardized vocabularies, let's see how we can map clinical codes from Synthea to OMOP standard concepts.</p>
<h3 id="heading-step-4-map-clinical-codes-to-omop-standard-concepts">Step 4: Map Clinical Codes to OMOP Standard Concepts</h3>
<p>One of the most important steps in our healthcare data standardization pipeline is clinical vocabulary mapping.</p>
<p>For example, Synthea represents type 2 diabetes mellitus using the SNOMED CT code <code>44054006</code>. OMOP CDM represents the same clinical concept using a unique concept identifier.</p>
<p>Let's look up this clinical code in the <code>CONCEPT</code> table.</p>
<pre><code class="language-python">concept.filter(
    (F.col("vocabulary_id") == "SNOMED") &amp;
    (F.col("concept_code") == "44054006")
).select(
    "concept_id",
    "concept_name",
    "domain_id",
    "standard_concept"
).show(truncate=False)
</code></pre>
<p>The corresponding concept is:</p>
<table>
<thead>
<tr>
<th>Attribute</th>
<th>Value</th>
</tr>
</thead>
<tbody><tr>
<td>concept_id</td>
<td>201826</td>
</tr>
<tr>
<td>concept_name</td>
<td>Type 2 diabetes mellitus</td>
</tr>
<tr>
<td>domain_id</td>
<td>Condition</td>
</tr>
<tr>
<td>standard_concept</td>
<td>S</td>
</tr>
</tbody></table>
<p>Here, <code>S</code> indicates that the concept is already a standard OMOP concept.</p>
<p>But not every clinical code maps directly to a standard concept. Some source concepts belong to non-standard vocabularies and need to be mapped using the <code>CONCEPT_RELATIONSHIP</code> table.</p>
<h4 id="heading-understanding-the-maps-to-relationship">Understanding the "Maps to" Relationship</h4>
<p>OMOP uses a relationship called <code>Maps to</code> to associate source concepts with their corresponding standard concepts.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69fd77e89f93a850a46d376f/b27c76a7-21be-464e-be7c-eb4c0df79118.png" alt="Flowchart showing how source clinical codes are mapped to OMOP standard concept IDs using the CONCEPT and CONCEPT_RELATIONSHIP tables, with the mapped concept's clinical domain determining the target OMOP table." style="display: block;" width="600" height="400" loading="lazy">

<p>Let's identify valid standard concepts.</p>
<pre><code class="language-python">standard = concept.filter(
    (F.col("standard_concept") == "S") &amp;
    (
        F.col("invalid_reason").isNull() |
        (F.col("invalid_reason") == "")
    )
)
</code></pre>
<p>Next, extract valid <code>Maps to</code> relationships.</p>
<pre><code class="language-python">links = concept_relationship.filter(
    (F.col("relationship_id") == "Maps to") &amp;
    (
        F.col("invalid_reason").isNull() |
        (F.col("invalid_reason") == "")
    )
)
</code></pre>
<p>Using these DataFrames, we create a reusable vocabulary lookup that maps source clinical codes to their corresponding standard concept IDs and clinical domains.</p>
<p>The complete lookup implementation is available in the accompanying Jupyter notebook.</p>
<p>Once the lookup is created, we can reuse it across different clinical tables.</p>
<pre><code class="language-python">def map_codes(df):
    return (
        df.join(
            lookup,
            ["vocab", "code"],
            "left"
        )
        .fillna(
            0,
            subset=[
                "source_concept_id",
                "standard_id"
            ]
        )
    )
</code></pre>
<p>When a clinical code can't be mapped, we assign a concept ID of <code>0</code>, indicating that no matching concept has been identified. These records should be tracked for further review.</p>
<p>Now that we have a reusable mechanism for clinical vocabulary mapping, let's start transforming our Synthea healthcare data into OMOP CDM tables, beginning with the <code>PERSON</code> table.</p>
<h3 id="heading-step-5-how-to-transform-patient-data-into-the-person-table">Step 5: How to Transform Patient Data into the PERSON Table</h3>
<p>The <code>PERSON</code> table is the central clinical table in OMOP CDM. It contains demographic information about patients whose healthcare records are represented in the dataset.</p>
<p>Every patient is assigned a unique <code>person_id</code>, which is referenced by other clinical tables.</p>
<p>Synthea represents patient identifiers using UUIDs. OMOP CDM uses integer identifiers. So we need to create a mapping between the original patient identifier and the standardized OMOP patient identifier. This mapping is often referred to as an <strong>identity crosswalk.</strong></p>
<p>Let's create the patient identity crosswalk using PySpark.</p>
<pre><code class="language-python">from pyspark.sql import Window

patients = synthea["patients"]

patient_mapping = (
    patients
    .select("Id")
    .distinct()
    .withColumn(
        "person_id",
        F.row_number().over(
            Window.orderBy("Id")
        )
    )
)
</code></pre>
<p>We'll reuse this mapping when transforming encounters, diagnoses, procedures, medications, and observations.</p>
<p>For this tutorial, sorted row numbers are sufficient because we're processing a fixed dataset. In a production pipeline, the identifier mapping should be persisted so that existing patient identifiers remain stable when new records are added.</p>
<p><strong>Source-to-Target Mapping</strong></p>
<p>Before transforming the data, let's understand how Synthea patient attributes map to OMOP attributes.</p>
<table>
<thead>
<tr>
<th>Synthea column</th>
<th>OMOP column</th>
<th>Transformation</th>
</tr>
</thead>
<tbody><tr>
<td>ID</td>
<td>person_id</td>
<td>Integer identifier mapping</td>
</tr>
<tr>
<td>ID</td>
<td>person_source_value</td>
<td>Preserve source identifier</td>
</tr>
<tr>
<td>BIRTHDATE</td>
<td>year_of_birth</td>
<td>Extract year</td>
</tr>
<tr>
<td>BIRTHDATE</td>
<td>month_of_birth</td>
<td>Extract month</td>
</tr>
<tr>
<td>BIRTHDATE</td>
<td>day_of_birth</td>
<td>Extract day</td>
</tr>
<tr>
<td>GENDER</td>
<td>gender_concept_id</td>
<td>Concept mapping</td>
</tr>
<tr>
<td>RACE</td>
<td>race_concept_id</td>
<td>Concept mapping</td>
</tr>
<tr>
<td>ETHNICITY</td>
<td>ethnicity_concept_id</td>
<td>Concept mapping</td>
</tr>
</tbody></table>
<p>This process of defining how source columns are transformed into target columns is known as source-to-target mapping.</p>
<p>The following code demonstrates the structural transformation of patient identifiers and birth dates.</p>
<pre><code class="language-python">person_demo = (
    patients
    .join(patient_mapping, "Id")
    .withColumn(
        "birth_date",
        F.to_date("BIRTHDATE")
    )
    .select(
        "person_id",
        F.year("birth_date").alias("year_of_birth"),
        F.month("birth_date").alias("month_of_birth"),
        F.dayofmonth("birth_date").alias("day_of_birth"),
        F.col("Id").alias("person_source_value")
    )
)

person_demo.show(5, truncate=False)
</code></pre>
<h3 id="heading-step-6-transform-the-remaining-clinical-tables">Step 6: Transform the Remaining Clinical Tables</h3>
<p>We can follow a similar approach to transform the remaining Synthea tables into OMOP CDM tables.</p>
<p>The following table summarizes the source-to-target mappings for our pipeline.</p>
<table>
<thead>
<tr>
<th>Synthea Source Table</th>
<th>OMOP Target Table</th>
</tr>
</thead>
<tbody><tr>
<td>encounters.csv</td>
<td>VISIT_OCCURRENCE</td>
</tr>
<tr>
<td>conditions.csv</td>
<td>CONDITION_OCCURRENCE</td>
</tr>
<tr>
<td>medications.csv</td>
<td>DRUG_EXPOSURE</td>
</tr>
<tr>
<td>procedures.csv</td>
<td>PROCEDURE_OCCURRENCE</td>
</tr>
<tr>
<td>observations.csv</td>
<td>MEASUREMENT</td>
</tr>
<tr>
<td>observations.csv</td>
<td>OBSERVATION</td>
</tr>
<tr>
<td>Patient visit and clinical event history</td>
<td>OBSERVATION_PERIOD</td>
</tr>
</tbody></table>
<p>For each transformation, we follow a similar approach:</p>
<ul>
<li>Define the source-to-target column mappings.</li>
<li>Map patient and encounter identifiers to maintain relationships across tables.</li>
<li>Map source clinical codes to OMOP standard concepts.</li>
<li>Identify the appropriate target table based on the clinical domain.</li>
<li>Transform column names, data types, and values according to the OMOP CDM specification.</li>
<li>Preserve original source values for traceability.</li>
</ul>
<p>The complete implementation is available in the accompanying <a href="https://github.com/lakshmi-mahabaleshwara/healthtech-playground/blob/main/omop-cdm/synthea_to_omop.ipynb">Jupyter notebook</a>.</p>
<h4 id="heading-understanding-clinical-domain-distribution">Understanding Clinical Domain Distribution</h4>
<p>One aspect of OMOP CDM is that a single source table can map to multiple target tables.</p>
<p>For example, Synthea stores laboratory results, vital signs, and other clinical findings in <code>observations.csv</code>. OMOP separates these records based on their clinical meaning.</p>
<p>The <code>MEASUREMENT</code> table captures results such as blood glucose, blood pressure, and body mass index, while the <code>OBSERVATION</code> table captures other clinical facts, such as family and social history.</p>
<p>We determine the target table using the <code>domain_id</code> of the mapped standard concept.</p>
<p>The following chart shows the clinical domain distribution obtained after running vocabulary mapping on our Synthea dataset.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69fd77e89f93a850a46d376f/894ff378-e893-4549-a2bf-4974e14a4484.png" alt="Stacked horizontal bar chart showing the percentage distribution of OMOP clinical domains across Synthea source tables, highlighting how conditions, procedures, and observations map to multiple clinical domains, while medications map entirely to the Drug domain." style="display: block;" width="600" height="400" loading="lazy">

<p>Records from <code>procedures.csv</code> are distributed across several domains, including Procedure, Measurement, and Observation.</p>
<p>This is why healthcare data standardization is more than a one-to-one table transformation. The clinical meaning of each record determines where it belongs in the standardized data model.</p>
<p>Unmapped concepts and records belonging to unsupported domains are captured separately for further review. Since a source record may map to multiple standard concepts, these distributions represent mapped rows instead of unique source records.</p>
<h3 id="heading-step-7-how-to-validate-the-standardized-healthcare-data">Step 7: How to Validate the Standardized Healthcare Data</h3>
<p>Before saving the transformed data, we need to verify that it follows the expected OMOP structure and maintains relationships between clinical records.</p>
<p>Our pipeline performs the following data quality checks:</p>
<ul>
<li><strong>Primary key uniqueness</strong>: Ensures that identifiers are unique.</li>
<li><strong>Referential integrity</strong>: Verifies that clinical records reference valid patients and encounters.</li>
<li><strong>Vocabulary validation</strong>: Ensures that mapped concepts belong to the appropriate clinical domains.</li>
<li><strong>Temporal validation</strong>: Checks for inconsistent clinical dates.</li>
<li><strong>Data reconciliation</strong>: Tracks successfully transformed and unmapped records.</li>
</ul>
<p>For example, we can verify that every patient has a unique <code>person_id</code>.</p>
<pre><code class="language-python">duplicate_patients = (
    person.groupBy("person_id")
    .count()
    .filter(F.col("count") &gt; 1)
)

assert duplicate_patients.count() == 0
</code></pre>
<p>Similarly, a left anti join helps us identify condition records that don't reference a valid patient.</p>
<pre><code class="language-python">orphan_conditions = condition_occurrence.join(
    person.select("person_id"),
    "person_id",
    "left_anti"
)

assert orphan_conditions.count() == 0
</code></pre>
<p>The remaining validation checks are implemented in the accompanying Jupyter notebook.</p>
<h3 id="heading-step-8-how-to-save-the-omop-tables-in-parquet-format">Step 8: How to Save the OMOP Tables in Parquet Format</h3>
<p>Once the validation checks pass, we can save the transformed OMOP tables in Parquet format for downstream analytics.</p>
<p>Apache Parquet is an open-source, columnar file format designed for efficient data storage and analytical processing.</p>
<p>Imagine a healthcare dataset with patient IDs, birth dates, diagnoses, and medications. Parquet stores data column by column, like organizing information into separate folders by category.</p>
<p>If we only need to analyze patient diagnoses, Parquet allows us to read the relevant columns without reading the entire dataset. This reduces the amount of data processed and improves query performance. Parquet also supports efficient data compression, reducing storage requirements.</p>
<p>To learn more about how Parquet works and its benefits, refer to my article <a href="https://coderlegion.com/30266/understanding-parquet-file-format">Understanding the Parquet File Format</a>.</p>
<pre><code class="language-python">for table_name, df in omop_tables.items():
    df.write.mode("overwrite").parquet(
        f"data/omop/{table_name}"
    )
</code></pre>
<p>Each OMOP table is stored in a separate directory and can be loaded independently without rerunning the ETL pipeline.</p>
<pre><code class="language-python">person = spark.read.parquet("data/omop/person")
</code></pre>
<h3 id="heading-step-9-how-to-perform-clinical-analytics-using-omop-cdm">Step 9: How to Perform Clinical Analytics Using OMOP CDM</h3>
<p>Now that our healthcare data follows a common structure and uses standardized concepts, we can query it using Spark SQL.</p>
<p>Let's identify the most frequently recorded conditions based on the number of unique patients.</p>
<pre><code class="language-python">for table_name, df in omop_tables.items():
    df.createOrReplaceTempView(table_name)

concept.createOrReplaceTempView("concept")

spark.sql("""
    SELECT
        c.concept_name,
        COUNT(DISTINCT co.person_id) AS patient_count
    FROM condition_occurrence co
    JOIN concept c
        ON co.condition_concept_id = c.concept_id
    GROUP BY
        c.concept_id,
        c.concept_name
    ORDER BY patient_count DESC
    LIMIT 10
""").show(truncate=False)
</code></pre>
<p>The query returns the most frequently recorded standardized conditions based on the number of unique patients.</p>
<p>If another hospital transforms its data into the same OMOP model, we can reuse this query without changing it to accommodate the original source schema. This is one of the key benefits of healthcare data standardization.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, we built a healthcare data standardization pipeline using Synthea, OMOP CDM, ATHENA, and PySpark. We explored clinical vocabulary mapping, transformed healthcare records into standardized OMOP tables, and validated the resulting data.</p>
<p>While we used synthetic data, the same principles apply when integrating data from real-world healthcare systems. Production implementations require additional considerations such as local clinical codes, missing data, patient privacy, and more comprehensive validation.</p>
<p>I hope this tutorial helps you get started with healthcare data standardization and understand how OMOP CDM can provide a foundation for clinical research, healthcare analytics, and AI applications.</p>
<h2 id="heading-references-for-the-article">References for the article</h2>
<ul>
<li><a href="https://ohdsi.github.io/CommonDataModel/cdm54.html">OMOP CDM v5.4 Documentation</a></li>
<li><a href="https://ohdsi.github.io/TheBookOfOhdsi">The Book of OHDSI</a></li>
<li><a href="https://athena.ohdsi.org">OHDSI ATHENA</a></li>
<li><a href="https://github.com/synthetichealth/synthea">Synthea</a></li>
<li><a href="https://github.com/OHDSI/ETL-Synthea">OHDSI ETL-Synthea Reference Implementation</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn Cybersecurity for Back End Developers ]]>
                </title>
                <description>
                    <![CDATA[ STRIDE is a checklist for spotting what could go wrong in an application at design time, and the OWASP Top 10 is a shared list of the web vulnerabilities that developers most often release into live a ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-cybersecurity-for-back-end-developers/</link>
                <guid isPermaLink="false">6b0eec38d8ddb3a3496c77d9</guid>
                
                    <category>
                        <![CDATA[ cybersecurity ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Tue, 01 Dec 2026 15:48:08 +0000</pubDate>
                <media:content url="https://i.ytimg.com/vi/aFfeYlz90vw/maxresdefault.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>STRIDE is a checklist for spotting what could go wrong in an application at design time, and the OWASP Top 10 is a shared list of the web vulnerabilities that developers most often release into live apps.</p>
<p>We just published a 5-hour course on the freeCodeCamp.org YouTube channel that will teach you how to find and fix common security flaws in back end code with Node.js. The course is taught by Jonathan Hill, software engineer and Scrimba instructor, and Rachel Johnson, developer and Scrimba course creator.</p>
<p>It starts with a quick exploit: you edit a URL parameter in a supermarket freezer dashboard to raise the temperature of another store's freezer, then look at the Express code to close the hole. You can also study the course interactively on Scrimba.</p>
<p>In this course, you will learn:</p>
<ul>
<li><strong>Threat Modeling with STRIDE &amp; OWASP</strong><br>How to model potential and feature-based threats for an example app, then triage bugs using the OWASP Top 10 categories.</li>
<li><strong>XSS, SQL Injection &amp; Denial of Service</strong><br>How attackers insert malicious code and manipulate database queries through input fields, and how they can overwhelm your application.</li>
<li><strong>Input Validation with Zod</strong><br>How to build Zod schemas, use safeParse and coerce, handle validation errors, and write validation middleware.</li>
<li><strong>Sessions, Tokens &amp; OAuth</strong><br>How stateful sessions and cookies, stateless opaque bearer tokens and JSON Web Tokens (JWT), and delegated OAuth work, and the pitfalls of each.</li>
<li><strong>Rate Limiting Algorithms</strong><br>How to build fixed window counter, sliding window, token bucket, and leaky bucket limiters, and identify clients by IP address, user ID, or API key.</li>
<li><strong>Throttling</strong><br>How to set up throttling middleware, configure delay times, and combine throttling with a rate limiter.</li>
</ul>
<p>Watch the full course on the <a href="https://youtu.be/aFfeYlz90vw">freeCodeCamp.org YouTube channel</a> (5-hour watch).</p>
<div class="embed-wrapper"><iframe width="560" height="315" src="https://www.youtube.com/embed/aFfeYlz90vw" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Secure Password Generator with Python ]]>
                </title>
                <description>
                    <![CDATA[ A while ago I decided to build a password generator just to practice some Python. I fired up the editor, put together a script with the random module, and it worked great: if you give it a length, it  ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-build-a-secure-password-generator-with-python/</link>
                <guid isPermaLink="false">6b0e018d2cb66b3df319a012</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Beginner Developers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Tutorial ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Sameer Qaiser ]]>
                </dc:creator>
                <pubDate>Mon, 30 Nov 2026 23:06:53 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/7a9cfcd2-adac-49c4-a097-ec862953ab5b.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A while ago I decided to build a password generator just to practice some Python. I fired up the editor, put together a script with the random module, and it worked great: if you give it a length, it spits out a string of characters.</p>
<p>Later, I found out that using <code>random</code> for anything that needs to be secure is a really bad idea. So, in this tutorial I’m going to show you why that module is unsuitable for security, and how to make a proper secure password generator with the secrets module instead.</p>
<p>So, this isn’t just another “here’s a password generator” tutorial. By the end, you'll know how to write a secure Python script, handle user input gracefully, and understand why standard random number generators aren't safe for passwords.</p>
<h3 id="heading-what-well-cover">What We'll Cover:</h3>
<ul>
<li><a href="#heading-how-most-beginners-write-it-and-mess-it-up">How Most Beginners Write It and Mess it Up</a></li>
<li><a href="#heading-how-to-use-the-secrets-module-for-true-randomness">How to Use the Secrets Module for True Randomness</a></li>
<li><a href="#heading-how-to-make-it-interactive-with-the-user-input">How to Make It Interactive with the User Input</a></li>
<li><a href="#heading-what-i-learned-about-secure-code">What I Learned About Secure Code</a></li>
</ul>
<h2 id="heading-how-most-beginners-write-it-and-mess-it-up">How Most Beginners Write It and Mess it Up</h2>
<p>This is what I (and pretty much every beginner) starts with:</p>
<pre><code class="language-python">import random
import string

chars = string.ascii_letters + string.digits
password = ''.join(random.choice(chars) for _ in range(12))
print(password)
</code></pre>
<p>It looks and runs fine. The passwords even look ok. The problem is that <code>random</code> is a pseudo-random number generator. It’s driven by a mathematical formula and a seed. If someone knows (or can guess) the seed, or sees enough outputs, the sequence becomes predictable.</p>
<p>For tasks like shuffling a playlist or rolling dice in a game, this is perfectly fine. But for passwords, it introduces a major security risk.</p>
<p>I used to think “random is random,” but apparently there’s a difference between “looks random” and “actually unpredictable.” I learned this lesson the hard way!</p>
<h2 id="heading-how-to-use-the-secrets-module-for-true-randomness">How to Use the Secrets Module for True Randomness</h2>
<p>Python has a built-in module called secrets that’s made exactly for this kind of thing. Instead of relying on some predictable math formula, it pulls randomness straight from your operating system’s entropy source.</p>
<p>On Linux it grabs data from /dev/urandom, and on Windows it uses CryptGenRandom. Sounds a bit technical, but basically it just means it’s using the computer’s deepest, most secure source of randomness. That’s the standard way to handle passwords and security tokens in Python.</p>
<p>Here’s the basic secure version:</p>
<pre><code class="language-python">import secrets
import string

letters = string.ascii_letters
digits = string.digits
symbols = string.punctuation

all_chars = letters + digits + symbols

password = ''.join(secrets.choice(all_chars) for _ in range(16))
print(password)
</code></pre>
<p>The code is almost identical. The only real change is swapping <code>random</code> for <code>secrets</code>. That one swap is the entire point of this whole thing.</p>
<h2 id="heading-how-to-make-it-interactive-with-the-user-input">How to Make it Interactive with the User Input</h2>
<p>Instead of hard-coding the length, let’s just ask the user for it. People might type letters or symbols by accident instead of a number, so we’ll throw in some error handling, so the script doesn’t crash.</p>
<pre><code class="language-python">import secrets
import string

print("===== SECURE PASSWORD GENERATOR =====")

while True:
    try:
        length = int(input("\nHow long should the password be? (minimum 8): "))
        if length &gt;= 8:
            break
        print("The Password must be at least 8 characters")
    except ValueError:
        print("Invalid Input. Please enter a number.")

all_chars = string.ascii_letters + string.digits + string.punctuation
password = ''.join(secrets.choice(all_chars) for _ in range(length))

print(f"\nYour secure password is:{password}")
</code></pre>
<p>A few quick notes on what’s going on here:</p>
<ul>
<li>The <code>while True</code> loop just keeps asking until it gets something usable.</li>
<li>The <code>try/except</code> block catches invalid inputs (like typing words instead of a number) so the script doesn't crash.</li>
<li>I set a minimum length of 8 characters because shorter passwords are easily compromised.</li>
</ul>
<p>Save it as <code>password_gen.py</code>, run it with the <code>python password_gen.py</code> command, and you’re done. Try typing letters or a number under 8 to see if the error handling actually works. It’s oddly satisfying.</p>
<pre><code class="language-plaintext">===== SECURE PASSWORD GENERATOR =====

How long should the password be? (minimum 8): 16

Here you go: k#P9$m!vQ2x@L8wE
</code></pre>
<h2 id="heading-what-i-learned-about-secure-code">What I Learned About Secure Code</h2>
<p>One thing that still catches people is assuming that if the code runs and produces something that looks like a strong password, it must be fine. The first version I wrote ran perfectly and was still the wrong tool for the job. <code>secrets</code> is the one you want when the output needs to be hard to guess.</p>
<p>If you want to take it a bit further, you can force the password to include at least one number and one symbol, so it never comes out as pure letters. Or you can wrap it in a tiny GUI if you’re into that. I usually just keep the terminal version because it’s fast and I don’t have to think about it.</p>
<p>In summary, the main takeaway is to avoid the <code>random</code> module when building anything security-related. By switching to <code>secrets</code> and adding basic error handling for user input, you can create a script that is both secure and reliable. Now you have a tool you can actually trust to generate strong passwords.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Production-Ready Authentication & Authorization System with Angular and NestJS ]]>
                </title>
                <description>
                    <![CDATA[ Authentication is one of those topics that seems like it would be simple. A user submits a username and password, the server verifies the credentials, and the application returns a token. But a secure ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-build-a-production-ready-authentication-authorization-system-with-angular-and-nestjs/</link>
                <guid isPermaLink="false">6b0d8efba84f8b699f29755c</guid>
                
                    <category>
                        <![CDATA[ authentication ]]>
                    </category>
                
                    <category>
                        <![CDATA[ authorization ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Angular ]]>
                    </category>
                
                    <category>
                        <![CDATA[ nestjs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Abanoub Kerols ]]>
                </dc:creator>
                <pubDate>Mon, 30 Nov 2026 14:58:03 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/adb9ee17-68b0-475e-ab46-6e023aa1cf7d.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Authentication is one of those topics that seems like it would be simple. A user submits a username and password, the server verifies the credentials, and the application returns a token.</p>
<p>But a secure authentication system involves more than just generating a JSON Web Token (JWT). You also need to think about password storage, access and refresh tokens, token rotation, session management, logout, concurrent requests, authorization, CSRF protection, rate limiting, input validation, CORS, secure cookies, database consistency, security monitoring, and...the list goes on.</p>
<p>In this handbook, we'll examine an authentication and authorization architecture for a full-stack application built with Angular, NestJS, MongoDB, and Redis. Our goals here are to understand the responsibilities of each component, how they work together, and which additional controls we need to verify before deploying a real application.</p>
<p>The design uses a short-lived access JWT held in Angular memory and an opaque refresh token delivered through an HttpOnly cookie. The backend stores a hash of the refresh token in MongoDB, uses session records to track logins, and uses Redis for rate limiting and other temporary state. The server (not the Angular UI) remains the security boundary for authentication and authorization.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a href="#heading-prerequisites">Prerequisites</a></li>
<li><a href="#heading-1-authentication-vs-authorization">1. Authentication vs Authorization</a></li>
<li><a href="#heading-2-the-architecture">2. The Architecture</a></li>
<li><a href="#heading-3-what-we-will-build">3. What We Will Build</a></li>
<li><a href="#heading-4-why-not-store-everything-in-localstorage">4. Why Not Store Everything in localStorage?</a></li>
<li><a href="#heading-5-project-structure">5. Project Structure</a></li>
<li><a href="#heading-6-install-dependencies">6. Install Dependencies</a></li>
<li><a href="#heading-7-environment-configuration">7. Environment Configuration</a></li>
<li><a href="#heading-8-user-model">8. User Model</a></li>
<li><a href="#heading-9-password-hashing">9. Password Hashing</a></li>
<li><a href="#heading-10-registration">10. Registration</a><ul>
<li><a href="#heading-database-constraints-are-still-required">Database Constraints Are Still Required</a></li>
</ul>
</li>
<li><a href="#heading-11-sessions">11. Sessions</a></li>
<li><a href="#heading-12-refresh-tokens">12. Refresh Tokens</a><ul>
<li><a href="#heading-generating-refresh-tokens">Generating Refresh Tokens</a></li>
<li><a href="#heading-hashing-the-refresh-token">Hashing the Refresh Token</a></li>
</ul>
</li>
<li><a href="#heading-13-access-jwt">13. Access JWT</a><ul>
<li><a href="#heading-creating-the-access-token">Creating the Access Token</a></li>
</ul>
</li>
<li><a href="#heading-14-login">14. Login</a><ul>
<li><a href="#heading-the-login-flow">The Login Flow</a></li>
<li><a href="#heading-login-implementation">Login Implementation</a></li>
<li><a href="#heading-why-httponly">Why HttpOnly?</a></li>
</ul>
</li>
<li><a href="#heading-15-angular-authservice">15. Angular AuthService</a><ul>
<li><a href="#heading-angular-interceptor">Angular Interceptor</a></li>
</ul>
</li>
<li><a href="#heading-16-handling-expired-access-tokens">16. Handling Expired Access Tokens</a><ul>
<li><a href="#heading-the-concurrency-problem">The Concurrency Problem</a></li>
<li><a href="#heading-angular-refresh-lock">Angular Refresh Lock</a></li>
<li><a href="#heading-refresh-endpoint">Refresh Endpoint</a></li>
</ul>
</li>
<li><a href="#heading-17-refresh-token-rotation">17. Refresh Token Rotation</a><ul>
<li><a href="#heading-reuse-detection">Reuse Detection</a></li>
</ul>
</li>
<li><a href="#heading-18-why-we-have-sessions">18. Why We Have Sessions</a></li>
<li><a href="#heading-19-jwt-authentication-in-nestjs">19. JWT Authentication in NestJS</a><ul>
<li><a href="#heading-jwtauthguard">JwtAuthGuard</a></li>
<li><a href="#heading-angular-guard-isnt-security">Angular Guard Isn't Security</a></li>
</ul>
</li>
<li><a href="#heading-20-rbac">20. RBAC</a><ul>
<li><a href="#heading-roles">@Roles()</a></li>
<li><a href="#heading-rolesguard">RolesGuard</a></li>
<li><a href="#heading-using-rbac">Using RBAC</a></li>
<li><a href="#heading-401-vs-403">401 vs 403</a></li>
<li><a href="#heading-public-routes">Public Routes</a></li>
</ul>
</li>
<li><a href="#heading-21-csrf">21. CSRF</a><ul>
<li><a href="#heading-samesite">SameSite</a></li>
<li><a href="#heading-csrf-token">CSRF Token</a></li>
<li><a href="#heading-csrf-guard">CSRF Guard</a></li>
</ul>
</li>
<li><a href="#heading-22-redis">22. Redis</a><ul>
<li><a href="#heading-rate-limiting">Rate Limiting</a></li>
<li><a href="#heading-dont-rate-limit-only-by-ip">Don't Rate Limit Only by IP</a></li>
<li><a href="#heading-endpoints-worth-protecting">Endpoints Worth Protecting</a></li>
</ul>
</li>
<li><a href="#heading-23-cors">23. CORS</a></li>
<li><a href="#heading-24-logout">24. Logout</a><ul>
<li><a href="#heading-logout-all-devices">Logout All Devices</a></li>
</ul>
</li>
<li><a href="#heading-25-mongodb-transaction-for-rotation">25. MongoDB Transaction for Rotation</a></li>
<li><a href="#heading-26-complete-authentication-flow">26. Complete Authentication Flow</a><ul>
<li><a href="#heading-login">Login</a></li>
<li><a href="#heading-normal-api-request">Normal API Request</a></li>
<li><a href="#heading-expired-access-token">Expired Access Token</a></li>
<li><a href="#heading-refresh-token-theft">Refresh Token Theft</a></li>
<li><a href="#heading-authorization-flow">Authorization Flow</a></li>
</ul>
</li>
<li><a href="#heading-27-security-review">27. Security Review</a></li>
<li><a href="#heading-28-things-we-should-add-later">28. Things We Should Add Later</a></li>
<li><a href="#heading-29-the-most-important-architectural-lessons">29. The Most Important Architectural Lessons</a></li>
<li><a href="#heading-30-final-architecture">30. Final Architecture</a></li>
<li><a href="#heading-explore-the-source-code">Explore the Source Code</a></li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>This tutorial will be approachable for you if you already know the basics of JavaScript and TypeScript and have built a small application with Angular or another frontend framework. Familiarity with HTTP requests, REST APIs, and basic database operations will make the examples easier to follow. You don't need to be a security specialist, but you should be comfortable reading backend TypeScript.</p>
<p>You'll also need Node.js and npm, the Angular CLI, a NestJS project, MongoDB, Redis, and a tool for sending HTTP requests such as Postman or <code>curl</code>. Git and an editor such as VS Code are also useful. You can run MongoDB and Redis locally or use managed development instances.</p>
<p>The snippets below illustrate the important parts of the design. But they're not a substitute for checking the complete repository, configuring every endpoint, and running automated security tests. Package versions and some bootstrap details can differ between project versions.</p>
<h2 id="heading-1-authentication-vs-authorization">1. Authentication vs Authorization</h2>
<p>Before we start, you need to know the difference between these two terms.</p>
<p>Authentication answers the question, “Who are you?” The server verifies the credentials or validates an existing session and establishes the identity associated with the request.</p>
<p>For example, a user submits an email address and password. If the credentials are valid, the server identifies the corresponding user. The client shouldn't be allowed to choose or forge that identity.</p>
<p>Authorization answers a different question: “What is this authenticated user allowed to do?” A user with an <code>ADMIN</code> role might be allowed to manage accounts, while a regular <code>USER</code> might be allowed to view or update only their own profile.</p>
<p>Authentication must happen before protected authorization rules can be evaluated. But a role check alone isn't always enough: an endpoint that reads <code>/orders/123</code> must also verify that the current user is allowed to access that particular order. We'll return to this distinction when we discuss RBAC and resource ownership below.</p>
<h2 id="heading-2-the-architecture">2. The Architecture</h2>
<p>The browser runs the Angular application, while NestJS exposes the API and makes security decisions. MongoDB stores durable user, session, and refresh-token records. Redis supports rate limiting and other temporary or shared state that shouldn't depend on one API process.</p>
<pre><code class="language-text">                    Angular
                       │
             ┌─────────┴─────────┐
             │                   │
       Access Token        Refresh Cookie
             │                   │
             ▼                   ▼
      Authorization Header    HttpOnly
             │                   │
             └─────────┬─────────┘
                       ▼
                    NestJS
                       │
              ┌────────┴────────┐
              │                 │
      Authentication      Authorization
              │                 │
         JWT Strategy       RolesGuard
              │                 │
              └────────┬────────┘
                       │
                       ▼
                    Service
                       │
              ┌────────┴────────┐
              ▼                 ▼
           MongoDB            Redis
              │                 │
       Users/Sessions       Rate Limits
       Refresh Tokens       Temporary State
</code></pre>
<p>We'll use a hybrid authentication model. The access token is a short-lived JWT that Angular keeps in memory and sends in the <code>Authorization</code> header. The refresh token is a cryptographically random, opaque value (not another JWT) and is sent by the browser in an HttpOnly cookie. MongoDB stores only a hash of that refresh token, along with its session and lifecycle metadata.</p>
<p>This is a deliberate division of responsibilities: the access token lets the API authenticate ordinary requests, while the refresh token lets the server continue a session after the access token expires. Because refresh tokens are tracked server-side, they can be rotated and revoked. A signed JWT isn't automatically revocable, though. If immediate access-token revocation is required, the API must also check session status or use another revocation strategy on protected requests.</p>
<h2 id="heading-3-what-we-will-build">3. What We Will Build</h2>
<p>Before discussing browser storage, let's establish the scope. The example architecture covers account registration, password hashing, login, short-lived access JWTs, opaque refresh tokens, refresh-token rotation and reuse detection, per-device sessions, logout, role-based access control, request validation, CSRF considerations, CORS, and rate limiting with Redis.</p>
<p>The Angular side keeps the access token in memory, adds it to protected API requests, and coordinates refresh attempts when requests fail because a token has expired. The NestJS side validates credentials and tokens, enforces permissions, and updates server-side session state. MongoDB stores durable identity and session records, while we use Redis for rate-limit state and other temporary coordination where configured.</p>
<p>This is a learning architecture, not a guarantee that every deployment is production-ready. You should implement and verify email verification, password reset, multi-factor authentication, robust audit logging, monitoring, deployment-specific cookie settings, cross-tab refresh coordination, and a complete automated security test suite for any real application's needs.</p>
<h2 id="heading-4-why-not-store-everything-in-localstorage">4. Why Not Store Everything in localStorage?</h2>
<p>A common implementation stores an access token in <code>localStorage</code> because it survives page reloads. The trade-off is that any JavaScript executing in the origin can read it. If an attacker exploits a cross-site scripting (XSS) vulnerability, injected JavaScript may read the token and send it to an external server. The same XSS can often perform actions as the user even if the token is kept only in memory, so in-memory storage reduces persistence and straightforward extraction but doesn't eliminate XSS risk.</p>
<p>In this design, Angular keeps the short-lived access token in memory. The refresh token is stored in an HttpOnly cookie, which prevents ordinary page JavaScript from reading its value. This makes direct refresh-token extraction through <code>document.cookie</code> harder, but it doesn't make XSS harmless. It also doesn't, by itself, prevent cross-site request forgery (CSRF). Cookie-based refresh endpoints still need an intentional SameSite policy and appropriate CSRF/origin defenses.</p>
<pre><code class="language-text">Angular Memory
    ↓
Access Token

HttpOnly Cookie
    ↓
Refresh Token
</code></pre>
<p>JavaScript can't directly read an HttpOnly cookie, but the browser can still attach it to matching requests. That's why cookie configuration and CSRF defenses are important.</p>
<h2 id="heading-5-project-structure">5. Project Structure</h2>
<p>The following are two parts of the same full-stack application, not mutually exclusive alternatives. The NestJS tree belongs to the backend API, while the Angular tree belongs to the browser client. They can live in separate repositories or under separate <code>apps/api</code> and <code>apps/web</code> folders in a monorepo.</p>
<p>Choose the arrangement that fits your team's deployment and tooling. Don't combine the two <code>src</code> trees into one application directory.</p>
<p>The backend separates authentication endpoints and token logic from user data, session persistence, and Redis integration. Guards and decorators provide reusable request-level security rules. In a larger system, some of these responsibilities might be split into additional modules.</p>
<p>Here's a possible NestJS structure:</p>
<pre><code class="language-text">src/
├── auth/
│   ├── auth.controller.ts
│   ├── auth.service.ts
│   ├── auth.module.ts
│   ├── token.service.ts
│   ├── strategies/
│   │   └── jwt.strategy.ts
│   ├── guards/
│   │   ├── jwt-auth.guard.ts
│   │   ├── roles.guard.ts
│   │   └── csrf.guard.ts
│   └── decorators/
│       ├── public.decorator.ts
│       ├── roles.decorator.ts
│       └── current-user.decorator.ts
│
├── users/
│   ├── users.service.ts
│   ├── users.module.ts
│   └── schemas/
│       └── user.schema.ts
│
├── sessions/
│   ├── sessions.service.ts
│   ├── sessions.module.ts
│   └── schemas/
│       ├── session.schema.ts
│       └── refresh-token.schema.ts
│
├── redis/
│   ├── redis.service.ts
│   └── redis.module.ts
│
└── app.module.ts
</code></pre>
<p>The Angular structure is the client-side counterpart. <code>AuthService</code> manages authentication requests and the in-memory access token. Interceptors attach the access token and handle CSRF-related headers where appropriate. The guard improves the navigation experience, but doesn't replace backend authorization. <code>auth.types.ts</code> contains client-side request/response types, and <code>auth.store.ts</code> can expose authentication state to components. Avoid storing the refresh token in Angular state. The browser manages the HttpOnly cookie.</p>
<p>Angular:</p>
<pre><code class="language-text">src/app/core/auth/
├── auth.service.ts
├── auth.interceptor.ts
├── csrf.interceptor.ts
├── auth.guard.ts
├── auth.types.ts
└── auth.store.ts
</code></pre>
<h2 id="heading-6-install-dependencies">6. Install Dependencies</h2>
<p>Run the following in the NestJS backend project. These packages provide configuration, MongoDB integration, JWT and Passport authentication, password hashing, cookie parsing, DTO validation, and Redis access. If your repository already includes some packages, check <code>package.json</code> before installing duplicates.</p>
<p>For NestJS:</p>
<pre><code class="language-bash">npm install \
  @nestjs/config \
  @nestjs/mongoose \
  @nestjs/jwt \
  @nestjs/passport \
  passport \
  passport-jwt \
  mongoose \
  bcrypt \
  cookie-parser \
  class-validator \
  class-transformer \
  ioredis
</code></pre>
<p>Here's what the runtime dependencies do:</p>
<ul>
<li><code>@nestjs/config</code> loads environment configuration and exposes it through <code>ConfigService</code>.</li>
<li><code>@nestjs/mongoose</code> integrates Mongoose models with NestJS. <code>mongoose</code> defines schemas and communicates with MongoDB.</li>
<li><code>@nestjs/jwt</code> signs and verifies JWTs.</li>
<li><code>@nestjs/passport</code>, <code>passport</code>, and <code>passport-jwt</code> connect Passport strategies to NestJS authentication flows.</li>
<li><code>bcrypt</code> hashes passwords and compares login attempts against stored password hashes.</li>
<li><code>cookie-parser</code> parses the incoming <code>Cookie</code> header so Express requests can expose parsed cookies. Register its middleware in the application bootstrap if your setup requires it.</li>
<li><code>class-validator</code> and <code>class-transformer</code> support DTO validation and transformation when used with NestJS's <code>ValidationPipe</code>.</li>
<li><code>ioredis</code> is a Redis client used for rate-limit counters and other shared temporary state.</li>
</ul>
<p>The <code>-D</code> flag installs development dependencies. The <code>@types/*</code> packages provide TypeScript declarations for libraries that don't ship all the needed types. They help the compiler and editor and aren't application runtime services. Exact type packages depend on the versions and TypeScript setup used by your project.</p>
<p>Development types:</p>
<pre><code class="language-bash">npm install -D \
  @types/bcrypt \
  @types/cookie-parser \
  @types/passport-jwt
</code></pre>
<h2 id="heading-7-environment-configuration">7. Environment Configuration</h2>
<p>Create a local <code>.env</code> file for development and load it through NestJS configuration. These values are illustrative local settings, not production secrets.</p>
<p>Never commit a real <code>.env</code> file. Commit an <code>.env.example</code> containing only safe placeholder values instead. In production, generate a high-entropy secret and provide it through your hosting platform's secret manager or protected environment configuration.</p>
<p>Validate required variables when the application starts so a missing or malformed secret doesn't remain unnoticed until a request arrives. Also, keep the configuration and implementation consistent: if <code>ACCESS_TOKEN_EXPIRES_IN</code> is configurable, the token service should read that variable instead of hard-coding <code>'15m'</code> in the signing call.</p>
<pre><code class="language-env">PORT=3000

MONGO_URI=mongodb://localhost:27017/secure_auth

REDIS_HOST=localhost
REDIS_PORT=6379

JWT_ACCESS_SECRET=strong-random-secret

ACCESS_TOKEN_EXPIRES_IN=15m

NODE_ENV=development
</code></pre>
<p><code>MONGO_URI</code> points to the MongoDB database, and the Redis host and port tell the application where to connect for rate limiting. <code>JWT_ACCESS_SECRET</code> signs access tokens, so it must be unpredictable and protected. <code>ACCESS_TOKEN_EXPIRES_IN</code> documents the intended short lifetime. Make sure the implementation actually reads it. <code>NODE_ENV</code> controls environment-specific settings such as whether cookies use the <code>Secure</code> attribute.</p>
<p>Notice that we don't need a <code>JWT_REFRESH_SECRET</code> variable because the refresh token isn't a JWT. It's a random opaque token.</p>
<h2 id="heading-8-user-model">8. User Model</h2>
<p>Before we can register users or authenticate them, we need somewhere to store the information that identifies each account. In this application, the <code>User</code> model represents one registered person. It holds the details we need during authentication, such as the email address and password hash, as well as account information like the user's name, email-verification status, and role.</p>
<p>We'll start by defining the roles the application understands:</p>
<pre><code class="language-ts">export enum UserRole {
  USER = 'user',
  ADMIN = 'admin',
  MODERATOR = 'moderator',
}
</code></pre>
<p>An enum gives us a fixed set of role values instead of scattering strings such as <code>'admin'</code> and <code>'user'</code> throughout the code. That makes role checks easier to keep consistent. These values describe permissions assigned by the application. They aren't values a person should be able to choose freely during public registration.</p>
<p>Next, we can define the Mongoose schema for a user:</p>
<pre><code class="language-ts">@Schema({ timestamps: true })
export class User {
  @Prop({
    required: true,
    unique: true,
    lowercase: true,
    trim: true,
  })
  email: string;

  @Prop({
    required: true,
  })
  passwordHash: string;

  @Prop({
    required: true,
    trim: true,
  })
  name: string;

  @Prop({
    default: false,
  })
  emailVerified: boolean;

  @Prop({
    type: String,
    enum: Object.values(UserRole),
    default: UserRole.USER,
  })
  role: UserRole;
}

export const UserSchema =
  SchemaFactory.createForClass(User);
</code></pre>
<p>Each <code>@Prop()</code> decorator tells Mongoose how a field should be stored and validated. For example, the email is required and normalized to lowercase with surrounding whitespace removed. The <code>unique</code> option asks MongoDB to create a unique index so two accounts can't share the same email address. We'll discuss why we still need to handle duplicate-key errors in the "Database Constraints Are Still Required" subsection of the Registration section.</p>
<p>The <code>passwordHash</code> field stores the result of password hashing, not the original password. <code>name</code> is required, <code>emailVerified</code> starts as <code>false</code>, and <code>role</code> defaults to <code>USER</code>. The <code>SchemaFactory</code> call turns the decorated class into the Mongoose schema used to create the model.</p>
<p>Notice that the model has no plain <code>password</code> field. We only keep <code>passwordHash</code>, because the original password should never be recoverable from the database.</p>
<h2 id="heading-9-password-hashing">9. Password Hashing</h2>
<p>Password hashing protects users if someone gains access to the database. Instead of saving the password itself, the server saves a one-way hash. During login, it checks a newly submitted password against that hash. The application should never log a password or include one in an API response.</p>
<p>Human passwords are usually much easier to guess than randomly generated secrets. People tend to choose familiar words, names, dates, or patterns, and attackers can try large lists of likely passwords. In security terms, this means passwords often have relatively low <em>entropy</em>: there may be fewer plausible combinations than the password's length alone suggests.</p>
<p>That's why we shouldn't use a fast general-purpose hash such as plain SHA-256 for passwords. An attacker with a stolen password database could test guesses very quickly.</p>
<p>Password-hashing algorithms such as bcrypt and Argon2 are deliberately expensive: they make each guess take more time and computational resources. They also use a salt, so identical passwords don't produce identical stored hashes. This doesn't make weak passwords impossible to crack, but it makes large-scale guessing much more costly.</p>
<p>For this example, we'll use bcrypt with a cost factor of <code>12</code>:</p>
<pre><code class="language-ts">const passwordHash = await bcrypt.hash(
  password,
  12,
);
</code></pre>
<p>When the user logs in, we don't hash the submitted password ourselves and compare two strings. Bcrypt stores the salt and cost information as part of the encoded hash, and <code>compare()</code> uses that information to run the appropriate verification process:</p>
<pre><code class="language-ts">const valid = await bcrypt.compare(
  password,
  user.passwordHash,
);
</code></pre>
<p>A direct comparison such as <code>password === passwordHash</code> won't work because the submitted password is plain text while <code>passwordHash</code> is a salted, encoded hash. They're different values, and a secure password hash isn't designed to be reversed. Use <code>bcrypt.compare()</code> so the library can verify the password using the salt and parameters stored in the hash.</p>
<p>Also, don't use encryption as a substitute for password hashing. Encryption is designed to be reversible when you have the key, and an application shouldn't need to decrypt a user's password at all. Store a password hash and verify it when the user signs in.</p>
<h2 id="heading-10-registration">10. Registration</h2>
<p>Registration is the first place where data from an unknown client enters our application. We shouldn't pass that data straight into a database operation. First, we need to check that the request contains the fields we expect and that those fields have sensible values. Then we should explicitly map the accepted values into the user record.</p>
<p>In NestJS, a <strong>Data Transfer Object (DTO)</strong> describes the shape of data that an endpoint accepts or returns. For registration, the DTO is the contract for the request body. We can use decorators from <code>class-validator</code> to describe rules such as “this value must be an email address” or “the password must be between 8 and 128 characters.” NestJS's <code>ValidationPipe</code> runs those checks before the controller handles the request.</p>
<p>Here's a registration DTO:</p>
<pre><code class="language-ts">export class RegisterDto {
  @IsEmail()
  email: string;

  @IsString()
  @MinLength(8)
  @MaxLength(128)
  password: string;

  @IsString()
  @MinLength(2)
  @MaxLength(100)
  name: string;
}
</code></pre>
<p>Enable validation globally:</p>
<pre><code class="language-ts">app.useGlobalPipes(
  new ValidationPipe({
    whitelist: true,
    forbidNonWhitelisted: true,
    transform: true,
  }),
);
</code></pre>
<p>This is important because an attacker might send:</p>
<pre><code class="language-json">{
  "email": "user@example.com",
  "password": "password",
  "role": "admin"
}
</code></pre>
<p>Notice that <code>role</code> isn't part of <code>RegisterDto</code>. That's intentional. A public registration endpoint should let someone provide their email, password, and name, but it shouldn't let them decide whether they're a regular user, moderator, or administrator. The user model supplies the default role (<code>USER</code>) on the server.</p>
<p>Because we enabled <code>whitelist</code> and <code>forbidNonWhitelisted</code>, NestJS rejects a request that includes a property that isn't declared in the DTO. For example, a request that tries to add <code>"role": "admin"</code> will fail validation instead of silently passing that property through. The controller should still create the user from an explicit list of accepted fields rather than spreading the entire request object into a database document.</p>
<p>The request therefore follows this path:</p>
<pre><code class="language-text">Client sends registration data
          ↓
ValidationPipe checks the DTO
          ↓
Known, valid fields reach the controller
          ↓
Controller/service maps allowed fields
          ↓
User is created with the server-side default role
</code></pre>
<p>This is one way to reduce the risk of <strong>mass assignment</strong>: accidentally allowing a client to set internal fields that should only be controlled by the server.</p>
<h3 id="heading-database-constraints-are-still-required">Database Constraints Are Still Required</h3>
<p>It's useful to check whether an email address is already registered before trying to create an account. That lets the API return a friendly response in the common case. But this application-level check is only a convenience. It can't guarantee uniqueness when requests arrive at the same time.</p>
<p>For example, two registration requests can both check the database before either one has inserted its new user. Both checks may report that the email is available, and then both requests may try to create an account. A unique index in MongoDB is what prevents the duplicate record from being saved.</p>
<p>You can still perform an early lookup:</p>
<pre><code class="language-ts">const existing =
  await usersService.findByEmail(email);
</code></pre>
<p>But this isn't enough.</p>
<p>Two requests can arrive simultaneously:</p>
<pre><code class="language-text">Request A → email doesn't exist
Request B → email doesn't exist
</code></pre>
<p>And both may attempt to create the account.</p>
<p>So the schema needs a unique index on the email field:</p>
<pre><code class="language-ts">unique: true
</code></pre>
<p>The database index handles the race condition. If both requests pass the earlier lookup, MongoDB allows the first insert and rejects the second with a duplicate-key error (usually error code <code>11000</code>).</p>
<p>The registration service is the part of the application that should catch that database error. It can translate the database-specific error into a predictable HTTP response, such as <code>409 Conflict</code>, without exposing raw MongoDB details to the client. For example:</p>
<pre><code class="language-ts">try {
  return await this.usersService.create({
    email,
    passwordHash,
    name,
  });
} catch (error) {
  if (
    error &amp;&amp;
    typeof error === 'object' &amp;&amp;
    'code' in error &amp;&amp;
    error.code === 11000
  ) {
    throw new ConflictException(
      'An account with this email already exists',
    );
  }

  throw error;
}
</code></pre>
<p>This is illustrative: put the <code>try/catch</code> around the operation that actually performs the insert, whether that lives in <code>AuthService</code> or <code>UsersService</code> in your project. The important part is that the layer handling account creation translates the duplicate-key error, while unexpected database errors continue to be handled by the application's regular error handling.</p>
<p>The early lookup improves the user experience, the unique index guarantees the data constraint, and the service turns a database error into a safe API response. Each has a different job.</p>
<h2 id="heading-11-sessions">11. Sessions</h2>
<p>A session represents one authenticated login context, such as a browser on a laptop or a phone. Keeping session state separately from the user record makes it possible to track devices, last activity, expiry, and revocation.</p>
<p>It's worth keeping these concepts separate: a user is the account, while a session represents one active login for that account. One user can sign in from several devices or browsers at the same time. For example, the same account might have sessions for:</p>
<pre><code class="language-text">Laptop
Phone
Tablet
</code></pre>
<p>For that reason, the request should follow this path:</p>
<pre><code class="language-text">User
 ├── Session A
 ├── Session B
 └── Session C
</code></pre>
<p>A Session can contain:</p>
<pre><code class="language-ts">@Schema({ timestamps: true })
export class Session {
  @Prop({ required: true, index: true })
  userId: Types.ObjectId;

  @Prop({
    required: true,
    unique: true,
    index: true,
  })
  sessionId: string;

  @Prop({ required: true })
  expiresAt: Date;

  @Prop({ default: null })
  revokedAt: Date | null;

  @Prop()
  ip?: string;

  @Prop()
  userAgent?: string;

  @Prop()
  lastUsedAt?: Date;
}
</code></pre>
<p>This gives us a place to track sessions, but the application must actually consult and update these records in its authentication flow. If protected requests validate only the JWT signature and expiration, revoking a session won't immediately invalidate an already-issued access token.</p>
<p>For immediate revocation, the JWT strategy must also validate the session ID (<code>sid</code>) against current server-side session state, or the system must use another revocation mechanism. This check has a performance and availability cost that you should consider explicitly.</p>
<h2 id="heading-12-refresh-tokens">12. Refresh Tokens</h2>
<p>Refresh tokens are long-lived credentials, so their lifecycle needs more protection than a short-lived access token. A separate collection makes it possible to revoke and audit each token in a rotation chain.</p>
<p>Instead of storing one refresh token directly inside the Session document, we can create a dedicated collection.</p>
<pre><code class="language-ts">@Schema({ timestamps: true })
export class RefreshToken {
  @Prop({
    required: true,
    index: true,
    type: Types.ObjectId,
    ref: 'User',
  })
  userId: Types.ObjectId;

  @Prop({
    required: true,
    index: true,
  })
  sessionId: string;

  @Prop({
    required: true,
    unique: true,
    index: true,
  })
  tokenHash: string;

  @Prop({
    required: true,
    unique: true,
    index: true,
  })
  tokenId: string;

  @Prop({ required: true })
  expiresAt: Date;

  @Prop({ default: null })
  revokedAt: Date | null;

  @Prop({ default: null })
  replacedBy: string | null;

  @Prop()
  usedAt?: Date;

  @Prop()
  ip?: string;

  @Prop()
  userAgent?: string;
}
</code></pre>
<p>Why keep refresh tokens in a separate collection instead of storing a single token on the session? Because every successful rotation replaces the current token, and we want to retain enough history to recognize an older token if it appears again. That history forms a chain:</p>
<pre><code class="language-text">R1 → R2 → R3 → R4
</code></pre>
<p>We want to be able to track that history.</p>
<h3 id="heading-generating-refresh-tokens">Generating Refresh Tokens</h3>
<p>You can generate refresh tokens with a cryptographically secure random-number generator. Don't use timestamps, ordinary pseudo-random values, or user-controlled strings as authentication secrets.</p>
<p>A refresh token doesn't need to be a JWT. Since the server already stores and checks its state, a cryptographically random opaque string is enough.</p>
<p>We can generate one with Node.js's <code>crypto</code> module like this:</p>
<pre><code class="language-ts">import { randomBytes } from 'crypto';

const refreshToken =
  randomBytes(32).toString('hex');
</code></pre>
<p>This produces a high-entropy random secret.</p>
<p>We also need two identifiers that tie the records together. We can create them the same way:</p>
<pre><code class="language-ts">const sessionId =
  randomBytes(16).toString('hex');

const tokenId =
  randomBytes(16).toString('hex');
</code></pre>
<p>These two values play different roles from the refresh token itself:</p>
<ul>
<li><code>sessionId</code> identifies one login (one device or browser). Every refresh token created for that login stores the same <code>sessionId</code>, which is how the server knows which tokens belong together and can revoke them all at once. It's also the value that ends up in the <code>sid</code> claim of the access JWT.</li>
<li><code>tokenId</code> is a unique label for one specific refresh-token record. During rotation, the old record's <code>replacedBy</code> field points to the new record's <code>tokenId</code>, which is how we build the chain <code>R1 → R2 → R3</code>.</li>
</ul>
<p>Neither one is the secret that the browser sends back. The secret is <code>refreshToken</code>. We still generate the identifiers randomly so they're unique and hard to guess.</p>
<h3 id="heading-hashing-the-refresh-token">Hashing the Refresh Token</h3>
<p>You'll want to store a hash rather than the raw refresh token so a database read alone doesn't reveal a directly reusable credential. Since the token is random and high-entropy, a fast cryptographic hash is suitable for lookup. This differs from human passwords, which need slow password hashing.</p>
<p>The browser needs the raw refresh token so it can send it back later, but the database does not. If someone reads the database, a stored hash is much less useful to them than a directly reusable token. Here, we'll hash the token before saving it:</p>
<pre><code class="language-ts">import { createHash } from 'crypto';

export function hashToken(
  token: string,
): string {
  return createHash('sha256')
    .update(token)
    .digest('hex');
}
</code></pre>
<p>The flow becomes:</p>
<pre><code class="language-text">Raw Refresh Token
       ↓
    SHA-256
       ↓
   MongoDB
</code></pre>
<p>Why SHA-256 instead of bcrypt?</p>
<p>Because the refresh token is random and high-entropy, unlike a human password. A fast cryptographic hash is appropriate for this kind of server-side lookup.</p>
<h2 id="heading-13-access-jwt">13. Access JWT</h2>
<p>A JWT is signed, not encrypted by default. Its signature helps the API detect changes, but anyone who obtains the token can usually decode its payload. For that reason, it's best to keep the payload small and include only the claims the API needs. Never put passwords, secrets, or unnecessary personal information in it.</p>
<p>For this design, the access token needs three claims:</p>
<pre><code class="language-ts">{
  sub: userId,
  sid: sessionId,
  type: 'access'
}
</code></pre>
<ul>
<li><code>sub</code> means subject, usually the user ID.</li>
<li><code>sid</code> means Session ID</li>
<li><code>type</code> prevents accidentally using another token type as an access token.</li>
</ul>
<h3 id="heading-creating-the-access-token">Creating the Access Token</h3>
<p>It's best to keep the signing secret outside source control and validate it during startup. Your token verification strategy should use compatible algorithm and claim expectations. Don't accept an algorithm merely because it appears in an incoming token.</p>
<pre><code class="language-ts">async createAccessToken(data: {
  userId: string;
  sessionId: string;
}) {
  return this.jwtService.signAsync(
    {
      sub: data.userId,
      sid: data.sessionId,
      type: 'access',
    },
    {
      secret:
        this.configService.getOrThrow&lt;string&gt;(
          'JWT_ACCESS_SECRET',
        ),
      expiresIn: this.configService.getOrThrow&lt;string&gt;(
        'ACCESS_TOKEN_EXPIRES_IN',
      ),
    },
  );
}
</code></pre>
<p>The short expiration is intentional. The configured lifetime should match the value used by the signing code, and the JWT strategy should validate the expected algorithm, signature, expiration, and token type. If the API also checks session revocation, it should validate the <code>sid</code> claim against the active session record.</p>
<p>If an access token is stolen, make sure that token has a limited lifetime. A short TTL reduces the damage window.</p>
<h2 id="heading-14-login">14. Login</h2>
<p>Now that we have users, sessions, refresh tokens, and access tokens, we can put them together in the login endpoint. In this section, we'll look at the overall flow first, then the implementation, and then why the refresh token is delivered in an HttpOnly cookie.</p>
<h3 id="heading-the-login-flow">The Login Flow</h3>
<p>Here's the complete conceptual flow to help you visualize how everything's working:</p>
<pre><code class="language-text">POST /auth/login
       │
       ▼
Find user
       │
       ▼
Compare password
       │
       ▼
Create Session
       │
       ├── sessionId
       │
       ▼
Create Refresh Token
       │
       ├── random secret
       ├── hash
       └── store hash
       │
       ▼
Create Access JWT
       │
       ▼
Set HttpOnly Cookie
       │
       ▼
Return accessToken
</code></pre>
<h3 id="heading-login-implementation">Login Implementation</h3>
<p>This example shows the main steps, but a complete implementation should also validate the DTO, apply rate limits, handle database failures, and ensure the session and refresh-token records are created consistently. Don't reveal whether the email or password was wrong. Instead, use a generic credential error.</p>
<pre><code class="language-ts">async login(
  dto: LoginDto,
  req: Request,
  res: Response,
) {
  const email =
    dto.email.trim().toLowerCase();

  const user =
    await this.usersService.findByEmail(email);

  if (!user) {
    throw new UnauthorizedException(
      'Invalid credentials',
    );
  }

  const valid =
    await bcrypt.compare(
      dto.password,
      user.passwordHash,
    );

  if (!valid) {
    throw new UnauthorizedException(
      'Invalid credentials',
    );
  }

  const sessionId =
    randomBytes(16).toString('hex');

  const refreshToken =
    randomBytes(32).toString('hex');

  const tokenId =
    randomBytes(16).toString('hex');

  const refreshTokenHash =
    hashToken(refreshToken);

  const expiresAt =
    new Date(
      Date.now() +
      7 * 24 * 60 * 60 * 1000,
    );

  await this.sessionsService.createSession({
    userId: user._id.toString(),
    sessionId,
    expiresAt,
    ip: req.ip,
    userAgent:
      req.headers['user-agent'],
  });

  await this.sessionsService.createRefreshToken({
    userId: user._id.toString(),
    sessionId,
    tokenHash: refreshTokenHash,
    tokenId,
    expiresAt,
    ip: req.ip,
    userAgent:
      req.headers['user-agent'],
  });

  const accessToken =
    await this.tokenService.createAccessToken({
      userId: user._id.toString(),
      sessionId,
    });

  res.cookie(
    'refresh_token',
    refreshToken,
    {
      httpOnly: true,
      secure:
        this.configService.get(
          'NODE_ENV',
        ) === 'production',
      sameSite: 'strict',
      path: '/auth',
      maxAge:
        7 * 24 * 60 * 60 * 1000,
    },
  );

  return {
    accessToken,
  };
}
</code></pre>
<p>Let's walk through the key features of this code:</p>
<ul>
<li>First, we normalize the email. The email is trimmed and lowercased so <code>User@Example.com</code> and <code>user@example.com</code> find the same account.</li>
<li>Then we have a generic credential error. There are two places where login can fail: the email doesn't match any user, or the password doesn't match the stored hash. In both cases, the code throws the same <code>UnauthorizedException('Invalid credentials')</code>, which NestJS returns to the client as a <code>401 Unauthorized</code> response with that message.</li>
<li>Next, we verify the password with <code>bcrypt.compare()</code>. The submitted password is checked against the stored <code>passwordHash</code>, never against a plain-text password.</li>
<li>Then we create the records. On success, the code generates random identifiers and a random refresh token, hashes the refresh token with SHA-256, and stores the session and the refresh-token record (only the hash, never the raw token) in MongoDB. Both expire in seven days.</li>
<li>After that, we return only what the client needs. The response body contains only the short-lived <code>accessToken</code>. The raw refresh token goes to the browser in a cookie, not in the JSON body.</li>
<li>Finally, we have cookie settings. <code>httpOnly</code> hides the cookie from JavaScript, <code>secure</code> (in production) means it's only sent over HTTPS, <code>sameSite: 'strict'</code> limits when the browser attaches it, and <code>path: '/auth'</code> means the browser only sends it to <code>/auth</code> endpoints, not every API request.</li>
</ul>
<p>So why shouldn't we reveal whether the email or the password was wrong? Imagine the API answered "No account with this email" for one case and "Wrong password" for the other. An attacker could then submit a long list of email addresses and learn exactly which ones have accounts on your system.</p>
<p>That's called <em>user enumeration</em>, and it helps with targeted password guessing, credential stuffing, and phishing. With one identical <code>Invalid credentials</code> response, the attacker learns nothing about which half of the credentials was wrong.</p>
<p>One more detail to be aware of: in this example, when the user doesn't exist the code returns immediately without running <code>bcrypt.compare()</code>, so that response can be measurably faster than one for a wrong password. A hardened implementation can compare against a dummy hash in that case so both paths take similar time, and combine this with the rate limiting we'll add later.</p>
<h3 id="heading-why-httponly">Why HttpOnly?</h3>
<p><code>HttpOnly</code> is an attribute you can set on a cookie. It tells the browser: "Keep this cookie for HTTP requests only, and don't let page JavaScript read it." The server sets the attribute when it sends the cookie, and the browser enforces it.</p>
<p>Here's what the server's response looks like after login (shortened, with an example value):</p>
<pre><code class="language-http">Set-Cookie: refresh_token=9f2c...e81a; HttpOnly; Secure; SameSite=Strict; Path=/auth; Max-Age=604800
</code></pre>
<p>If any script on the page then tries to read cookies through the standard browser API, the <code>refresh_token</code> cookie isn't there:</p>
<pre><code class="language-js">console.log(document.cookie);
// "" ← refresh_token isn't included, because it's HttpOnly
</code></pre>
<p>The code block above shows two things: the <code>HttpOnly</code> flag on the cookie the server sends, and what JavaScript sees when it asks for cookies. JavaScript can't read the value because the browser deliberately leaves HttpOnly cookies out of <code>document.cookie</code>. The cookie is stored and managed by the browser itself, not by the page's JavaScript, and the browser only reads it when it needs to attach it to an outgoing request.</p>
<p>But the browser still attaches the cookie automatically to matching requests, like <code>POST /auth/refresh</code>. That's why cookie-based endpoints require CSRF-aware design, which we'll cover later.</p>
<p>So the path for the refresh token looks like this:</p>
<pre><code class="language-text">Server sets cookie (HttpOnly)
          ↓
Browser stores it
          ↓
Page JavaScript asks for cookies → refresh_token is not visible
          ↓
Browser itself attaches it to matching requests (for example POST /auth/refresh)
</code></pre>
<p>Why is this the best approach here, and how does it defend against token theft? The most common way to steal a token from a web page is to run malicious JavaScript in it (XSS), read the token, and send it to a server the attacker controls. If the refresh token is in an HttpOnly cookie, that script has nothing to read, so it can't copy the long-lived credential and use it later from the attacker's own machine. This is an important defense against token theft through client-side JavaScript. It's not a complete defense: a malicious script running in the page can still make requests as the user while the page is open, which is why we need the other protections in this tutorial.</p>
<h2 id="heading-15-angular-authservice">15. Angular AuthService</h2>
<p>The <code>AuthService</code> is the single place in the Angular app that talks to the authentication endpoints and holds the access token. Components never call <code>/auth/login</code> or store tokens themselves. They ask the service.</p>
<p>That's what we mean when we say the service centralizes authentication requests and the in-memory access-token value: the HTTP calls for login, refresh, and logout all live in one class, and the access token lives in one private field inside it. Because the token is a plain class property (not <code>localStorage</code>), it's gone after a page reload, and every part of the app gets the same current value from one source of truth.</p>
<p>The <code>withCredentials: true</code> option on each request tells the browser to include cookies and accept <code>Set-Cookie</code> headers on cross-origin requests. Without it, the refresh cookie wouldn't be stored or sent when Angular and the API run on different origins.</p>
<p>In a real app, you'd want to connect the response to your application state, handle errors, and refresh on application startup if you want to restore a valid session after a reload.</p>
<pre><code class="language-ts">@Injectable({
  providedIn: 'root',
})
export class AuthService {
  private accessToken: string | null = null;

  private readonly apiUrl =
    'http://localhost:3000/auth';

  constructor(
    private readonly http: HttpClient,
  ) {}

  login(credentials: LoginRequest) {
    return this.http.post&lt;LoginResponse&gt;(
      `${this.apiUrl}/login`,
      credentials,
      {
        withCredentials: true,
      },
    );
  }

  refresh() {
    return this.http.post&lt;LoginResponse&gt;(
      `${this.apiUrl}/refresh`,
      {},
      {
        withCredentials: true,
      },
    );
  }

  logout() {
    return this.http.post(
      `${this.apiUrl}/logout`,
      {},
      {
        withCredentials: true,
      },
    );
  }

  setAccessToken(token: string) {
    this.accessToken = token;
  }

  getAccessToken() {
    return this.accessToken;
  }

  clearAccessToken() {
    this.accessToken = null;
  }
}
</code></pre>
<p>The access token is held in ordinary Angular memory and is lost on a full page reload. Because the refresh token is in an HttpOnly cookie, Angular can't read it to restore the access token directly. The app has to call the refresh endpoint on startup and handle failure by returning the user to a signed-out state.</p>
<p>You'll need to protect this endpoint against CSRF and configure it to allow credentials only from the intended frontend origin.</p>
<p>The important architecture is:</p>
<pre><code class="language-text">Access Token
    ↓
Angular memory

Refresh Token
    ↓
Browser HttpOnly Cookie
</code></pre>
<h3 id="heading-angular-interceptor">Angular Interceptor</h3>
<p>An interceptor is a piece of code that sits between your Angular app and the network. Every HTTP request made with <code>HttpClient</code> passes through it on the way out (and every response on the way back), so it can inspect or change them. That makes it useful for applying cross-cutting HTTP behavior in one place.</p>
<p>"Cross-cutting" means behavior that applies to many requests regardless of which feature made them, such as adding an authorization header, logging, or handling errors. Without an interceptor, you'd have to repeat that logic in every service that calls the API.</p>
<p>You should keep it narrowly scoped to your API, and make sure it doesn't overwrite an existing authorization header unexpectedly or attach credentials to unrelated origins.</p>
<p>Every protected request should automatically receive the access token when one is available. The interceptor should avoid attaching it to unrelated third-party URLs and shouldn't recursively attempt to refresh requests made to the login or refresh endpoints.</p>
<p>Every protected request should automatically receive:</p>
<pre><code class="language-http">Authorization: Bearer &lt;accessToken&gt;
</code></pre>
<pre><code class="language-ts">export const authInterceptor:
  HttpInterceptorFn = (req, next) =&gt; {

  const authService =
    inject(AuthService);

  const token =
    authService.getAccessToken();

  const authReq = token
    ? req.clone({
        setHeaders: {
          Authorization:
            `Bearer ${token}`,
        },
      })
    : req;

  return next(authReq);
};
</code></pre>
<h2 id="heading-16-handling-expired-access-tokens">16. Handling Expired Access Tokens</h2>
<p>Access tokens are short-lived on purpose, so every client eventually runs into an expired one. In this section, we'll look at how the app detects that case, what goes wrong when several requests fail at once, and how Angular and NestJS cooperate to fix it.</p>
<p>Suppose the access token is expired. The backend returns <code>401 Unauthorized</code> when the access token is missing, invalid, or expired. A <code>401</code> doesn't always mean the token expired, so refresh should be attempted only for relevant protected API requests and shouldn't loop indefinitely. If refresh fails, clear the in-memory token, stop retrying, and return the user to the signed-out flow.</p>
<p><strong>How do we know which case it is?</strong> By default, all three failures produce the same response: <code>401 Unauthorized</code>. But underneath, the JWT library knows why validation failed. It reports a <code>TokenExpiredError</code> for an expired token, a "No auth token" message when the header is missing, and errors such as an invalid signature for a tampered token. We can pass that reason to the client by overriding <code>handleRequest</code> in the JWT guard (the guard itself is explained in a later section):</p>
<pre><code class="language-ts">@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  handleRequest(err: any, user: any, info: any) {
    if (info?.name === 'TokenExpiredError') {
      throw new UnauthorizedException({
        message: 'Access token expired',
        code: 'TOKEN_EXPIRED',
      });
    }

    if (err || !user) {
      throw new UnauthorizedException({
        message: 'Unauthorized',
        code: 'UNAUTHORIZED',
      });
    }

    return user;
  }
}
</code></pre>
<p>Here, <code>info</code> carries the reason the JWT library rejected the token. If it's a <code>TokenExpiredError</code>, the guard answers with <code>401</code> and a machine-readable <code>code</code> of <code>TOKEN_EXPIRED</code>. Any other failure (missing or invalid token) gets a different code. Angular can then read <code>error.error.code</code> in its error handler and refresh only when the code says the token expired.</p>
<p>A second option is on the client: the access token's payload isn't encrypted, so Angular can decode the token and read its <code>exp</code> (expiry) claim to see that it's about to expire. The server's answer is still the authority, though, because the client's clock may be wrong.</p>
<p><strong>What should Angular do when the token has expired?</strong> Here are the steps in plain words:</p>
<ol>
<li>A request to a protected endpoint fails with <code>401</code>, and the response says the access token expired.</li>
<li>Angular pauses that failed request instead of showing an error to the user.</li>
<li>Angular calls <code>POST /auth/refresh</code>. The browser automatically attaches the HttpOnly refresh cookie, because Angular can't read it or add it itself.</li>
<li>The backend validates the refresh token, rotates it, sets a new refresh cookie, and returns a new access token.</li>
<li>Angular stores the new access token in memory.</li>
<li>Angular retries the original request, this time with the new token, and hands the result to the component as if nothing had happened.</li>
<li>If the refresh call itself fails (for example, the refresh token is expired, revoked, or was reused), Angular clears the in-memory token, stops retrying, and sends the user back to the login page.</li>
</ol>
<p>Two safeguards matter here: never try to refresh in response to a <code>401</code> from <code>/auth/login</code> or <code>/auth/refresh</code> (that would loop forever), and retry each original request only once.</p>
<h3 id="heading-the-concurrency-problem">The Concurrency Problem</h3>
<p>Imagine you have these five requests:</p>
<pre><code class="language-text">GET /users
GET /products
GET /orders
GET /profile
GET /notifications
</code></pre>
<p>All receive a 401.</p>
<p>Without protection, the following happens:</p>
<pre><code class="language-text">Request A → refresh R1
Request B → refresh R1
Request C → refresh R1
Request D → refresh R1
Request E → refresh R1
</code></pre>
<p>This happens easily: a dashboard page often fires several API calls at once, and they all carry the same access token, so if it expires, they all fail at the same moment. Each failed request independently decides to refresh, and each sends the same refresh cookie, R1.</p>
<p>But our refresh token rotation says:</p>
<pre><code class="language-text">R1 → R2
</code></pre>
<p>That means each refresh token is single-use. The first refresh request to reach the server uses R1 and gets R2 in exchange. R1 is now marked as used. The other four requests then arrive carrying R1, which the server sees as an already-used token. At best, those requests are rejected and the user is signed out for no good reason. At worst, the server treats it as token theft (we'll cover reuse detection later) and revokes the whole session.</p>
<p>So when we say "Only one should consume R1," we mean that only one refresh request should be sent with R1, and every other request that needs a new token should wait for that single result.</p>
<p>Therefore we need a shared refresh operation.</p>
<h3 id="heading-angular-refresh-lock">Angular Refresh Lock</h3>
<p>A refresh lock is a way for the Angular app to make sure only one refresh request is in flight at a time. It isn't a real operating-system lock. Instead, the service keeps a variable (<code>refreshInProgress$</code>) that holds the refresh request while it's running:</p>
<ul>
<li>The first caller finds the variable empty, starts the HTTP request, and stores it in the variable.</li>
<li>Every other caller that arrives while the refresh is running finds the variable filled and gets the same request back instead of starting a new one.</li>
<li><code>shareReplay(1)</code> makes all callers share one result: they all receive the same new access token, even if they subscribe slightly late.</li>
<li><code>finalize()</code> clears the variable when the request finishes, so a later expiry can start a fresh refresh.</li>
</ul>
<pre><code class="language-ts">private refreshInProgress$:
  Observable&lt;string&gt; | null = null;

refreshAccessToken():
  Observable&lt;string&gt; {

  if (this.refreshInProgress$) {
    return this.refreshInProgress$;
  }

  this.refreshInProgress$ =
    this.http
      .post&lt;LoginResponse&gt;(
        `${this.apiUrl}/refresh`,
        {},
        {
          withCredentials: true,
        },
      )
      .pipe(
        map(response =&gt; {
          this.setAccessToken(
            response.accessToken,
          );

          return response.accessToken;
        }),

        finalize(() =&gt; {
          this.refreshInProgress$ = null;
        }),

        shareReplay(1),
      );

  return this.refreshInProgress$;
}
</code></pre>
<p>The resulting structure looks like this:</p>
<pre><code class="language-text">A ─┐
B ─┤
C ─┼──→ one refresh request
D ─┤
E ─┘
</code></pre>
<p>This lock makes requests in the same Angular application instance share one refresh operation. It doesn't coordinate separate browser tabs, and it can't replace atomic token rotation on the server. The backend must still make sure that only one request can consume a particular active refresh token.</p>
<h3 id="heading-refresh-endpoint">Refresh Endpoint</h3>
<p>The refresh endpoint must read the cookie, hash the supplied token, find the matching active record, verify token and session expiry/revocation, and rotate the token safely. It should also return a new access token and set a replacement cookie only after the server-side operation succeeds.</p>
<p>The backend receives:</p>
<pre><code class="language-text">refresh_token cookie
</code></pre>
<p>Then:</p>
<pre><code class="language-text">Cookie
 ↓
SHA-256
 ↓
Find RefreshToken
 ↓
Check revokedAt
 ↓
Check expiration
 ↓
Find Session
 ↓
Check Session
 ↓
Rotate
 ↓
New Access Token
</code></pre>
<p>Here's what happens at each step:</p>
<ol>
<li>Read the cookie: The browser attached the raw <code>refresh_token</code> to the request. The server reads it from the incoming cookies.</li>
<li>Hash it: The server computes the SHA-256 hash, because the database only contains hashes, never raw tokens.</li>
<li>Find the record: It looks up the refresh-token record with that hash. No match means the token is unknown, so the request is rejected.</li>
<li>Check <code>revokedAt</code>: If the token was already revoked or used, this is a possible reuse, and the server follows the reuse-detection policy we'll describe shortly.</li>
<li>Check expiration: An expired refresh token is rejected, and the user has to log in again.</li>
<li>Find and check the session: The token's <code>sessionId</code> points to a session. If that session is missing, expired, or revoked (for example, after logout), the request is rejected even if the token itself looks fine.</li>
<li>Rotate: The server marks the old token as used, creates a new refresh token in the same session, and links them.</li>
<li>Respond: The server sets the new refresh token in an HttpOnly cookie and returns a new access token in the response body.</li>
</ol>
<h2 id="heading-17-refresh-token-rotation">17. Refresh Token Rotation</h2>
<p>Rotation replaces a refresh token after it's been successfully used. The old token must become unusable as part of the same logical operation that creates the replacement. Otherwise, retries or concurrent requests can produce inconsistent session state.</p>
<p>Suppose R1 is currently active. The client refreshes, and the server creates R2.</p>
<p>At that point, the server updates the old record to say two things: it's no longer valid, and which token took its place:</p>
<pre><code class="language-text">R1.revokedAt = now
R1.replacedBy = R2
</code></pre>
<p>The database now stores a small chain. R1 points forward to R2 through <code>replacedBy</code>, and R2 is the one currently active:</p>
<pre><code class="language-text">R1
 │
 └── replacedBy → R2

R2
 │
 └── active
</code></pre>
<p>The browser receives R2 in a new cookie, and from now on it only sends R2. On the next refresh, the same thing repeats: R2 is retired and R3 takes over.</p>
<pre><code class="language-text">R2 → R3
</code></pre>
<p>This is token rotation. At any moment, exactly one token in the chain is valid, and every older token is permanently dead, but still stored. Keeping those dead tokens is what makes the next feature possible.</p>
<h3 id="heading-reuse-detection">Reuse Detection</h3>
<p>If a token that was already rotated is presented again, it may indicate theft, but it can also be caused by a legitimate request race or a retry after a response was lost. The server needs an explicit policy for distinguishing between and handling these cases.</p>
<p>Suppose an attacker steals R1.</p>
<p>The legitimate user already used it:</p>
<pre><code class="language-text">R1 → R2
</code></pre>
<p>For that reason, the request should follow this path:</p>
<pre><code class="language-text">R1.revokedAt != null
</code></pre>
<p>If R1 appears again:</p>
<pre><code class="language-text">POST /auth/refresh
Cookie: R1
</code></pre>
<p>we treat this as suspicious token reuse.</p>
<p>A strong response is to revoke the entire session.</p>
<p>So:</p>
<pre><code class="language-text">Session A
 ├── R1 
 ├── R2 
 └── R3 
</code></pre>
<p>This is much stronger than simply rejecting R1.</p>
<h2 id="heading-18-why-we-have-sessions">18. Why We Have Sessions</h2>
<p>Our system could have used only a JWT per user, so why do we also have sessions?</p>
<p>Without sessions, the system has just a user and a token:</p>
<pre><code class="language-text">User
 ↓
JWT
</code></pre>
<p>The server knows who the token belongs to, but it has no concept of <em>where</em> the user is logged in. All tokens for a user look the same. That means the server can't tell the laptop login from the phone login, can't end just one of them, can't show the user a list of their logged-in devices, and can't tell which login a suspicious refresh attempt came from.</p>
<p>The only drastic option is to invalidate everything for that user, for example by changing the signing key or the user's token version.</p>
<p>With sessions, each login becomes its own record that tokens belong to:</p>
<pre><code class="language-text">User
 ├── Chrome
 │     └── Session A
 │
 ├── Android
 │     └── Session B
 │
 └── Firefox
       └── Session C
</code></pre>
<p>Now every refresh token and access token is tied to one session through <code>sessionId</code> / <code>sid</code>, and the server can act on one session without touching the others. For example, we can implement:</p>
<pre><code class="language-text">Logout current device
Logout all devices
View active sessions
Revoke one device
Detect suspicious activity
</code></pre>
<p>If someone steals the refresh token from the Android phone, we revoke Session B and the laptop and Firefox stay signed in. That per-device control is what sessions give us.</p>
<h2 id="heading-19-jwt-authentication-in-nestjs">19. JWT Authentication in NestJS</h2>
<p>On the server, we need a way to turn the <code>Authorization: Bearer &lt;token&gt;</code> header into a known user for every protected request. NestJS does this with Passport, using a JWT strategy that describes how to read and verify the token.</p>
<p>We'll use Passport:</p>
<pre><code class="language-ts">@Injectable()
export class JwtStrategy
  extends PassportStrategy(
    Strategy,
    'jwt',
  ) {

  constructor(
    private readonly configService:
      ConfigService,
    private readonly usersService:
      UsersService,
  ) {
    super({
      jwtFromRequest:
        ExtractJwt
          .fromAuthHeaderAsBearerToken(),

      ignoreExpiration: false,

      secretOrKey:
        configService.getOrThrow&lt;string&gt;(
          'JWT_ACCESS_SECRET',
        ),

      algorithms: ['HS256'],
    });
  }

  async validate(payload: {
    sub: string;
    sid: string;
    type: string;
  }) {

    if (payload.type !== 'access') {
      throw new UnauthorizedException();
    }

    const user =
      await this.usersService.findById(
        payload.sub,
      );

    if (!user) {
      throw new UnauthorizedException();
    }

    return {
      userId: user._id.toString(),
      sessionId: payload.sid,
      role: user.role,
      email: user.email,
    };
  }
}
</code></pre>
<p>Here's how authentication works in this code. It has two phases:</p>
<ol>
<li>First, the constructor configures token verification. <code>jwtFromRequest</code> says to take the token from the <code>Authorization: Bearer ...</code> header. <code>ignoreExpiration: false</code> means expired tokens are rejected. <code>secretOrKey</code> is the secret used to verify the signature, so tampered tokens fail. <code>algorithms: ['HS256']</code> restricts the accepted signing algorithm instead of trusting whatever the token claims. Passport performs all these checks before our own code runs.</li>
<li>Second, <code>validate()</code> runs only after the token is verified. It first checks that the <code>type</code> claim is <code>'access'</code> so no other kind of token can be used here. Then it loads the user from MongoDB using the <code>sub</code> claim, and rejects the request if the user no longer exists. Finally, it returns a small object (<code>userId</code>, <code>sessionId</code>, <code>role</code>, or <code>email</code>). Whatever <code>validate()</code> returns is attached to the request as <code>req.user</code>, which later guards and controllers use.</li>
</ol>
<p>The role comes from the database, not from the token, so a role change takes effect on the next request. Note that this version doesn't yet check that the session (<code>sid</code>) is still active. As I mentioned earlier, add that check if you need immediate revocation.</p>
<h3 id="heading-jwtauthguard">JwtAuthGuard</h3>
<p>First, what's a guard? A guard is a piece of code that decides whether a request is allowed to continue. The framework runs it <em>before</em> the actual route handler. If the guard allows the request, the handler runs. If it blocks it, the handler never runs.</p>
<p>This term appears in both frameworks, with the same idea:</p>
<ul>
<li>An <strong>Angular guard</strong> runs in the browser during navigation and decides whether the router may open a page (for example, redirecting to the login page if the user isn't signed in). It's a UX feature.</li>
<li>A <strong>NestJS guard</strong> is a class with a <code>canActivate()</code> method that runs on the server before a controller method. It decides whether the HTTP request may reach the endpoint. This is the one that provides actual security.</li>
</ul>
<p><code>JwtAuthGuard</code> is a NestJS guard. It's built from Passport's <code>AuthGuard('jwt')</code>, where <code>'jwt'</code> is the name we gave our <code>JwtStrategy</code>. When a request arrives, the guard runs the strategy: it extracts and verifies the token, calls <code>validate()</code>, and, if all goes well, puts the result on <code>req.user</code> and lets the request through. If anything fails, it responds with <code>401 Unauthorized</code>, and the controller never runs. It relies on verified server-side claims, not on values sent in arbitrary request fields.</p>
<pre><code class="language-ts">@Injectable()
export class JwtAuthGuard
  extends AuthGuard('jwt') {}
</code></pre>
<p>Now:</p>
<pre><code class="language-ts">@Get('me')
@UseGuards(JwtAuthGuard)
me(@Req() req: Request) {
  return req.user;
}
</code></pre>
<p>Here, <code>@UseGuards(JwtAuthGuard)</code> attaches the guard to the <code>me</code> endpoint. Only requests with a valid access token get through, and the handler returns the authenticated user that the strategy stored on <code>req.user</code>.</p>
<p>The backend becomes the true security boundary. Angular guards are only for navigation UX.</p>
<h3 id="heading-angular-guard-isnt-security">Angular Guard Isn't Security</h3>
<p>Angular guards improve navigation and user experience, but users can bypass browser code and call the API directly. So you should enforce all authentication and authorization rules in NestJS as well.</p>
<p>This is a very important rule:</p>
<pre><code class="language-text">Angular Guard
      ↓
UX / Navigation

NestJS Guard
      ↓
Security
</code></pre>
<p>An attacker can completely bypass Angular. For example, they can send requests directly from the command line with a tool like <code>curl</code>:</p>
<pre><code class="language-bash">curl ...
</code></pre>
<p>or with other tools that send raw HTTP requests without running your frontend at all:</p>
<pre><code class="language-text">Postman
Burp Suite
custom script
</code></pre>
<p>Postman is an API client, Burp Suite is a security-testing proxy that can capture and modify requests, and a custom script is any program that calls your API's URLs directly. None of them run your Angular code, so none of them are stopped by an Angular guard.</p>
<p>Therefore every sensitive endpoint must enforce authorization on the backend.</p>
<h2 id="heading-20-rbac">20. RBAC</h2>
<p>Authentication tells us <em>who</em> the user is. Next we need to decide what they're allowed to do. A common way to do that is with roles.</p>
<p>A role is a label attached to a user that describes a broad level of access. Our application uses three:</p>
<ul>
<li><code>USER</code>: a regular account. It can use the application normally and manage its own data.</li>
<li><code>MODERATOR</code>: a trusted account with extra powers over content or other users' behavior, such as removing inappropriate posts.</li>
<li><code>ADMIN</code>: a fully trusted account that can manage the system, such as listing, changing, or deleting user accounts.</li>
</ul>
<p>Role-Based Access Control (RBAC) maps users to roles and roles to broad capabilities. You should keep role assignment under trusted server-side control. For example, a registration request must never be allowed to set its own role.</p>
<p>Our roles are as follows:</p>
<pre><code class="language-ts">export enum UserRole {
  USER = 'user',
  MODERATOR = 'moderator',
  ADMIN = 'admin',
}
</code></pre>
<p>A role answers which broad actions a user may perform: "Can this person access the admin area at all?" That's different from resource-level authorization, which answers whether this user may act on this particular record: "Can this person open order #123?"</p>
<p>Two regular users both have the <code>USER</code> role, but neither should read the other's orders. So for every endpoint that works with a specific record (an order, a profile, a document), also check in the service layer that the record belongs to the current user, or that they have an explicit permission for it. Roles alone aren't enough for those endpoints.</p>
<p>In the next few subsections, we'll build the role-checking pieces: a decorator to declare which roles an endpoint needs, a guard that enforces it, and then an example of using them together.</p>
<h3 id="heading-roles">@Roles()</h3>
<p>We want a simple way to say, right on a controller method, which roles may call it. NestJS lets us attach custom information (called metadata) to a route with <code>SetMetadata</code>. The <code>@Roles()</code> decorator is a small wrapper around that. It stores the list of allowed roles on the route, so the guard that we write next can read it:</p>
<pre><code class="language-ts">export const ROLES_KEY = 'roles';

export const Roles =
  (...roles: UserRole[]) =&gt;
    SetMetadata(
      ROLES_KEY,
      roles,
    );
</code></pre>
<p>The decorator doesn't enforce anything by itself. It only labels the route. For example:</p>
<pre><code class="language-ts">@Roles(UserRole.ADMIN)
</code></pre>
<p>means:</p>
<pre><code class="language-text">Only ADMIN users
</code></pre>
<p>You can pass more than one role, such as <code>@Roles(UserRole.ADMIN, UserRole.MODERATOR)</code>, meaning either role is allowed.</p>
<h3 id="heading-rolesguard">RolesGuard</h3>
<p><code>RolesGuard</code> is the code that enforces what <code>@Roles()</code> declares. It uses NestJS's <code>Reflector</code> to read the roles stored on the route, and compares them with the role of the current user (<code>request.user</code>, which <code>JwtAuthGuard</code> already filled in).</p>
<pre><code class="language-ts">@Injectable()
export class RolesGuard
  implements CanActivate {

  constructor(
    private readonly reflector:
      Reflector,
  ) {}

  canActivate(
    context: ExecutionContext,
  ): boolean {

    const requiredRoles =
      this.reflector.getAllAndOverride&lt;
        UserRole[]
      &gt;(
        ROLES_KEY,
        [
          context.getHandler(),
          context.getClass(),
        ],
      );

    if (!requiredRoles) {
      return true;
    }

    const request =
      context
        .switchToHttp()
        .getRequest();

    const user =
      request.user;

    if (!user) {
      throw new UnauthorizedException();
    }

    if (
      !requiredRoles.includes(
        user.role,
      )
    ) {
      throw new ForbiddenException(
        'Insufficient permissions',
      );
    }

    return true;
  }
}
</code></pre>
<p>What's happening in this code:</p>
<ol>
<li><code>getAllAndOverride</code> reads the <code>roles</code> metadata, first from the method and then from the controller class, so a role set on a method overrides one set on the whole class.</li>
<li>If no roles are required (no <code>@Roles()</code>), the guard lets the request through.</li>
<li>It gets the current request and its <code>user</code>. If there's no user, authentication didn't happen, so it throws <code>401</code>.</li>
<li>If the user's role isn't in the list of required roles, it throws <code>403 Forbidden</code> ("Insufficient permissions").</li>
<li>Otherwise, it returns <code>true</code> and the request continues to the controller.</li>
</ol>
<h3 id="heading-using-rbac">Using RBAC</h3>
<p>Now we can combine everything on an endpoint. This route lists all users, which should only be allowed for admins:</p>
<pre><code class="language-ts">@Get('users')
@UseGuards(
  JwtAuthGuard,
  RolesGuard,
)
@Roles(UserRole.ADMIN)
findUsers() {
  return this.usersService.findAll();
}
</code></pre>
<p><code>@UseGuards(JwtAuthGuard, RolesGuard)</code> runs the two guards in order: first authenticate, then check the role. <code>@Roles(UserRole.ADMIN)</code> tells <code>RolesGuard</code> which role is needed. Order matters: <code>RolesGuard</code> depends on <code>req.user</code>, which only exists after <code>JwtAuthGuard</code> has run.</p>
<p>The request goes through this flow:</p>
<pre><code class="language-text">Request
   ↓
JWT valid?
   │
   ├── No → 401
   │
   ▼
User identified
   ↓
Role = admin?
   │
   ├── No → 403
   │
   ▼
Controller
</code></pre>
<h3 id="heading-401-vs-403">401 vs 403</h3>
<p>This distinction is extremely important, because the two codes tell the client two different things, and the client reacts differently to each.</p>
<h4 id="heading-401">401</h4>
<p>A <code>401 Unauthorized</code> response means the server doesn't know who you are, or couldn't verify it. The request has no valid identity. The fix is to authenticate (or re-authenticate), and in our app, a <code>401</code> is what triggers a token refresh or sends the user to login.</p>
<pre><code class="language-text">Authentication failed
</code></pre>
<p>Examples:</p>
<pre><code class="language-text">Missing token
Invalid token
Expired token
Invalid credentials
</code></pre>
<h4 id="heading-403">403</h4>
<p>A <code>403 Forbidden</code> response means the server knows exactly who you are, and you're not allowed to do this. Logging in again or refreshing the token won't help, because the identity was fine. The user simply doesn't have permission, so the client should show an "access denied" message instead of retrying.</p>
<pre><code class="language-text">Authentication succeeded
but authorization failed
</code></pre>
<p>Example:</p>
<pre><code class="language-text">User = USER
Required = ADMIN
</code></pre>
<p>This is important because mixing them up causes real problems: if you return <code>401</code> for a permissions problem, the Angular app will try to refresh and loop, and if you return <code>403</code> for a missing token, the app won't know it should re-authenticate. A quick way to remember them:</p>
<pre><code class="language-text">401 → Who are you?

403 → We know who you are,
      but you're not allowed.
</code></pre>
<h3 id="heading-public-routes">Public Routes</h3>
<p>If protection is the default, we need a way to mark the few endpoints that must stay open, such as login and registration. Instead of manually adding guards everywhere, we can create a <code>@Public()</code> decorator. It uses the same metadata technique as <code>@Roles()</code>:</p>
<pre><code class="language-ts">export const IS_PUBLIC_KEY =
  'isPublic';

export const Public = () =&gt;
  SetMetadata(
    IS_PUBLIC_KEY,
    true,
  );
</code></pre>
<p>Then we apply it to the routes that should be open, for example the login endpoint:</p>
<pre><code class="language-ts">@Post('login')
@Public()
login() {}
</code></pre>
<p>This allows us to make authentication guards global. Making a guard global means registering it once for the whole application (for example, as an <code>APP_GUARD</code>) so it runs on every route automatically, instead of adding <code>@UseGuards(JwtAuthGuard)</code> to each controller or method. The global guard checks for <code>@Public()</code> first: if the route has it, the request is allowed through, and otherwise normal JWT authentication runs.</p>
<p>The architecture becomes:</p>
<pre><code class="language-text">Request
  ↓
Global Auth Guard
  ↓
@Public()?
 ├── yes → allow
 └── no
      ↓
JWT authentication
      ↓
Authorization
</code></pre>
<p>This is often safer because new endpoints are protected by default. If a developer forgets to add a guard to a new route, it's still protected, and opening a route to the public has to be a deliberate choice.</p>
<h2 id="heading-21-csrf">21. CSRF</h2>
<p>Cross-Site Request Forgery matters when a browser automatically attaches credentials, such as cookies, to a request. HttpOnly protects cookie confidentiality from JavaScript but doesn't stop the browser from sending the cookie.</p>
<p>Our refresh token is stored in a cookie. Cookies have an important property: browsers automatically attach them to requests according to cookie rules.</p>
<p>That creates CSRF considerations. The main issue is this: a request is sent with the user's valid cookie, but the user never intended to send it. The server sees a valid cookie and can't tell by the cookie alone whether the request came from our own app or from another website. For state-changing endpoints such as <code>/auth/refresh</code> or <code>/auth/logout</code>, that lets a malicious site trigger actions in the context of a logged-in user.</p>
<p>Suppose:</p>
<pre><code class="language-text">User logged into our-app.com

then visits

evil.com
</code></pre>
<p>The malicious site may try to cause:</p>
<pre><code class="language-http">POST https://our-app.com/auth/refresh
</code></pre>
<p>The browser manages cookies automatically. To combat against this issue, we can add CSRF defenses. In the next subsections, we'll look at three: the <code>SameSite</code> cookie attribute, a CSRF token, and a guard that checks it.</p>
<h3 id="heading-samesite">SameSite</h3>
<p><code>SameSite</code> is a cookie attribute that tells the browser when it may send the cookie on requests that start from a different site. With <code>Strict</code>, the browser only sends the cookie when the request comes from the same site as the cookie. With <code>Lax</code>, it also sends it on top-level navigations such as clicking a link. With <code>None</code>, it sends it on all cross-site requests (and requires <code>Secure</code>).</p>
<p>Our refresh cookie can use:</p>
<pre><code class="language-ts">sameSite: 'strict'
</code></pre>
<p>This is a useful defense-in-depth setting, but it's not a complete CSRF strategy. Cookie behavior depends on the relationship between frontend and backend sites, cookie domain/path, and whether credentials are enabled in the client and CORS configuration.</p>
<p>But cookie behavior depends on whether the frontend and backend are same-origin, same-site, or cross-site.</p>
<p>For cross-site deployments, you may need:</p>
<pre><code class="language-text">SameSite=None
Secure=true
</code></pre>
<p>plus explicit CSRF protection. The client must use <code>withCredentials: true</code>, and the API must allow credentials for the exact trusted frontend origin. You should never combine credentialed requests with a wildcard CORS origin.</p>
<p>So, make sure you design your cookie configuration together with your deployment architecture. SameSite is defense in depth. It isn't a substitute for validating state-changing requests.</p>
<h3 id="heading-csrf-token">CSRF Token</h3>
<p>A CSRF token is a random value that the server gives to our own frontend, and that the frontend must send back with every state-changing request. A malicious site can make the browser attach cookies, but it can't read our cookies or set custom headers on our domain, so it can't produce the matching token. The server accepts the request only if the token in the header matches the one in the cookie.</p>
<p>A common pattern is:</p>
<pre><code class="language-text">HttpOnly Cookie
refresh_token

Regular Cookie
csrf_token
</code></pre>
<p>The <code>csrf_token</code> is a normal (not HttpOnly) cookie so that Angular can read it. Angular reads:</p>
<pre><code class="language-text">csrf_token
</code></pre>
<p>and sends it back in a custom header:</p>
<pre><code class="language-http">X-CSRF-Token: &lt;token&gt;
</code></pre>
<p>Then the server checks that the two values are the same:</p>
<pre><code class="language-text">Cookie csrf_token
        ==
X-CSRF-Token
</code></pre>
<p>The refresh token itself remains HttpOnly.</p>
<h3 id="heading-csrf-guard">CSRF Guard</h3>
<p>The CSRF guard is the NestJS guard that performs that check on the server. We'll look at the code, which skips safe methods (they don't change state) and rejects any other request whose cookie and header tokens are missing or different.</p>
<pre><code class="language-ts">@Injectable()
export class CsrfGuard
  implements CanActivate {

  canActivate(
    context: ExecutionContext,
  ): boolean {

    const request =
      context
        .switchToHttp()
        .getRequest();

    const safeMethods = [
      'GET',
      'HEAD',
      'OPTIONS',
    ];

    if (
      safeMethods.includes(
        request.method,
      )
    ) {
      return true;
    }

    const cookieToken =
      request.cookies?.csrf_token;

    const headerToken =
      request.headers[
        'x-csrf-token'
      ];

    if (
      !cookieToken ||
      !headerToken ||
      cookieToken !== headerToken
    ) {
      throw new ForbiddenException(
        'Invalid CSRF token',
      );
    }

    return true;
  }
}
</code></pre>
<p>In a production system, you'd want to compare the two token values using a constant-time comparison and consider checking the request's <code>Origin</code> as an additional defense. The application must also generate a cryptographically unpredictable CSRF token and provide it to Angular through a deliberate mechanism.</p>
<p>Comparing the cookie and header is only one part of the design, so you'll want to verify the complete flow against your actual frontend and backend domains and proxy configuration.</p>
<h2 id="heading-22-redis">22. Redis</h2>
<p>Redis is useful for short-lived shared state, including rate-limit counters, because multiple API instances can use the same store. It shouldn't become the only durable record of user identity or long-lived sessions unless that's an explicit architectural choice.</p>
<p>Redis isn't our main database here. In our case, MongoDB stores users, sessions, and RefreshTokens</p>
<p>Redis is useful for rate limits, temporary counters, short-lived locks, OTP state, temporary authentication state, and caching.</p>
<p>This is an important architectural principle: don't add Redis simply because production systems use Redis. Use it where its characteristics solve a real problem.</p>
<h3 id="heading-rate-limiting">Rate Limiting</h3>
<p>Rate limiting reduces abuse by limiting repeated attempts over a time window. You should choose limits based on endpoint risk and user experience, and return a consistent <code>429 Too Many Requests</code> response when a client exceeds them.</p>
<p>Consider:</p>
<pre><code class="language-text">POST /auth/login
</code></pre>
<p>An attacker can send 1000 requests in a short period.</p>
<p>We can maintain a Redis counter:</p>
<pre><code class="language-text">auth:login:ip:&lt;ip&gt;
</code></pre>
<p>and increment it like this:</p>
<pre><code class="language-ts">const attempts =
  await redisService.increment(
    key,
    60,
  );

if (attempts &gt; 10) {
  throw new TooManyRequestsException();
}
</code></pre>
<p>Here's what this code is doing. <code>key</code> is the counter's name, built from the pattern above (for example, <code>auth:login:ip:203.0.113.7</code>), so each IP address gets its own counter. <code>redisService.increment(key, 60)</code> is a helper that adds 1 to that counter in Redis and returns the new value. The <code>60</code> is the window length in seconds: the first time the key is created, it's given a time-to-live (TTL) of 60 seconds, after which Redis deletes it automatically and the count starts again.</p>
<p>Then the code compares the count with the limit. In this example, more than 10 login attempts from one IP within 60 seconds causes the request to be rejected with a <code>429 Too Many Requests</code> error instead of checking the password.</p>
<p>The first request creates:</p>
<pre><code class="language-text">counter = 1
TTL = 60 seconds
</code></pre>
<p>Then:</p>
<pre><code class="language-text">2
3
4
...
</code></pre>
<p>Because Redis is shared, the count is the same no matter which API instance handles the request. Note that <code>TooManyRequestsException</code> is a helper that produces the <code>429</code> response. If you don't have one in your project, you can throw an <code>HttpException</code> with status <code>429</code>.</p>
<h3 id="heading-dont-rate-limit-only-by-ip">Don't Rate Limit Only by IP</h3>
<p>IP-only rate limiting can hurt legitimate users.</p>
<p>For example:</p>
<pre><code class="language-text">Company
   ↓
NAT
   ↓
100 users
   ↓
same public IP
</code></pre>
<p>A better strategy can combine:</p>
<pre><code class="language-text">IP
+
Account identifier
+
IP + account
</code></pre>
<p>For example:</p>
<pre><code class="language-text">auth:login:ip:&lt;ip&gt;

auth:login:email:&lt;hash&gt;

auth:login:ip-email:&lt;ip&gt;:&lt;hash&gt;
</code></pre>
<p>Different limits can be applied to each dimension.</p>
<h3 id="heading-endpoints-worth-protecting">Endpoints Worth Protecting</h3>
<p>Authentication-related endpoints deserve special attention:</p>
<pre><code class="language-text">POST /auth/login
POST /auth/register
POST /auth/refresh
POST /auth/forgot-password
POST /auth/reset-password
POST /auth/verify-email
POST /auth/change-password
</code></pre>
<p>Especially:</p>
<pre><code class="language-text">login
refresh
forgot-password
</code></pre>
<p>because they're attractive targets for abuse.</p>
<h2 id="heading-23-cors">23. CORS</h2>
<p>CORS is a browser policy controlling which origins may read cross-origin responses. It's not authentication and doesn't stop non-browser clients from calling an API.</p>
<p>Two terms here need explaining. An <em>origin</em> is the combination of scheme, host, and port, such as <code>http://localhost:4200</code>. A <em>credentialed request</em> is a cross-origin request where the browser includes credentials, such as cookies, which is what Angular's <code>withCredentials: true</code> does.</p>
<p>For credentialed requests, the browser requires the API to name an explicit allowed origin (the exact origin of your frontend) rather than a wildcard. The wildcard is <code>*</code>, which means "any origin may do this," and browsers refuse to accept it when credentials are involved.</p>
<p>Angular might run at:</p>
<pre><code class="language-text">http://localhost:4200
</code></pre>
<p>while NestJS runs at:</p>
<pre><code class="language-text">http://localhost:3000
</code></pre>
<p>Because these are different origins (the ports differ), the browser applies CORS rules. We can configure the API like this:</p>
<pre><code class="language-ts">app.enableCors({
  origin:
    'http://localhost:4200',

  credentials: true,
});
</code></pre>
<p>This configuration does two things. <code>origin</code> tells the API to allow cross-origin requests from only the Angular app at <code>http://localhost:4200</code>, so the response includes a matching <code>Access-Control-Allow-Origin</code> header. <code>credentials: true</code> adds <code>Access-Control-Allow-Credentials: true</code>, which lets the browser send and accept cookies (like our refresh cookie) on those requests.</p>
<p>In production, don't use:</p>
<pre><code class="language-ts">origin: '*'
</code></pre>
<p>with credentialed requests. Use explicit trusted origins.</p>
<h2 id="heading-24-logout">24. Logout</h2>
<p>Logout should revoke the current server-side refresh/session state and clear the refresh cookie using matching cookie attributes. Clearing the Angular access token alone only signs the current UI out. It doesn't invalidate a stolen token on the server.</p>
<p>Logout should revoke the current session.</p>
<pre><code class="language-ts">@Post('logout')
@UseGuards(JwtAuthGuard)
async logout(
  @Req() req: Request,
  @Res({
    passthrough: true,
  })
  res: Response,
) {
  await this.sessionsService
    .revokeSession(
      req.user.sessionId,
    );

  res.clearCookie(
    'refresh_token',
    {
      httpOnly: true,
      secure:
        this.configService.get(
          'NODE_ENV',
        ) === 'production',
      sameSite: 'strict',
      path: '/auth',
    },
  );

  return {
    message:
      'Logged out successfully',
  };
}
</code></pre>
<p>Notice something important here: the current access JWT may remain technically valid until it expires. This is a deliberate trade-off.</p>
<h3 id="heading-logout-all-devices">Logout All Devices</h3>
<p>Logout-all should revoke the authenticated user’s active sessions and associated refresh tokens. Make sure the user ID comes from the verified request identity, not from an arbitrary ID submitted by the client.</p>
<p>Because we have Sessions:</p>
<pre><code class="language-text">User
 ├── Session A
 ├── Session B
 └── Session C
</code></pre>
<p>we can do the following:</p>
<pre><code class="language-ts">await sessionsService
  .revokeAllUserSessions(
    userId,
  );
</code></pre>
<p>What's happening here: <code>revokeAllUserSessions</code> finds every active session that belongs to this user in MongoDB and marks each one as revoked (and revokes their refresh tokens). The <code>userId</code> should come from the authenticated request (<code>req.user.userId</code>), never from the request body, so users can only log themselves out. This is the "sign out everywhere" button you see in many apps, and it's also useful after a password change or a suspected compromise.</p>
<p>The resulting structure looks like this:</p>
<pre><code class="language-text">Session A 
Session B 
Session C 
</code></pre>
<p>All three are now revoked. Any future refresh attempt fails, and every device has to log in again once its short-lived access token expires.</p>
<h2 id="heading-25-mongodb-transaction-for-rotation">25. MongoDB Transaction for Rotation</h2>
<p>When one refresh operation updates multiple MongoDB documents, those writes need consistent failure behavior. MongoDB multi-document transactions require a replica set (including a properly configured single-node replica set for local development) or a supported sharded deployment. They don't work on a standalone MongoDB server.</p>
<p>There's another production consideration.</p>
<p>Suppose rotation performs the following:</p>
<pre><code class="language-text">revoke R1
create R2
</code></pre>
<p>What if the application crashes between those operations?</p>
<p>We might get:</p>
<pre><code class="language-text">R1 = revoked
R2 = not created
</code></pre>
<p>So when appropriate, use a MongoDB transaction:</p>
<pre><code class="language-text">BEGIN
   ↓
revoke R1
   ↓
create R2
   ↓
update session
   ↓
COMMIT
</code></pre>
<p>If something fails, you can always rollback.</p>
<p>This makes rotation atomic only when the database deployment supports transactions and all related writes are included in the transaction.</p>
<p>MongoDB multi-document transactions require a replica set (including a properly configured single-node replica set for local development) or a supported sharded deployment. They don't work on a standalone MongoDB server. Conditional updates are still needed to ensure that only one request consumes a particular active refresh token.</p>
<h2 id="heading-26-complete-authentication-flow">26. Complete Authentication Flow</h2>
<p>Let's put everything together. The following subsections walk through the complete life of an authenticated user, in order: logging in, making ordinary requests, handling an expired token, what happens when a refresh token is stolen, and how authorization decisions are made.</p>
<h3 id="heading-login">Login</h3>
<pre><code class="language-text">Angular
   │
   │ email/password
   ▼
NestJS
   │
   ├── validate DTO
   ├── rate limit
   ├── find user
   ├── bcrypt.compare
   │
   ├── create session
   ├── create R1
   ├── store SHA-256(R1)
   ├── create access JWT
   │
   └── Set-Cookie R1
          │
          ▼
       Angular
       accessToken
</code></pre>
<h3 id="heading-normal-api-request">Normal API Request</h3>
<pre><code class="language-text">Angular
   │
   │ Authorization: Bearer JWT
   ▼
NestJS
   │
   ▼
JwtAuthGuard
   │
   ▼
JWT validation
   │
   ▼
User
   │
   ▼
RolesGuard
   │
   ▼
Controller
   │
   ▼
Service
</code></pre>
<h3 id="heading-expired-access-token">Expired Access Token</h3>
<pre><code class="language-text">Angular
   │
   ▼
API
   │
   ▼
401
   │
   ▼
refreshAccessToken()
   │
   ▼
POST /auth/refresh
   │
   └── HttpOnly Cookie R1
          │
          ▼
      NestJS
          │
          ├── hash R1
          ├── find token
          ├── check expiration
          ├── check revoked
          ├── check session
          │
          ├── revoke R1
          ├── create R2
          └── create new JWT
                  │
                  ▼
              Angular
                  │
                  ▼
             retry request
</code></pre>
<h3 id="heading-refresh-token-theft">Refresh Token Theft</h3>
<p>Suppose a legitimate client and an attacker both end up with the same refresh token, R1. This could happen if the attacker copied it from a compromised device or intercepted it somewhere.</p>
<p>The legitimate client refreshes first, and the server rotates the token:</p>
<pre><code class="language-text">Legitimate client:
R1 → R2
</code></pre>
<p>R1 is now marked as used and replaced. Later, the attacker tries to use their copy:</p>
<pre><code class="language-text">R1
</code></pre>
<p>The server looks up R1, finds it, and sees that it was already used:</p>
<pre><code class="language-text">R1.revokedAt != null
</code></pre>
<p>A valid refresh token would never be presented a second time by a correct client, so the server treats this as a sign that two parties have the same token. Rather than just rejecting the attacker's request, it responds by shutting the whole session down:</p>
<pre><code class="language-text">Token reuse detected
       ↓
Revoke session
       ↓
Force re-authentication
</code></pre>
<p>Revoking the session also kills R2, which the legitimate user holds, so the attacker can't simply wait and use the newest token. The legitimate user is signed out and has to log in again, which is an inconvenience, but the attacker's access ends. The user logging in again creates a brand-new session with fresh tokens the attacker doesn't have.</p>
<p>Reuse detection is useful only when the server can distinguish a previously rotated token from a valid current token and apply a defined response. When reuse is confirmed, you should revoke the affected session (or token family) and require the user to authenticate again.</p>
<p>The lookup, old-token revocation, replacement-token creation, and session updates must be atomic. Otherwise, simultaneous refresh requests can create race conditions. Be careful not to treat every duplicate request as theft without considering legitimate parallel requests or a retry after a lost response.</p>
<h3 id="heading-authorization-flow">Authorization Flow</h3>
<p>For:</p>
<pre><code class="language-http">DELETE /users/123
</code></pre>
<p>we have:</p>
<pre><code class="language-text">Request
   ↓
Authentication
   ↓
user = {
   id: 123,
   role: USER
}
   ↓
RolesGuard
   ↓
Required = ADMIN
   ↓
USER != ADMIN
   ↓
403 Forbidden
</code></pre>
<h2 id="heading-27-security-review">27. Security Review</h2>
<p>Use this as a review checklist, not as proof that every control is fully implemented or production-ready. Verify each item against the actual code, deployment settings, and automated tests:</p>
<h3 id="heading-passwords">Passwords</h3>
<pre><code class="language-text"> Password hashing
 No plaintext passwords
 Strong password policy
</code></pre>
<h3 id="heading-jwt">JWT</h3>
<pre><code class="language-text"> Short-lived access tokens
 Strong secret
 Explicit algorithm
 Minimal payload
</code></pre>
<h3 id="heading-refresh-tokens">Refresh Tokens</h3>
<pre><code class="language-text"> Cryptographically random
 SHA-256 hash at rest
 HttpOnly cookie
 Secure cookie in production
 SameSite policy
 Rotation
 Reuse detection
</code></pre>
<h3 id="heading-sessions">Sessions</h3>
<pre><code class="language-text"> Session per device
 Current-session logout
 Logout all
 Session revocation
</code></pre>
<h3 id="heading-authorization">Authorization</h3>
<pre><code class="language-text"> JwtAuthGuard
 RolesGuard
 @Roles()
 401 vs 403 separation
</code></pre>
<h3 id="heading-browser-security">Browser Security</h3>
<pre><code class="language-text"> CSRF protection
 CORS restrictions
 HttpOnly cookies
</code></pre>
<h3 id="heading-abuse-protection">Abuse Protection</h3>
<pre><code class="language-text"> Redis rate limiting
 Login protection
 Refresh protection
</code></pre>
<h3 id="heading-api-security">API Security</h3>
<pre><code class="language-text"> DTO validation
 whitelist
 forbidNonWhitelisted
 Database constraints
 Explicit input mapping
</code></pre>
<h2 id="heading-28-things-we-should-add-later">28. Things We Should Add Later</h2>
<p>A real production identity system needs more than the core login and refresh flow. The items below are additional capabilities, not features that should be assumed to exist unless they're implemented, configured, and tested in the application.</p>
<h3 id="heading-email-verification">Email Verification</h3>
<pre><code class="language-text">Register
   ↓
Verification Email
   ↓
Verify Token
   ↓
emailVerified = true
</code></pre>
<h3 id="heading-password-reset">Password Reset</h3>
<pre><code class="language-text">Forgot Password
      ↓
Reset Token
      ↓
New Password
      ↓
Revoke existing sessions
</code></pre>
<h3 id="heading-mfa">MFA</h3>
<pre><code class="language-text">Password
   +
Authenticator / Passkey / OTP
</code></pre>
<h3 id="heading-security-events">Security Events</h3>
<p>Log:</p>
<pre><code class="language-text">Login success
Login failure
Logout
Password change
Password reset
Refresh reuse detection
Session revoked
Role changed
</code></pre>
<h3 id="heading-permission-based-authorization">Permission-based Authorization</h3>
<p>Instead of:</p>
<pre><code class="language-ts">@Roles(UserRole.ADMIN)
</code></pre>
<p>we can eventually have:</p>
<pre><code class="language-ts">@Permissions(
  Permission.USERS_READ,
  Permission.USERS_DELETE,
)
</code></pre>
<p>which scales better for complex systems.</p>
<h2 id="heading-29-the-most-important-architectural-lessons">29. The Most Important Architectural Lessons</h2>
<p>The biggest lessons from this system are the design decisions.</p>
<h3 id="heading-lesson-1">Lesson 1:</h3>
<p>Authentication and authorization are different problems.</p>
<pre><code class="language-text">Authentication
Who are you?

Authorization
What can you do?
</code></pre>
<h3 id="heading-lesson-2">Lesson 2:</h3>
<p>A User is not a Session.</p>
<pre><code class="language-text">User
 ├── Session A
 ├── Session B
 └── Session C
</code></pre>
<h3 id="heading-lesson-3">Lesson 3:</h3>
<p>A refresh token isn't necessarily a JWT. A random opaque token can be simpler and safer when the server already stores session state.</p>
<h3 id="heading-lesson-4">Lesson 4:</h3>
<p>Never store refresh tokens in plaintext.</p>
<p>Store them like this:</p>
<pre><code class="language-text">SHA256(refreshToken)
</code></pre>
<p>instead.</p>
<h3 id="heading-lesson-5">Lesson 5:</h3>
<p>Refresh-token rotation changes the security model.</p>
<pre><code class="language-text">R1 → R2 → R3
</code></pre>
<p>allows us to detect reuse.</p>
<h3 id="heading-lesson-6">Lesson 6:</h3>
<p>Frontend guards aren't security boundaries. Backend authorization is mandatory.</p>
<h3 id="heading-lesson-7">Lesson 7:</h3>
<p>Cookies introduce CSRF considerations. HttpOnly protects against JavaScript reading the cookie, but it doesn't by itself eliminate CSRF.</p>
<h3 id="heading-lesson-8">Lesson 8:</h3>
<p>Rate limiting is part of authentication security. A secure password system without brute-force protection is incomplete.</p>
<h3 id="heading-lesson-9">Lesson 9:</h3>
<p>Concurrency is part of security. A refresh-token rotation system must account for multiple simultaneous requests.</p>
<h3 id="heading-lesson-10">Lesson 10:</h3>
<p>Production security is layered.</p>
<pre><code class="language-text">TLS
 ↓
CORS
 ↓
CSRF
 ↓
Authentication
 ↓
Authorization
 ↓
Validation
 ↓
Rate Limiting
 ↓
Database Constraints
 ↓
Session Security
 ↓
Monitoring
</code></pre>
<p>No single mechanism is enough.</p>
<h2 id="heading-30-final-architecture">30. Final Architecture</h2>
<p>Our complete system can now be visualized like this:</p>
<pre><code class="language-text">                         ┌───────────────┐
                         │    Angular    │
                         └───────┬───────┘
                                 │
                    ┌────────────┴────────────┐
                    │                         │
             Access Token              Refresh Cookie
                    │                         │
             Memory only                  HttpOnly
                    │                         │
                    ▼                         ▼
              Authorization              CSRF
                 Header                 Protection
                    │                         │
                    └────────────┬────────────┘
                                 │
                                 ▼
                         ┌───────────────┐
                         │    NestJS     │
                         └───────┬───────┘
                                 │
                 ┌───────────────┼───────────────┐
                 │               │               │
                 ▼               ▼               ▼
          Rate Limiting    Authentication   Authorization
             Redis          JWT Strategy      RolesGuard
                 │               │               │
                 └───────────────┼───────────────┘
                                 │
                                 ▼
                           Application
                             Service
                                 │
                       ┌─────────┴─────────┐
                       ▼                   ▼
                   MongoDB               Redis
                       │                   │
              ┌────────┼────────┐          │
              │        │        │          │
             Users  Sessions Refresh    Rate Limits
                            Tokens       Locks
</code></pre>
<p>This gives us a security-oriented architecture to build on. Whether it's appropriate for production depends on the completeness of the implementation, threat model, deployment configuration, operational monitoring, and security tests.</p>
<p>Treat the diagram as a map of responsibilities rather than a guarantee that every control is already implemented.</p>
<p>The important thing is that each mechanism has a specific responsibility:</p>
<pre><code class="language-text">JWT
→ short-lived authentication

Refresh Token
→ session continuation

Session
→ device/session lifecycle

RBAC
→ authorization

CSRF
→ protection for cookie-based state-changing requests

Redis
→ rate limiting and temporary/distributed state

MongoDB
→ persistent identity/session data

Angular Interceptor
→ client-side token lifecycle

NestJS Guards
→ server-side security boundary
</code></pre>
<p>Once these responsibilities are clearly separated, the system becomes much easier to reason about, test, extend, and secure.</p>
<h2 id="heading-explore-the-source-code">Explore the Source Code</h2>
<p>You can explore the source code for this project on GitHub:</p>
<p><a href="https://github.com/abanoubkerols/Authentication-AuthorizationSystemWithAngularAndNestJS"><strong>Authentication &amp; Authorization System with Angular and NestJS</strong></a></p>
<p>The repository provides a practical reference for the concepts discussed in this article. Feel free to explore the implementation, review the code, and experiment with the architecture as you learn how authentication and authorization work together in a modern web application.</p>
<p>If you find it helpful, consider starring the repository on GitHub.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Wearables Can Turn Your Body Into a Dashboard ]]>
                </title>
                <description>
                    <![CDATA[ Have you ever found yourself waking up feeling perfectly normal and then being told by your wearable app that you've slept poorly? And perhaps not only that, but somehow finding yourself starting to f ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-wearables-can-turn-your-body-into-a-dashboard/</link>
                <guid isPermaLink="false">6b0740e9d9c19e6e465e6cbf</guid>
                
                    <category>
                        <![CDATA[ Wearable Technology ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Wearables ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Shradha Puri ]]>
                </dc:creator>
                <pubDate>Wed, 25 Nov 2026 20:11:21 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/6103d1de-159f-474e-9981-b1c84778c5ff.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Have you ever found yourself waking up feeling perfectly normal and then being told by your wearable app that you've slept poorly? And perhaps not only that, but somehow finding yourself starting to feel a bit tired just because of it? Well, yeah, me too.</p>
<p>As a wearables person, I'm definitely not going to recommend that you give up on your tracking device and put it into a drawer. But there are some things we should discuss about when a number starts being valued above your actual feelings and how you can use your smart device effectively.</p>
<h3 id="heading-what-well-cover">What We'll Cover:</h3>
<ul>
<li><a href="#heading-morning-scores-and-how-they-affect-your-day">Morning Scores and How They Affect Your Day</a></li>
<li><a href="#heading-enter-orthosomnia">Enter Orthosomnia</a></li>
<li><a href="#heading-obsessing-about-the-number-makes-you-sleep-worse">Obsessing About the Number Makes You Sleep Worse</a></li>
<li><a href="#heading-how-accurate-is-your-dashboard">How Accurate Is Your Dashboard?</a></li>
<li><a href="#heading-all-this-goes-beyond-sleep">All this Goes Beyond Sleep</a></li>
<li><a href="#heading-when-helpful-app-features-become-a-source-of-pressure">When Helpful App Features Become a Source of Pressure</a></li>
<li><a href="#heading-why-your-score-can-feel-so-convincing">Why Your Score Can Feel So Convincing</a></li>
<li><a href="#heading-the-jewelry-problem">The Jewelry Problem</a></li>
<li><a href="#heading-where-tracking-genuinely-helps">Where Tracking Genuinely Helps</a></li>
<li><a href="#heading-what-id-actually-do">What I'd Actually Do</a></li>
<li><a href="#heading-wrapping-up">Wrapping Up</a></li>
</ul>
<h2 id="heading-morning-scores-and-how-they-affect-your-day">Morning Scores and How They Affect Your Day</h2>
<p>Readiness scores and sleep scores are designed to be glanceable. This is their key advantage. The problem is that glancing leads to checking, which leads to checking becoming an uncontrollable addiction. You reach for your smartphone before you even drink your first glass of water in the morning and receive a judgement about your own body.</p>
<p>In case of a high score, you feel great. In case of a low score, you look for reasons why you don't feel great. Your legs are heavy? Sure, sounds right. Your throat feels scratchy? Yep, most likely. But you felt just great 5 minutes ago.</p>
<p>There are a lot of discussions about sensors, battery life, and titanium finish (I'm guilty of this, too). But people spend little to no time on discussing the experience of having your health grade updated daily.</p>
<p>It also impacts your behavior. People avoid working out when the app says their recovery level is low and other people train when the score is green even if they feel terrible. In any case, the app makes a decision for you that your body used to make.</p>
<h2 id="heading-enter-orthosomnia">Enter Orthosomnia</h2>
<p>Sleep gave a name to this phenomenon. In 2017, researchers from Rush University and Northwestern <a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC5263088/"><u>described three patients</u></a> in a case series in the Journal of Clinical Sleep Medicine. The patients' sleep complaints came mostly from their tracker data. Stretches of light or restless sleep on the app had convinced them they had insomnia or weren't getting enough rest. The authors called it orthosomnia, or an obsession with "good" sleep (which is a nod to orthorexia, the unhealthy preoccupation with eating "correctly").</p>
<p>The part that really caught my attention is that one of the patients, a lady who had trouble feeling refreshed, believed her Fitbit over a lab study that demonstrated that she got plenty of deep sleep. It became quite difficult for anyone to convince her otherwise.</p>
<p>That being said, the study only focused on three cases so it's certainly not extensive. I won't go into too much hype about it. But if you've experienced seeing (and perhaps wincing at) your sleep score after waking up at 7 am, then you'll understand what I mean.</p>
<h2 id="heading-obsessing-about-the-number-makes-you-sleep-worse">Obsessing About the Number Makes You Sleep Worse</h2>
<p>There's one point from the <a href="https://www.rushu.rush.edu/news/sleep-trackers-can-prompt-sleep-problems"><u>write-up about Rush University</u></a> researchers that I'll remember forever. The subjects of the study were basically increasing the amount of sleep shown by their trackers by spending more and more hours in bed. But this goes against the recommendation of sleep therapists. So a device which is meant to improve a person's sleep was encouraging them to develop habits which hinder good sleep.</p>
<p>Dr. Kelly Glazer Baron, the first author of the study, also mentioned that these devices can't differentiate between light and deep sleep and may treat even reading in bed as sleep. She also emphasized that such devices can't be used to diagnose sleep apnea.</p>
<h2 id="heading-how-accurate-is-your-dashboard">How Accurate Is Your Dashboard?</h2>
<p>This is a good question, because if all the data were perfectly measured, it wouldn't really matter. And in fact, wearables can actually deal with the basics pretty well. Distinguishing between asleep or awake periods and measuring their duration, for example. But estimating sleep stages is when they have a harder time: the classic deep, light, and REM classification we're all interested in.</p>
<p><a href="https://www.mdpi.com/1424-8220/24/20/6532"><u>A 2024 study in the journal Sensors</u></a> compared the performance of Oura Ring Gen3, Fitbit Sense 2, and Apple Watch Series 8 to polysomnography (PSG), which is the laboratory method gold standard. The test was carried out using 35 healthy volunteers, aged 20 to 50 years, during one night.</p>
<p>The results were interesting. All three wearables produced total sleep duration estimates that were statistically similar to the PSG results. They also detected sleep periods with at least 95% sensitivity (more on sensitivity below). But their ability to identify individual sleep stages varied considerably.</p>
<p>For light, deep, and REM sleep, the sensitivity results were:</p>
<ul>
<li><strong>Oura Ring Gen 3:</strong> 78.2% for light sleep, 79.5% for deep sleep, and 76% for REM sleep.</li>
<li><strong>Fitbit Sense 2:</strong> 78% for light sleep, 61.7% for deep sleep, and 67.3% for REM sleep.</li>
<li><strong>Apple Watch Series 8:</strong> 86.1% for light sleep, 50.5% for deep sleep, and 82.6% for REM sleep.</li>
</ul>
<p>These numbers tell us that even when a wearable can estimate how long you slept reasonably well, it may struggle to identify exactly which sleep stage you were in. For example, the Apple Watch identified only 50.5% of the deep-sleep periods recorded by PSG. That's quite a difference when we're talking about something as specific as sleep stages.</p>
<p>It's important to understand that sensitivity doesn't tell the whole story. It measures how often a device correctly identifies a particular sleep stage when PSG detects it, but it doesn't tell us how often the device's own sleep-stage predictions are correct. So these percentages are useful for understanding where wearables struggle, but they shouldn't be treated as an overall accuracy score.</p>
<p>There were also differences in the estimated duration of individual stages. Oura's estimates of wake, light, deep, and REM sleep were not significantly different from PSG. Fitbit overestimated light sleep by 18 minutes and underestimated deep sleep by 15 minutes. The Apple Watch underestimated deep sleep by 43 minutes and overestimated light sleep by 45 minutes.</p>
<p>As an Oura user myself, I find its sleep tracking useful, but these results show why I wouldn't treat every number as an exact measurement. The study suggests that wearables can be quite helpful in estimating overall sleep duration, while individual sleep-stage readings still have limitations. It's also worth remembering that this was a single-night study involving healthy sleepers, so we shouldn't assume the same results will apply to everyone or across different nights.</p>
<p>So, when your app tells you that you got 41 minutes of deep sleep, don't immediately assume that's exactly what happened. It's an estimate based on sensor data, not a laboratory measurement.</p>
<h2 id="heading-all-this-goes-beyond-sleep">All this Goes Beyond Sleep</h2>
<p>Sleep gets all the credit, but heart rate, HRV, stress numbers and step counts can do exactly the same thing to your mind.</p>
<p>In a 2020 study, <a href="https://humanities.ku.dk/news/2020/fitness-watches-generate-useful-information-but-increase-patient-anxiety/"><u>researchers at the University of Copenhagen</u></a> tracked 27 heart disease patients with arrhythmias or pacemakers for six months using Fitbits. They monitored sleep quality, heart rate, and physical activity.</p>
<p>Participants learned more about their health conditions and became motivated to exercise. But on the other hand, they became more anxious. Bad sleep numbers would frighten them and failing to achieve 10,000 steps per day made them feel guilty. Tariq Osman Andersen, one of the researchers, said that the overall effect of self-monitoring was "more problematic than beneficial."</p>
<p>This was a relatively small sample size with a certain health condition, so I don't want to generalize too much here about the overall benefits of sleep and fitness tracking. But the idea can apply to anyone. A concerning number without any additional information or context is easy to interpret as a danger signal.</p>
<h2 id="heading-when-helpful-app-features-become-a-source-of-pressure">When Helpful App Features Become a Source of Pressure</h2>
<p>A 2024 systematic review published in the <a href="https://journals.sagepub.com/doi/10.1177/07439156231224731"><u>Journal of Public Policy &amp; Marketing</u></a> explored the negative effects of health and fitness technologies. The researchers reviewed 65 publications and found that 42 of them (64.6%) reported negative emotional outcomes associated with these technologies. Guilt, pressure, stress, anxiety, and frustration were among the most commonly reported feelings.</p>
<p>But what I find interesting here is that the problem isn't necessarily the tracking itself. Some of the features designed to keep people motivated can also become a source of pressure.</p>
<p>The review identified unmet goals and negative feedback as two particularly important examples. Failure to achieve goals was discussed in 23 publications, while negative feedback appeared in 15. Reminders and notifications were also linked to feelings of stress and annoyance.</p>
<p>Think about daily goals, for example. Your wearable encourages you to complete 10,000 steps, close your activity rings, or maintain a sleep schedule. These targets can be useful, but repeatedly failing to achieve them can leave you feeling guilty or disappointed.</p>
<p>The same goes for feedback. Notifications reminding you about missed goals or showing poor performance can make you feel as though you're falling behind, even when you're making reasonable progress.</p>
<p>Then there's the gamification aspect. Leaderboards, achievement badges, streaks and social competitions encourage people to stay active and keep using their devices. But they can also make users compare their performance with others. When someone consistently sees their friends taking more steps or achieving better results, it can create unnecessary pressure and frustration.</p>
<p>This doesn't mean these features are inherently bad or that everyone will experience these problems. The review found associations between certain app features and negative emotional experiences, rather than proving that these features directly cause them in every user.</p>
<p>It makes sense when you think about it. These applications are designed to encourage you to check your progress, achieve your goals, and keep improving. But sometimes, the constant reminders of what you haven't achieved can become more noticeable than the progress you have actually made.</p>
<h2 id="heading-why-your-score-can-feel-so-convincing">Why Your Score Can Feel So Convincing</h2>
<p>The number seems objective because it was read from the sensor and displayed on a neat app. In contrast, your own sense of being tired is vague and annoying, so the number becomes more believable even though it's not supposed to be so.</p>
<p>Also, the apps almost never inform you of the degree of uncertainty of the estimate. There's no small note saying that the result is an approximation with an error range. You only see "62" in red. Because the scores are yours, a low score is something very personal.</p>
<p>Things are even worse when you're already stressed out. If you're concerned about sleeping poorly, a poor score just proves it and can feel like it manifests it and you become stressed about the score as well.</p>
<h2 id="heading-the-jewelry-problem">The Jewelry Problem</h2>
<p>This one is unique to the area I'm talking about. The whole idea of smart rings and good-looking watches is that you simply forget they're there. You wear them to the gym, to dinner, and to bed. That's some serious design there.</p>
<p>That also means that the monitoring never ends and the scoring continues as well. A cumbersome device that's removed before bed takes a rest automatically. Not so with a ring you forget about.</p>
<h2 id="heading-where-tracking-genuinely-helps">Where Tracking Genuinely Helps</h2>
<p>I'm not trying to say that this data is pointless, since it isn't. Realizing that you have poor sleep from eating late dinners or traveling a lot can ruin your whole week, but it can be valid information. It can even help you realize that you've been living on five hours of sleep a day for a month, which might encourage you to make some changes. After all, these applications are great at picking up patterns.</p>
<p>This is where the problem lies: when you use the same application to assess one night's sleep or how you feel on one particular morning, that's not the best information. Patterns over time hold the most valuable data. One individual assessment is nothing more than noise.</p>
<h2 id="heading-what-id-actually-do">What I'd Actually Do</h2>
<p>I'm not anti-tracking. I just think you should set a few ground rules to help you use the app in a helpful way.</p>
<ul>
<li>Look at weekly trends, not single nights. One bad score tells you almost nothing.</li>
<li>Check how you feel first, then open the app. If you feel fine, the score doesn't matter nearly as much.</li>
<li>Turn off notifications that nudge you about sleep or stress.</li>
<li>If a number makes you feel worse for a couple of weeks straight, take a break. A week without your ring is fine. See how you feel without it.</li>
<li>For real symptoms, see a doctor. Trackers can give you something to ask about, but they can't diagnose you.</li>
</ul>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>The technology isn't necessarily the bad thing here. My study of the existing literature reveals that the problem arises when the number starts to overrule your personal experience and feelings. And we shouldn't forget that we're all able to track our own health and how we feel without these tools.</p>
<p>Still, wearables are great at detecting patterns and they're very good at basics. Just remember that anything else is just an educated guess.</p>
<p>So I encourage you to look at the numbers, take and use what's valuable to you, and move on with your life.</p>
<p>Put on the ring, appreciate the data, and every once in a while check in with yourself about how you actually feel rather than what the app suggests you should feel. If there's disagreement, I'd believe yourself over a device.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
