<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mbaocha Jonathan on Medium]]></title>
        <description><![CDATA[Stories by Mbaocha Jonathan on Medium]]></description>
        <link>https://medium.com/@mbaochajonathan?source=rss-ccb9dee6e319------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Mbaocha Jonathan on Medium</title>
            <link>https://medium.com/@mbaochajonathan?source=rss-ccb9dee6e319------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 00:40:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mbaochajonathan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Why Your Container Can’t Find “localhost”: A Docker Networking Story]]></title>
            <link>https://medium.com/@mbaochajonathan/why-your-container-cant-find-localhost-a-docker-networking-story-bbc084b0309e?source=rss-ccb9dee6e319------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbc084b0309e</guid>
            <dc:creator><![CDATA[Mbaocha Jonathan]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 15:36:00 GMT</pubDate>
            <atom:updated>2026-07-15T15:36:00.797Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Day 1 to Hero — Networking</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gj6w_AiH8KcyDXBPPsi7Bg.png" /></figure><p>Before diving into Docker networking itself, I wanted to get one thing straight first: was this actually new territory, or something I already half-knew without realizing it? I didn’t want to spend the whole day circling concepts I’d already absorbed elsewhere.</p><p>So the starting point became a comparison — what I already understood versus what networking actually means inside Docker.</p><h3>What Networking Actually Means, in Plain Terms</h3><p>In the simplest possible terms, no technical jargon attached: networking is how two things that aren’t the same program manage to send information to each other anyway.</p><p>Picture two friends in separate rooms, trying to communicate. They need three things to make that work: a way to know <em>where</em> the other person actually is, some channel to send something across — a hallway, a phone line, whatever’s available — and an agreed way of speaking, so both sides actually understand each other once the message arrives.</p><p>Computer networking is the exact same three requirements, just formalized. An <strong>address</strong> — something unique identifying where the other side is, like an IP address. A <strong>channel</strong> — the actual path data travels across, whether that’s wifi, ethernet, or a virtual network Docker creates on its own. And a <strong>protocol</strong> — the agreed rules for the conversation itself; HTTP, for instance, is just “here’s how to phrase a request, here’s how to phrase a response.”</p><p>That definition alone didn’t feel like it justified a whole separate topic, because I was already living inside it every day without naming it. My DATABASE_URL sitting in .env — that&#39;s an address, plain and simple, telling my app exactly where to find Postgres. My server&#39;s URL, and the CORS_ORIGIN I configure so my frontend is even allowed to talk to it — that&#39;s the same address-plus-permission idea, just guarding the <em>other</em> direction of the conversation. Connection strings and API calls were address, channel, and protocol the whole time, just never labeled that way.</p><p>But then, all of this configuration — the database URL, the CORS origin — lives in my .env file. And from earlier lessons, I already knew Docker lets you inject environment variables straight into a container:</p><pre>docker run -e DATABASE_URL=... -e CORS_ORIGIN=... myapp</pre><p>So if that’s true, where does networking actually come into it? If I can just hand my container the right values through -e, why isn&#39;t that the end of the story?</p><h3>The Gap: A DB URL Isn’t a Network Connection</h3><p>Here’s what I was missing: a DB URL and a network connection aren’t the same thing. A DB URL is just an <em>address</em> — nothing more. On one machine, localhost inside that address works, because everything sharing that machine — my app, my database — shares the same network stack too.</p><p>Containerize both the app and the database, and localhost stops meaning what I assumed it meant. Inside a container, localhost refers to <em>that container, and nothing else</em>. My Express container asking for localhost:5432 isn&#39;t reaching next door into a Postgres container — it&#39;s looking inside itself, and finding nothing there at all.</p><p>The DB URL was never the connection. It was only ever the address. Something else has to exist to make that address findable in the first place — and that’s the actual gap networking fills.</p><h3>How a Container Actually Gets on a Network</h3><p>The course I’m using went fairly deep here — virtual ethernet pairs, bridges, the whole mechanism underneath. In my own opinion, going that deep isn’t actually necessary to work effectively with Docker day to day. What I actually took from it, stripped down to the one thing worth keeping, is this: understanding veth pairs and bridges at the implementation level mostly isn&#39;t going to move the needle on real DevOps work. What actually matters — and what gets used constantly — is the outcome. Containers on the same Docker network can reach each other by name. Containers on different networks can&#39;t. Everything from here on is that one idea, demonstrated.</p><h3>Network Drivers</h3><p>Going through Docker’s own docs surfaced something worth noting: the Docker Engine ships with a number of different network drivers, not just one — and among them, a default bridge network that’s created automatically the moment Docker itself is installed.</p><p>In summary, four drivers stood out to me as actually worth knowing well — not because they’re the only ones that exist, but because these are the ones I’ll realistically reach for most often. Here’s a brief rundown of each.</p><p><strong>Bridge (custom)</strong> — the everyday driver. It’s what you reach for whenever multiple containers on one machine need to talk to each other. Use case: an API container and a database container that need to communicate — the exact scenario this whole article has been building toward.</p><p><strong>Host</strong> — skips container network isolation entirely, letting a container share the host machine’s network stack directly. Use case: performance- sensitive tools, or anything that specifically needs to see the host’s real network traffic rather than an isolated container view of it — not something reached for in ordinary app development.</p><p><strong>None</strong> — deliberately zero network access. Use case: batch or offline processing jobs that never need to talk to anything at all, where cutting off network access entirely doubles as a security measure — if the container’s ever compromised, it has nowhere to send data to.</p><p><strong>Overlay</strong> — for containers that need to reach each other across <em>different physical machines</em>, not just within one. Use case: this is the mechanism underneath Kubernetes and Docker Swarm, letting a container on one machine talk to a container on another as if they were sitting on the same local network.</p><p>And the commands themselves, at least, are quick to get comfortable with — nowhere near as much to hold onto as the concepts behind them. Here are a few worth knowing:</p><ul><li>docker network create &lt;name&gt; — creates a new custom network, ready for containers to be attached to it.</li><li>docker network ls — lists every network on the machine, including Docker&#39;s built-in defaults (bridge, host, none) alongside any custom ones created.</li><li>docker network inspect &lt;name&gt; — shows the details of a specific network, including exactly which containers are currently attached to it.</li><li>docker run --network &lt;name&gt; &lt;image&gt; — starts a container directly on a specified network, rather than defaulting to the plain bridge.</li></ul><h3>Proving It, Not Just Taking It on Faith</h3><p>To put things into perspective, here’s what I actually did. Remember the default bridge network, the one created automatically the moment Docker is installed? It’s easy to assume this default is enough for any multi-container setup. It isn’t — and rather than take that on faith, I wanted to prove it myself.</p><p>Here’s what I did, step by step, so it’s easy to follow along — and along the way, I’ll point out a container lifecycle “hack” worth knowing too.</p><p><strong>Step 1 — Two containers, no custom network</strong></p><p>The plan: rely purely on the default bridge and see whether it actually works. In a real-world scenario, this would mean containerizing a frontend and a backend and checking whether they can reach each other with no custom network involved. For this test, though, I used nginx and BusyBox instead (nginx being a lightweight web server that responds the moment it’s running, and BusyBox being a minimal Linux image carrying just enough basic tools — a shell, ping, wget — to test connectivity from). Using two small, pre-built images instead of my actual app meant I could isolate the one thing I was actually testing — whether the name resolves — without any real application code getting in the way.</p><p>First, the web container:</p><pre>docker run -d --name web nginx</pre><p>The terminal itself was good about narrating what was actually happening:</p><pre>Unable to find image &#39;nginx:latest&#39; locally<br>latest: Pulling from library/nginx<br>63e237f10cf6: Pull complete<br>75e5e08234c9: Pull complete<br>...<br>Status: Downloaded newer image for nginx:latest</pre><p>Since this was the first time pulling nginx on this machine, Docker checked locally, found nothing, and fell back to pulling it from Docker Hub — layer by layer, visible right there in the output.</p><p>Then a second container, to actually test connectivity from:</p><pre>docker run -it --name test-client busybox</pre><p>Breaking the command down: -d runs a container detached, in the background, handing the terminal straight back. -it is different — it keeps the container attached and interactive, dropping you directly into a live shell inside it, which is exactly what&#39;s needed here to actually run commands <em>from inside</em> the container rather than just starting it and walking away. --name test-client assigns a memorable, chosen name instead of a random one Docker would generate otherwise — and that name is specifically what gets tested for resolution in the next step.</p><p>With test-client now running interactively, the actual test could finally happen — try to ping web by name, and see whether the default bridge could resolve it.</p><p>Inside the BusyBox shell:</p><pre>/ # ping web<br>ping: bad address &#39;web&#39;</pre><p>That’s the failure, live. Both containers were healthy and running — client had no way to even look up what web was. The name simply didn&#39;t resolve to anything, because the default bridge network has no built-in DNS.</p><p>Cleaning up, before Step 2, surfaced a second small lesson:</p><pre>nate@Mbaochas-MacBook-Pro ~ % docker rm web test-client<br>test-client<br>Error response from daemon: cannot remove container &quot;/web&quot;: container is running: stop the container before removing or force remove</pre><p>docker rm only works on stopped containers. web was still running in detached mode, so it refused. The graceful route is docker stop web then docker rm web as two steps; the quicker route collapses both with a force flag:</p><pre>docker rm -f web test-client</pre><p><strong>Step 2 — Same test, on a custom network</strong></p><p>This time, a custom network first, using the command from earlier — then both web and test-client get connected to it instead of relying on the default bridge. One thing added here worth flagging separately: a --rm flag on both containers, which I&#39;ll explain in a moment.</p><pre>docker network create test-net<br>docker run -d --name web --network test-net --rm nginx<br>docker run -it --name test-client --network test-net --rm busybox</pre><p>That --rm flag is a small container lifecycle hack worth keeping. It tells Docker to automatically remove the container the moment it stops — no leftover stopped containers piling up, no manual docker rm needed afterward. It&#39;s set at creation time, in docker run, rather than something reached for after the fact the way docker rm -f was in Step 1. Since test-client here is interactive, the moment its shell is exited, the container stops and immediately cleans itself up — one less thing to remember between test runs.</p><pre>/ # ping web<br>PING web (172.18.0.2): 56 data bytes<br>64 bytes from 172.18.0.2: seq=0 ttl=64 time=1.319 ms<br>64 bytes from 172.18.0.2: seq=1 ttl=64 time=0.306 ms<br>...<br>44 packets transmitted, 44 packets received, 0% packet loss</pre><p>Same images, same commands — the only thing that changed was which network both containers sat on. web resolved instantly to 172.18.0.2, and every ping got a reply.</p><p>That resolution step — name to IP — is exactly the mechanism that made the earlier DB URL example work: custom bridge networks run their own internal DNS, translating container names into reachable addresses automatically. The default bridge just doesn’t have that piece.</p><p>Containers on the default bridge can still reach each other — just by raw IP address, not by name. ping 172.17.0.2 would have worked fine in Step 1, even though ping web didn&#39;t. The real reason nobody uses the default bridge for multi-container apps isn&#39;t that it&#39;s broken — it&#39;s that manually tracking and hardcoding IPs (which aren&#39;t even guaranteed to stay the same across restarts) is a genuinely worse way to work than addressing containers by a stable, memorable name.</p><h3>Where This Leaves Me</h3><p>The whole day compressed to one idea: an address by itself isn’t enough — something has to make that address findable, and on a single machine, that something is a Docker network with DNS attached. Everything else — the bridge mechanics, the driver types, the commands — was really just different angles on that one fact.</p><p><em>This is Day 3 of my “Day 1 to Hero” series, documenting the process of learning Docker and Kubernetes from the ground up.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbc084b0309e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Bug That Taught Me More Than the Course Did: Building My First Docker Image]]></title>
            <link>https://medium.com/@mbaochajonathan/docker-for-beginners-day-2-images-dockerfiles-and-the-bug-that-taught-me-more-than-the-course-a2fd3f9fb2d4?source=rss-ccb9dee6e319------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2fd3f9fb2d4</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Mbaocha Jonathan]]></dc:creator>
            <pubDate>Sun, 12 Jul 2026 14:30:54 GMT</pubDate>
            <atom:updated>2026-07-12T14:46:19.480Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Day 1 to Hero — Building My First Image</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*laW8s6AmueKzIfKjtrCt0w.png" /></figure><p>Day 1 was theory: hypervisors, VMs, the case for containers, the npm/pnpm parallels that made Docker Hub click. Day 2 is where I actually opened a Dockerfile and started building things — and, as it turns out, where I learned more from a stubborn bug than from any single lesson.</p><h3>What an Image Actually Is</h3><p>Docker’s entire ecosystem runs on <strong>images</strong> — lightweight, standalone, executable packages containing everything a piece of software needs to run. Three words in that definition are doing real work:</p><ul><li><strong>Standalone</strong> — the app code, runtime, system libraries, and dependencies are all bundled inside. Nothing external needs installing separately for it to work.</li><li><strong>Immutable</strong> — once built, an image never changes. Need to ship an update? You don’t edit the existing image, you build a <em>new</em> one. This single rule is why rollbacks are trivial (the old image still exists, untouched) and why “works on my machine” mismatches mostly disappear — an image tagged v1 behaves identically no matter who runs it or when.</li><li><strong>Portable</strong> — because everything needed is bundled inside, the image runs identically anywhere Docker is installed.</li></ul><p><strong>New update = new image = new rollout.</strong> There’s no “patch the running container” move in Docker’s model — every change, even a one-line fix, means rebuilding and redeploying. This isn’t a limitation; it’s the exact mechanism Kubernetes later automates as a formal “rollout” operation.</p><h3>Images Are Built in Layers</h3><p>An image isn’t one solid block — it’s a stack of layers, one per instruction in the build process. This matters for two very practical reasons: Docker can <strong>cache</strong> layers that haven’t changed (skipping expensive steps like dependency installation on rebuilds), and it can <strong>share</strong> layers across different images — if two images both start from node:20, that base layer is stored once on disk, not twice.</p><h3>Containers: Runtime Instances of an Image</h3><p>If an image is the blueprint, a <strong>container</strong> is a running instance of it — the class-and-object relationship from Day 1, now applied concretely.</p><p>Three properties define how containers behave:</p><p><strong>Isolation.</strong> Each container gets its own process list, filesystem view, and network namespace. But there’s a subtler form of isolation worth calling out: <strong>configuration isolation</strong>, driven by environment variables. Because images are immutable and shouldn’t hardcode things like database URLs or feature flags, a well-built image reads that kind of config from environment variables at runtime instead. That means the <em>same</em> image can produce containers that behave completely differently:</p><pre>docker run -e NODE_ENV=development -e DB_URL=localhost:5432 myapp:v1<br>docker run -e NODE_ENV=production -e DB_URL=prod-db.com myapp:v1</pre><p>Same image, two different behaviors — because the config differs, not the code. This is a core idea in the <strong>12-Factor App</strong> methodology: config belongs in the environment, never baked into the build. It’s also worth noting that images <em>can</em> ship their own default environment variables (set via ENV in the Dockerfile) — a container isn&#39;t a blank slate; it&#39;s more accurate to say the image provides sensible defaults, and -e at runtime overrides them.</p><p><strong>Ephemeral.</strong> Once a container dies, it’s gone — along with any files it wrote while running, unless you’ve set up persistent storage (Docker’s <strong>volumes</strong> exist specifically to solve this, for things like a database’s actual data).</p><p><strong>Portable.</strong> Inherited directly from the image underneath it.</p><h3>Writing an Actual Dockerfile</h3><p>Here’s roughly where my Dockerfile landed for a simple Express app:</p><pre>FROM node:20-alpine<br>WORKDIR /app<br>COPY package*.json ./<br>RUN npm install<br>COPY . .<br>EXPOSE 3000<br>CMD [&quot;node&quot;, &quot;src/index.js&quot;]</pre><p>A few things worth being precise about, since each one tripped me up at least once.</p><p><strong>FROM is not &quot;install one package.&quot;</strong> It&#39;s closer to choosing a starter template — you&#39;re inheriting an entire pre-built image (OS layer + a runtime already configured) as your foundation, then building your own layers on top. node:20 breaks down as image-name:tag — the tag pins a specific version. Leaving it off defaults to latest, which quietly breaks reproducibility over time; always pin a version in anything real.</p><p><strong>WORKDIR and </strong><strong>COPY&#39;s destination are unrelated to what gets copied.</strong> WORKDIR /app only decides <em>where inside the image</em> files land — it has zero effect on <em>which</em> files from your machine get selected. What actually controls that is the <strong>build context</strong> (the folder you point docker build at — nothing outside it is even visible to COPY), your .dockerignore file, and how specific your COPY source paths are. Three separate mechanisms, easy to conflate, worth keeping distinct.</p><p><strong>Local paths and image paths don’t need to match.</strong> COPY apps/api/src ./src takes files from wherever they live on your machine and places them wherever you choose inside the image — the two sides of a COPY instruction are entirely independent.</p><h3>The Layer-Ordering Rule of Thumb</h3><p>This is the optimization that matters most: <strong>order instructions from “changes least often” to “changes most often.”</strong> Docker invalidates a cached layer — and every layer after it — the moment something upstream changes. Copy your dependency manifest first, install dependencies, <em>then</em> copy your actual source code last:</p><pre>COPY package*.json ./     # changes occasionally<br>RUN npm install             # expensive — you want this cached<br>COPY . .                    # changes on every commit — put it last</pre><p>Get this backwards — copying source before the manifest — and <em>any</em> code edit invalidates your npm install layer, forcing a full reinstall on every rebuild even though your dependencies never changed.</p><h3>.dockerignore, and What It Actually Does</h3><p>.dockerignore works like .gitignore, sitting next to your Dockerfile. One detail worth being precise about: it&#39;s not a continuous, &quot;on the fly&quot; filter — it&#39;s checked <strong>once</strong>, at the very start of the build, when Docker assembles the build context. Whatever it excludes is permanently invisible to every COPY instruction in the file, no matter how many there are.</p><pre>node_modules<br>.git<br>.env<br>Dockerfile</pre><p>There’s no global, cross-project version of this file the way Git has a global excludesFile — Docker has no equivalent. Each build context needs its own.</p><h3>EXPOSE Is Documentation, Not Networking</h3><p>I initially assumed EXPOSE 3000 was the mechanism that makes a container reachable. It isn&#39;t. EXPOSE in a Dockerfile is essentially informational — it declares what port the app listens on internally, but doesn&#39;t publish anything. The actual networking happens at docker run time, with -p:</p><pre>docker run -p 3000:3000 myapp</pre><p>hostPort:containerPort — and yes, both sides need the literal port number. You can&#39;t reference an environment variable inside the -p flag (-p 5000:PORT doesn&#39;t work); -p is parsed by the Docker CLI before the container even starts, at which point any -e-provided environment variable doesn&#39;t exist yet from the CLI&#39;s point of view. Host port and container port are genuinely independent numbers — you just have to keep them in sync by hand.</p><h3>The Bug That Ate My Afternoon</h3><p>At this point I built a small Express app, wrote what I believed was a correct Dockerfile, and hit a wall: Error: Cannot find module &#39;express&#39; — despite express being correctly listed in package.json, despite npm install completing with no errors, despite a fully clean, uncached rebuild.</p><p>The investigation, compressed:</p><ul><li>Checked package.json inside the built image — correct, express was there.</li><li>Checked node_modules inside the image — express&#39;s folder existed, but was <strong>completely empty</strong>. Not a broken symlink, not a missing folder — an empty directory where the package&#39;s actual files should have been.</li><li>Checked other packages (body-parser, accepts) — also empty. This ruled out anything express-specific immediately; the entire install was silently failing to write file contents while still reporting success.</li><li>Ruled out caching, disk space (I had 58GB free), and Docker’s own reclaimable space (freed over 21GB via docker system prune -a) — none of it changed the outcome.</li><li>Switched base images (alpine → slim), switched install commands (npm install → npm ci) — same empty-folder result either way, which ruled out Alpine/musl compatibility as a cause too (Express has zero native dependencies, so it was never a realistic suspect in hindsight).</li><li>The one consistent thread across every attempt: npm install reliably took almost exactly <strong>80 seconds</strong>, success or failure, on every single run.</li></ul><p>That consistent timing was the actual clue. A direct connectivity test — wget-ing registry.npmjs.org from inside a container — hung indefinitely at &quot;Connecting to registry.npmjs.org.&quot; The root cause wasn&#39;t Docker, npm, Alpine, or my Dockerfile at all: it was the network path between Docker Desktop&#39;s Linux VM and npm&#39;s registry timing out, with npm handling that stall differently depending on version — sometimes crashing loudly (&quot;Exit handler never called&quot;), sometimes failing silently and leaving hollow package folders behind.</p><p>I’m noting this here, unresolved, at the time of writing — because it’s a genuinely useful example of a category of bug that has nothing to do with your code being wrong. Docker debugging often means ruling out your own Dockerfile <em>first</em>, and then being willing to suspect the network, the VM, or the tooling underneath it. Systematically eliminating variables — base image, install command, cache state, disk space — until only the network path was left standing, was the actual useful skill here, even without a fix in hand yet.</p><h3>Multi-Stage Builds</h3><p>This is where image-size optimization actually lives, and it’s a purely practical technique — no deeper meaning, no connection to dev/staging/production environments (an assumption I had to get talked out of). A “stage” is just everything under one FROM instruction in a Dockerfile; each new FROM starts a fresh one.</p><p>The problem it solves: building an app often needs tools the <em>running</em> app never needs. A TypeScript project needs the TypeScript compiler and its full devDependencies to build — but at runtime, all it needs is plain Node and the compiled JavaScript.</p><pre># Stage 1: has everything needed to compile<br>FROM node:20-alpine AS builder<br>WORKDIR /app<br>COPY package*.json ./<br>RUN npm install<br>COPY . .<br>RUN npm run build</pre><pre># Stage 2: clean runtime image<br>FROM node:20-alpine<br>WORKDIR /app<br>COPY package*.json ./<br>RUN npm install --omit=dev<br>COPY --from=builder /app/dist ./dist<br>CMD [&quot;node&quot;, &quot;dist/index.js&quot;]</pre><p>The final image never contains a single .ts file or the TypeScript compiler — just compiled JavaScript and production dependencies.</p><p>The pattern gets even more dramatic for a React app. Building it requires Node and a full toolchain (Vite, webpack, whatever). But the <em>output</em> is static HTML/CSS/JS — which doesn’t need Node to serve at all, just a lightweight web server:</p><pre>FROM node:20-alpine AS builder<br>WORKDIR /app<br>COPY package*.json ./<br>RUN npm install<br>COPY . .<br>RUN npm run build</pre><pre>FROM nginx:alpine<br>COPY --from=builder /app/dist /usr/share/nginx/html<br>EXPOSE 80<br>CMD [&quot;nginx&quot;, &quot;-g&quot;, &quot;daemon off;&quot;]</pre><p>A Node-based image for this might run 200MB+. The nginx + static files version can land under 30MB.</p><blockquote><em>Nginx is a piece of software whose job is being a web server.</em></blockquote><p>That’s the whole category, plainly stated. A web server is anything that listens for HTTP requests and sends back responses — nginx and Express both qualify. The difference is what each one does once a request lands: nginx mostly serves static files or routes traffic elsewhere, while Express runs custom application code to generate a dynamic response. Neither is “more of a real web server” than the other — they’re just built for different strengths within the same job.</p><p><strong>The rule of thumb that actually matters:</strong> ask whether your project has a build step at all (npm run build, tsc, vite build). No build step, no real benefit to multi-stage — a single-stage Dockerfile is genuinely fine. If there is a build step, everything needed only to <em>produce</em> the final output — compilers, dev dependencies, pre-compiled source — belongs in an earlier, throwaway stage. The last FROM in the file is the only one that ships; make it as lean as possible.</p><h3>What Actually Got Me Through the Bug</h3><p>It would be easy to close this out by telling you “don’t worry about what to write in a Dockerfile, most of it can be copied and pasted.” That’s not quite honest, though, and it’s not what actually happened today. I didn’t get through the Express bug by finding the right snippet — I got through as much of it as I did by understanding <em>why</em> .dockerignore matters, <em>why</em> layer order affects caching, and <em>why</em> an 80-second timeout showing up across every single variant I changed was the actual clue worth following, not the specific error message each time.</p><p>If I had to name the real skill, it’s not memorizing syntax and it’s not just knowing what a “finished, working container” is supposed to look like. It’s three smaller things, stacked:</p><ol><li><strong>Knowing which moves are even available to you</strong> — that you <em>can</em> open a shell inside a running container, that you <em>can</em> check what actually got installed versus what you expected, that you <em>can</em> test raw network connectivity from inside a container. Without this, a beginner staring at Cannot find module &#39;express&#39; has nowhere to go — not because they don&#39;t know the command, but because they don&#39;t know that kind of check is possible at all.</li><li><strong>Understanding what each move actually does</strong> — docker exec -it &lt;container&gt; sh only becomes useful once you know it opens a live shell <em>inside</em> the container&#39;s own isolated filesystem, not your host machine.</li><li><strong>Being able to read what comes back</strong> — knowing the commands means nothing if you can’t tell that a consistent 80-second delay across alpine, slim, npm install, and npm ci alike was pointing at the network, not at any of the things I kept changing.</li></ol><p>The reassuring part, and it’s a genuine one: the actual command surface here is small and fixed. docker ps, docker logs, docker exec, docker build, docker run — you don&#39;t learn new ones every week, you reuse the same handful in different combinations for nearly every problem. A few weeks of hitting real bugs and typing docker ps -a becomes as automatic as reaching for console.log. The syntax stops being the hard part almost immediately. Knowing what&#39;s possible, and why, is the part actually worth building — and that&#39;s what today was really about, unresolved network bug included.</p><p>Day 3 turns to networking — how containers actually talk to each other, and to the outside world.</p><p><em>This is Day 2 of my “Day 1 to Hero” series, documenting the process of learning Docker and Kubernetes from the ground up.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2fd3f9fb2d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Containers Exist: What I Learned Before Writing a Single Dockerfile]]></title>
            <link>https://medium.com/@mbaochajonathan/docker-for-beginners-what-i-actually-learned-before-writing-a-single-dockerfile-8a7fff6ea5e5?source=rss-ccb9dee6e319------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a7fff6ea5e5</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-container]]></category>
            <dc:creator><![CDATA[Mbaocha Jonathan]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 19:06:20 GMT</pubDate>
            <atom:updated>2026-07-12T14:45:40.270Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Day 1 to Hero — Container Fundamentals</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YvrrePJXZCeq7ZT2oTQRuw.png" /></figure><p>If you’re a developer who’s heard “just Dockerize it” a hundred times without really knowing what that means, you’re exactly who this article is for. Before touching a single Dockerfile, I wanted to understand <em>why</em> Docker exists at all — and that meant starting one layer below Docker, with the technology it&#39;s often compared to: the hypervisor.</p><h3>The Old Way: Hypervisors and Virtual Machines</h3><p>Imagine you have one physical server, and you want to run three different apps on it without them interfering with each other. Maybe they need different OS versions. Maybe one crashing shouldn’t take the others down with it.</p><p>The traditional answer to this is a <strong>hypervisor</strong> — software that simulates hardware. It takes one real physical machine and carves it into multiple <strong>Virtual Machines (VMs)</strong>, each believing it has its own dedicated CPU, RAM, and disk. None of that hardware is real — it’s emulated — but from inside the VM, it looks and behaves exactly like the real thing.</p><p>Here’s the part that matters most: each VM needs its own <strong>operating system</strong> installed inside it, kernel and all, before it can do anything useful. Picture the hypervisor as a developer building three separate houses on one plot of land — each with its own foundation, plumbing, and electrical system. Fully independent, but a lot of duplicated infrastructure.</p><p>The full stack looks like this:</p><pre>Physical Server<br>   └── Hypervisor (creates VMs)<br>          └── VM (empty simulated hardware)<br>                 └── OS installed inside (full kernel)<br>                        └── Bins/Libs (e.g. Node.js)<br>                               └── Your App</pre><p>That’s an important equation to get right, by the way: <strong>a VM is not “OS + Bins + App.”</strong> The VM is the empty shell the hypervisor creates. OS + Bins + App is the content you load into it afterward.</p><h3>Two Flavors of Hypervisor</h3><p>Hypervisors come in two types, and the difference matters once you start reading production infrastructure docs:</p><ul><li><strong>Type 1 (bare-metal)</strong> — installed directly on physical hardware, no host OS required. This is what data centers use (VMware ESXi, Hyper-V in server mode).</li><li><strong>Type 2 (hosted)</strong> — installed as an application on top of an existing OS, like running VirtualBox on your laptop.</li></ul><h3>Can a Hypervisor Create Resources Out of Thin Air?</h3><p>Short answer: no. If your physical machine has 2GB of RAM, that’s the hard ceiling. No software can conjure 8GB more from nothing.</p><p>What a hypervisor <em>can</em> do — assuming a larger real pool exists somewhere, like a server rack with 512GB of physical RAM — is redistribute from that pool. If your app is capped at 2GB but the rack has plenty of room, you can raise the ceiling to 10GB, and it’s real, available memory, not magic. Beyond that, hypervisors also have tricks like overcommitment (allocating more than physically exists, betting not everyone maxes out at once) and swap (borrowing disk space as slow, emergency RAM). None of these create resources — they just manage a fixed, real pool more flexibly.</p><h3>Enter Docker: A Lighter Way to Isolate Apps</h3><p>VMs solve isolation, but at a cost: gigabytes of size, minutes to boot, and a permanently reserved slice of RAM/CPU per app. Docker asked a different question: <em>what if isolated apps could share the host machine’s operating system, instead of each needing their own?</em></p><p>That’s the entire idea behind a <strong>container</strong>. Rather than simulating hardware and installing a fresh OS on top, Docker uses features already built into the Linux kernel — <strong>namespaces</strong> (which give each container its own isolated view of processes, filesystem, and network) and <strong>cgroups</strong> (which control how much CPU/RAM each container is allowed to use, and let you adjust that limit on the fly). The result: isolation without needing separate hardware or a separate kernel.</p><p>The container stack, side-by-side with the VM stack from earlier:</p><pre>Docker Engine (creates containers)<br>   └── Container (isolated process — shares HOST&#39;s kernel)<br>          └── Bins/Libs (e.g. Node.js)<br>                 └── Your App</pre><p>Notice what’s missing: the entire OS layer. That single missing layer is the root cause of nearly everything that makes containers appealing — they’re lighter, smaller, and start in seconds instead of minutes.</p><p><strong>Docker Engine</strong> is the software responsible for all of this — it’s a <strong>container engine</strong>, not a hypervisor. Same general role (creating and managing isolated units), completely different, lighter mechanism (kernel-sharing instead of hardware emulation).</p><h3>The Windows/Mac Catch</h3><p>Here’s a detail that trips a lot of beginners up: a Linux container needs a Linux kernel. It cannot run on a Windows kernel directly — the two are fundamentally incompatible at the system-call level.</p><p>So how does Docker Desktop run Linux containers on your Windows or Mac laptop? It quietly spins up one small <strong>Linux VM in the background</strong>, and every “Linux container” you run actually shares that single hidden VM’s kernel.</p><pre>Windows/Mac laptop<br>   └── Hidden lightweight Linux VM<br>          └── Linux Kernel  ← every container shares THIS<br>                ├── Container 1<br>                ├── Container 2<br>                └── Container 3</pre><p>On a native Linux server, that hidden VM step disappears entirely — containers talk straight to the host kernel. It’s a big part of why production deployments usually run on Linux.</p><h3>Docker Didn’t Replace the Hypervisor — It Stacked on Top of It</h3><p>It’s tempting to think Docker made hypervisors obsolete. It didn’t. VMs are still the right call when you need genuinely different kernels side-by-side (Windows and Linux on one machine), stronger security boundaries, or — and this is the part people forget — when you’re renting a “server” from a cloud provider at all. An AWS EC2 instance <em>is</em> a VM, running on a hypervisor, on physical hardware Amazon owns.</p><p>Which means most real production setups look like this:</p><pre>Physical Hardware → Hypervisor → VM (e.g. an EC2 instance) → Docker → Containers</pre><p>Containers didn’t replace the hypervisor layer. They added a lighter layer of isolation <em>on top of it</em>.</p><h3>Image vs. Container: Class vs. Instance</h3><p>Two terms get used constantly and conflated often, so it’s worth being precise:</p><ul><li>An <strong>image</strong> is the packaged, read-only blueprint — OS-level files, binaries, libraries, your app code, configuration, all bundled together.</li><li>A <strong>container</strong> is a live, running instance created from that image.</li></ul><p>If you write code, this maps directly onto something you already know: <strong>an image is a class, a container is an instance of it.</strong> You can pull or build one image once, and run it multiple times to get multiple independent, simultaneously running containers.</p><h3>Docker Hub Is Just npm for Containers</h3><p>If you’ve used npm or pnpm, you already understand Docker’s ecosystem better than you think.</p><p>npm/pnpm world Docker world Node.js (the runtime) Docker Engine (the runtime) npm registry Docker Hub (registry of pre-built images) npm install &lt;package&gt; docker pull &lt;image&gt; package.json Dockerfile node_modules/ A Docker image (built artifact) pnpm&#39;s local cache Docker&#39;s local image cache</p><p>Installing Docker only gets you the <strong>engine</strong> — the runtime that can build and run containers. <strong>Docker Hub</strong> is the separate, hosted registry of pre-built images that other people and companies have published — a Postgres image, a Node.js image, a Redis image — so you don’t have to build everything from scratch.</p><p>docker pull &lt;image&gt; behaves exactly like npm install &lt;package&gt;: it fetches something and stores it locally. docker run &lt;image&gt; is closer to actually <em>executing</em> that thing — and if you don&#39;t already have the image locally, it pulls it first automatically, then creates and starts a container from it.</p><p>There’s also a local caching layer, much like pnpm’s shared store: once you’ve pulled or built an image, it’s stored locally (visible via docker images), and Docker doesn&#39;t re-download it if you need it again. Docker even shares common <em>layers</em> between images — if two images are both built on node:20, that shared layer is stored once, not twice.</p><p>One catch that applies equally to pnpm and Docker: <strong>a local cache only has what’s already been downloaded before, at the exact version previously used.</strong> A new project, a package you’ve never installed, or a newer version than what’s cached — all of these require a fresh network call, cache or no cache.</p><h3>Why Developers Actually Bother With All This</h3><p>Every explanation of Docker eventually lists the same five benefits: consistency, scalability, isolation, portability, and efficiency. They can feel like buzzwords until you trace them back to their source — which, by this point, should look familiar: <strong>containers skip the OS layer and share the host’s kernel.</strong> Everything else falls out of that one fact.</p><ul><li><strong>Consistency</strong> — the exact OS libraries, runtime version, and dependencies travel with the image, so “works on my machine” becomes true everywhere: your laptop, a teammate’s laptop, staging, production.</li><li><strong>Scalability</strong> — containers start in seconds, so spinning up ten copies of an app under load is fast and cheap, unlike booting ten full VMs.</li><li><strong>Isolation</strong> — each container has its own filesystem, process list, and network namespace, so one crashing or misbehaving doesn’t take down the others, even with conflicting dependency versions.</li><li><strong>Portability</strong> — an image is self-contained; ship it to any machine with Docker installed and it behaves identically, no lengthy setup documentation required.</li><li><strong>Efficiency</strong> — without a duplicated OS per app, far more containers fit on the same physical hardware than VMs ever could.</li></ul><h3>The Commands That Get You Moving</h3><p>A short, practical toolkit to actually start using this:</p><pre># Images<br>docker pull &lt;image&gt;       # download an image only — nothing runs yet<br>docker images             # list images stored locally<br>docker rmi &lt;image_id&gt;     # remove an image</pre><pre># Running containers<br>docker run &lt;image&gt;                 # runs in the foreground, blocks your terminal<br>docker run -d &lt;image&gt;              # -d = detached, runs in the background<br>docker run -p 3000:3000 &lt;image&gt;    # maps hostPort:containerPort so you can reach it<br>docker run --name myapp &lt;image&gt;    # gives it a memorable name</pre><pre># Viewing containers<br>docker ps            # running containers only<br>docker ps -a         # ALL containers, including stopped/crashed ones</pre><pre># Stopping and removing<br>docker stop &lt;container&gt;       # graceful stop<br>docker rm &lt;container&gt;         # remove a stopped container<br>docker rm -f &lt;container&gt;      # force stop + remove in one shot</pre><pre># Debugging<br>docker logs &lt;container&gt;            # view a container&#39;s output<br>docker exec -it &lt;container&gt; bash   # open a shell inside a running container</pre><p>If a container crashes seconds after starting, docker ps -a will show it as &quot;Exited&quot; with a status code — and docker logs &lt;container&gt; right after will usually tell you exactly what went wrong.</p><h3>Where This Leaves Me</h3><p>Two clean mental models, side by side:</p><pre>VM route:        Hypervisor → VM → OS → Bins/Libs → App<br>Container route: Docker Engine → Container (shares host kernel) → Bins/Libs → App</pre><p>One extra OS layer is the entire difference — and it’s responsible for nearly every advantage containers have over VMs. With that foundation in place, the next step is writing an actual Dockerfile and packaging a real app into an image of my own. That&#39;s where Part 2 picks up.</p><p><em>This is Day 1 of my “Day 1 to Hero” series, documenting the process of learning Docker and Kubernetes from the ground up.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a7fff6ea5e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Magic Link Authentication: Building a Cross-Device Authentication System (Part 2)]]></title>
            <link>https://medium.com/@mbaochajonathan/magic-link-authentication-building-a-cross-device-authentication-system-part-2-aa791fa48ea8?source=rss-ccb9dee6e319------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa791fa48ea8</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Mbaocha Jonathan]]></dc:creator>
            <pubDate>Fri, 29 Aug 2025 23:13:17 GMT</pubDate>
            <atom:updated>2025-08-29T23:13:17.045Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is Part 2 of my magic link authentication series. In </em><a href="https://medium.com/javascript-in-plain-english/why-i-ditched-passwords-for-magic-links-a-developers-journey-away-from-authentication-complexity-a4e437b9936d"><em>Part 1</em></a><em>, I shared why I moved away from traditional password authentication and OAuth-only solutions. Now let’s dive into the actual implementation.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tcUxQC4RDhQlMd5YJi_HmQ.png" /></figure><h3>From Concept to Code: Building the Magic Link System</h3><p>After deciding on magic links for my prescription management app, I faced the reality of implementation. The concept seemed straightforward, but as any developer knows, the devil is in the details.</p><p>Let me walk you through how I built a production-ready magic link authentication system that elegantly handles the cross-device challenge I mentioned in Part 1.</p><h3>Architecture Decisions: Why REST in a GraphQL World</h3><p>Before we dive into code, I need to address something that might seem contradictory: I chose REST endpoints for authentication in what is otherwise a GraphQL-first application.</p><p>The reason is simple: magic links in emails need to be straightforward GET requests that work reliably across all email clients. While you <em>could</em> make GraphQL work with email links, REST endpoints are the natural fit for this use case.</p><h3>The Core Flow: Elegant Simplicity</h3><p>The magic link concept is beautifully simple when you break it down:</p><ol><li><strong>Request</strong>: User provides their email address</li><li><strong>Generate</strong>: Server creates a secure token and sends it via email</li><li><strong>Verify</strong>: User clicks the link, proving they own the email</li><li><strong>Authenticate</strong>: Server validates the token and logs them in</li></ol><p>But as I learned building this system, the real complexity comes from handling edge cases and creating a smooth user experience. Let me show you how I implemented each piece.</p><h3>The Entry Point: Requesting a Magic Link</h3><p>Everything starts with a simple endpoint that receives an email and triggers the authentication flow:</p><pre>// Route definition<br>router.post(&quot;/magiclink&quot;, authController.sendMagicLink);</pre><p>The controller implementation is refreshingly straightforward:</p><pre>async sendMagicLink(req: Request, res: Response) {<br>  const { email } = req.body;<br>  if (!email) return res.status(400).json({ error: &quot;Email is required&quot; });<br><br>  await magicLinkService.requestMagicLink(email);<br>  return res.status(200).json({ message: &quot;Magic link sent!&quot;, success: true });<br>}</pre><p>This simplicity is intentional. The endpoint does one thing well: it takes an email, delegates the token generation and email sending to a service, and returns a success response. No complex validation, no user lookup at this stage — just pure delegation.</p><p>The MagicLinkService handles the token generation and email logic:</p><h3>Email Delivery: The Critical Link</h3><p>I understand that for my magic link system to work, I need reliable email delivery. You can have the most elegant token generation in the world, but if emails don’t reach users’ inboxes, the whole system falls apart.</p><p>I chose Nodemailer for email delivery, primarily because it gives me control over the SMTP configuration and doesn’t tie me to a specific email service provider:</p><pre>// src/auth/services/emailService.ts<br>import * as nodemailer from &quot;nodemailer&quot;;<br>import { EmailService } from &quot;../types&quot;;<br><br>class NodemailerEmailService implements EmailService {<br>  private transporter = nodemailer.createTransporter({<br>    host: process.env.SMTP_HOST,<br>    port: Number(process.env.SMTP_PORT),<br>    secure: process.env.SMTP_SECURE === &quot;true&quot;, // true for 465, false for other ports<br>    auth: {<br>      user: process.env.SMTP_USER,<br>      pass: process.env.SMTP_PASSWORD,<br>    },<br>  });<br>  async sendMagicLink(email: string, link: string): Promise&lt;void&gt; {<br>    const mailOptions = {<br>      from: process.env.SMTP_FROM_EMAIL,<br>      to: email,<br>      subject: &quot;Your Magic Login Link&quot;,<br>      html: `&lt;p&gt;Click the link below to log in:&lt;/p&gt;&lt;a href=&quot;${link}&quot;&gt;${link}&lt;/a&gt;`,<br>    };<br>    await this.transporter.sendMail(mailOptions);<br>  }<br>}<br>export const emailService = new NodemailerEmailService();</pre><h3>Why SMTP Over Email APIs?</h3><p>You might wonder why I chose SMTP over services like SendGrid, AWS SES, or Mailgun APIs. Here’s my reasoning:</p><p><strong>Provider Flexibility</strong>: With SMTP configuration, I can switch email providers without changing code. Today it might be Gmail’s SMTP, tomorrow it could be AWS SES or a dedicated email service.</p><p><strong>Cost Control</strong>: For a prescription management app that might send a handful of emails per user per month, SMTP through existing providers can be more cost-effective than API-based services with per-email pricing.</p><p><strong>Simplicity</strong>: Nodemailer’s SMTP approach is straightforward — it’s just email sending without learning another API or managing API keys beyond basic SMTP credentials.</p><p>The configuration is entirely environment-driven, which means I can easily adapt to different email providers across development, staging, and production environments.</p><h3>The Email Template:I Kept It Simple</h3><p>Notice the minimal HTML template in the sendMagicLink method. This simplicity is intentional:</p><ul><li><strong>No complex styling</strong> that might break across email clients</li><li><strong>Clear call-to-action</strong> with the magic link prominently displayed</li><li><strong>Accessible text</strong> that works even if HTML rendering fails</li></ul><p>In production, you’d probably want more sophisticated templates, but for the core functionality, simple works reliably across all email clients.</p><h3>Behind the Scenes: The Magic Link Service</h3><pre>async requestMagicLink(email: string): Promise&lt;void&gt; {<br>  console.log(`[MagicLinkService] Requesting magic link for: ${email}`); //&lt;== DEBUG<br><br>try {<br>    const payload: TokenPayload = {<br>      email,<br>      type: &quot;magiclink&quot;,<br>    };<br>    const token = await this.tokenService.generateToken(payload, {<br>      expiresIn: this.config.tokenExpiry,<br>    });<br>    const link = `${this.config.magicLinkBaseUrl}?token=${token}`;<br>    // Store in Redis for additional security<br>    const redisKey = this.getRedisKey(token);<br>    const ttl = 15 * 60; // 15 minutes<br>    const stored = await redisUtil.set(redisKey, email, ttl);<br>    if (!stored) throw new Error(&quot;Failed to store token in Redis&quot;);<br>    // Send the magic link email<br>    await emailService.sendMagicLink(email, link);<br>  } catch (error) {<br>    console.error(&quot;[MagicLinkService] Error in requestMagicLink:&quot;, error);<br>    throw error;<br>  }<br>}</pre><p>Here’s what makes this approach secure and reliable:</p><p><strong>JWT Token Generation</strong>: Each token contains the email and a type identifier, signed with our secret key and set to expire in 15 minutes.</p><p><strong>Redis Double-Check</strong>: Beyond JWT expiration, I store each token in Redis with its own TTL (time to live). This gives us an additional layer of control — we can invalidate tokens immediately if needed.</p><p><strong>Email as Proof of Ownership</strong>: The fundamental security assumption is simple but powerful: if you can access the email, you own that account.</p><h3>The Validation Endpoint</h3><p>When a user clicks the magic link in their email, they hit our validation endpoint directly. The magic link URL is the server endpoint itself — there’s no separate validation page. The validation happens on the server, and users get redirected automatically based on the result.</p><p>This direct endpoint approach improves user experience by eliminating unnecessary page loads — users go straight from email click to their authenticated destination without intermediate validation screens.</p><pre>router.get(&quot;/magiclink/validate&quot;, authController.validateMagicLink);</pre><p>This is where the cross-device intelligence I mentioned in Part 1 comes into play:</p><pre>async validateMagicLink(req: Request, res: Response) {<br>  const { token } = req.query;<br>  if (typeof token !== &quot;string&quot;) {<br>    return res.status(400).json({ error: &quot;Invalid token&quot; });<br>  }<br>const payload = await magicLinkService.validateToken(token);<br>  if (!payload) {<br>    return res.status(401).json({ error: &quot;Invalid or expired token&quot; });<br>  }<br>  // Ensure user exists in database<br>  let user = await prisma.user.findUnique({<br>    where: { email: payload.email },<br>  });<br>  if (!user) {<br>    user = await prisma.user.create({<br>      data: { email: payload.email },<br>    });<br>  }<br>  // Here&#39;s where the cross-device magic happens<br>  const ua = req.headers[&quot;user-agent&quot;] || &quot;&quot;;<br>  const agent = parse(ua);<br>  const isMobile = agent.device?.toString().toLowerCase().includes(&quot;mobile&quot;);<br>  if (isMobile) {<br>    // Direct mobile authentication - send to app<br>    return res.redirect(<br>      `yourapp://auth/verify?token=${encodeURIComponent(token)}`<br>    );<br>  }<br>  // Desktop detected - initiate QR code flow<br>  const requestId = await magicLinkService.storeAuthRequest(user.id);<br>  return res.redirect(<br>    `${process.env.WEB_APP_URL}/auth/qr?requestId=${encodeURIComponent(requestId)}`<br>  );<br>}</pre><p>This validation logic solves the cross-device problem I mentioned in Part 1. The server becomes intelligent about the user’s context:</p><p><strong>Mobile Device Detected</strong>: If the user clicks the magic link on their phone, they get redirected directly to the mobile app via a deep link. Simple and seamless.</p><p><strong>Desktop Browser Detected</strong>: If they’re on a computer, the system assumes they want to authenticate their mobile device. It generates a requestId, stores the user&#39;s information temporarily, and redirects to a QR code page.</p><p><strong>User Creation on Demand</strong>: Notice how we create the user account only when they successfully validate their email ownership. No abandoned accounts from unverified emails.</p><h3>The QR Code Bridge: Connecting Devices</h3><p>When the system detects a desktop browser, it redirects to a QR code page. The QR code generation itself is refreshingly simple — sometimes the most elegant solutions don’t need complex architectures.</p><p>I kept the QR code logic directly in the controller because there wasn’t enough complexity to justify a separate service:</p><pre>// src/auth/controllers/qrController.ts<br>import { Request, Response } from &quot;express&quot;;<br>import QRCode from &quot;qrcode&quot;;<br><br>export const qrController = {<br>  async generateQRCode(req: Request, res: Response) {<br>    const { requestId } = req.query;<br>    if (typeof requestId !== &quot;string&quot;) {<br>      return res.status(400).json({ error: &quot;Missing or invalid requestId&quot; });<br>    }<br>    // The URL encoded inside the QR code that the mobile app will scan<br>    const qrData = `${process.env.BACKEND_URL}/auth/qr-scan?requestId=${requestId}`;<br>    try {<br>      const qrPngBuffer = await QRCode.toBuffer(qrData, {<br>        type: &quot;png&quot;,<br>        width: 300,<br>        margin: 2,<br>        color: {<br>          dark: &quot;#000000&quot;,<br>          light: &quot;#ffffff&quot;,<br>        },<br>      });<br>      res.setHeader(&quot;Content-Type&quot;, &quot;image/png&quot;);<br>      return res.send(qrPngBuffer);<br>    } catch (error) {<br>      console.error(&quot;Error generating QR code:&quot;, error);<br>      return res.status(500).json({ error: &quot;Failed to generate QR code&quot; });<br>    }<br>  },<br>};</pre><h3>Why Keep It Simple?</h3><p>This controller does exactly one thing: it takes a requestId and generates a PNG image of a QR code. The logic is straightforward:</p><ol><li><strong>Extract the requestId</strong> from the query parameters</li><li><strong>Build the scan URL</strong> that the mobile app will handle</li><li><strong>Generate the QR code</strong> as a PNG buffer using the qrcode package</li><li><strong>Return the image</strong> directly as a PNG response</li></ol><p>The qrcode package handles all the heavy lifting. I chose specific settings for good mobile scanning:</p><ul><li><strong>300px width</strong>: Large enough to scan easily, small enough to load quickly</li><li><strong>2px margin</strong>: Clean white space around the code</li><li><strong>High contrast colors</strong>: Black on white for maximum readability</li></ul><h3>Why requestId is Critical: The Cross-Device Handshake</h3><p>The requestId might seem like just another parameter, but it&#39;s actually the heart of the entire cross-device authentication system. Without it, the server would have no way to know which user to authenticate when a mobile device scans the QR code.</p><p>Here’s the problem it solves:</p><p><strong>Without </strong><strong>requestId:</strong></p><ul><li>User clicks magic link on desktop → server validates token, knows it’s user123</li><li>Desktop shows QR code (but the QR code has no idea which user this is for)</li><li>Mobile app scans QR code → hits server</li><li><strong>Server has NO IDEA which user the mobile app should authenticate as</strong></li></ul><p><strong>With </strong><strong>requestId (the handshake):</strong></p><ul><li>User clicks magic link on desktop → server validates token, knows it’s user123</li><li>Server generates requestId (like &quot;abc123&quot;) and stores in Redis: &quot;abc123&quot; → &quot;user123&quot;</li><li>QR code contains the requestId: /auth/qr-scan?requestId=abc123</li><li>Mobile app scans → sends requestId=abc123 to server</li><li>Server looks up: &quot;abc123&quot; → finds &quot;user123&quot;</li><li><strong>Now server knows to authenticate user123 on the mobile device</strong></li></ul><p>The requestId is essentially the &quot;handshake token&quot; that bridges two completely separate contexts—the desktop browser session and the mobile app—allowing secure user identification across devices.</p><h3>The Cross-Device Flow in Action</h3><p>Here’s how the complete cross-device authentication works:</p><ol><li>User requests magic link on mobile app</li><li>User clicks magic link on their desktop computer</li><li>System detects desktop browser, creates requestId, stores user info in Redis</li><li>Desktop browser redirects to /auth/qr?requestId=...</li><li>Frontend calls our QR endpoint to get the QR code image</li><li>QR code contains: ${BACKEND_URL}/auth/qr-scan?requestId=${requestId}</li><li>User has two options:</li></ol><ul><li><strong>Mobile Authentication</strong>: Scan QR code with mobile app, which calls /auth/continue</li><li><strong>Desktop Authentication</strong>: Click “Continue on this device” button to authenticate on PC</li></ul><h3>The Final Piece: /auth/continue Endpoint</h3><p>The mobile app scans the QR code, extracts the requestId, and calls the /auth/continue endpoint to complete the authentication flow:</p><pre>async continueOnDevice(req: Request, res: Response) {<br>  const { requestId } = req.body;<br>  if (!requestId || typeof requestId !== &quot;string&quot;) {<br>    return res.status(400).json({ error: &quot;Missing or invalid requestId&quot; });<br>  }<br><br>try {<br>    // Retrieve stored session from Redis<br>    const sessionKey = `auth:qr:${requestId}`;<br>    const userId = await redisUtil.get(sessionKey);<br>    if (!userId) {<br>      return res.status(400).json({ error: &quot;Invalid or expired session&quot; });<br>    }<br>    // Get user from DB<br>    const user = await prisma.user.findUnique({ where: { id: userId } });<br>    if (!user) {<br>      return res.status(404).json({ error: &quot;User not found&quot; });<br>    }<br>    // Access token payload<br>    const payload: TokenPayload = {<br>      userId: user.id,<br>      email: user.email,<br>      type: &quot;magiclink&quot;,<br>    };<br>    // 1️⃣ Issue short-lived access token<br>    const accessToken = await (magicLinkService as any)[<br>      &quot;tokenService&quot;<br>    ].generateToken(payload, { expiresIn: process.env.JWT_EXPIRY || &quot;1h&quot; });<br>    // 2️⃣ Generate and store long-lived refresh token<br>    const refreshTokenValue = crypto.randomBytes(32).toString(&quot;hex&quot;);<br>    const refreshTokenHash = crypto<br>      .createHash(&quot;sha256&quot;)<br>      .update(refreshTokenValue)<br>      .digest(&quot;hex&quot;);<br>    await prisma.refreshToken.create({<br>      data: {<br>        tokenHash: refreshTokenHash,<br>        userId: user.id,<br>        expiresAt: addDays(new Date(), 30), // 30 days validity<br>      },<br>    });<br>    // 3️⃣ Store both tokens in HTTP-only cookies<br>    res.cookie(&quot;auth_token&quot;, accessToken, {<br>      httpOnly: true,<br>      secure: process.env.NODE_ENV === &quot;production&quot;,<br>      sameSite: &quot;lax&quot;,<br>      maxAge: 3600 * 1000, // 1h<br>    });<br>    res.cookie(&quot;refresh_token&quot;, refreshTokenValue, {<br>      httpOnly: true,<br>      secure: process.env.NODE_ENV === &quot;production&quot;,<br>      sameSite: &quot;lax&quot;,<br>      maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days<br>    });<br>    // 4️⃣ Clean up Redis<br>    await redisUtil.del(sessionKey);<br>    // ✅ Send user data in response<br>    return res.json({<br>      success: true,<br>      user: {<br>        id: user.id,<br>        email: user.email,<br>        phone: user.phone,<br>        name: user.name,<br>        timeZone: user.timeZone,<br>        createdAt: user.createdAt,<br>        updatedAt: user.updatedAt,<br>        onboarded: user.onboarded,<br>      },<br>    });<br>  } catch (err) {<br>    console.error(&quot;ContinueOnDevice error:&quot;, err);<br>    return res.status(500).json({ error: &quot;Internal server error&quot; });<br>  }<br>}</pre><p>This endpoint is where all the cross-device magic comes together. Let me break down what makes this implementation robust:</p><h3>The Authentication Completion Process</h3><p><strong>1. Request Validation</strong>: The endpoint expects a requestId in the request body—this comes from either the QR code scan or the desktop &quot;continue on this device&quot; action.</p><p><strong>2. Session Retrieval</strong>: Using the requestId, we retrieve the stored userId from Redis. Remember, this was stored with a short TTL (120 seconds) when the user first clicked the magic link.</p><p><strong>3. User Verification</strong>: We fetch the complete user record from the database to ensure the user still exists and get their current information.</p><p><strong>4. Dual Token Strategy</strong>: Here’s where the security gets interesting. Instead of just issuing one token, I implement a dual-token approach:</p><ul><li><strong>Access Token</strong>: Short-lived (1 hour) JWT for API requests</li><li><strong>Refresh Token</strong>: Long-lived (30 days) cryptographically secure random token</li></ul><p><strong>5. Secure Cookie Storage</strong>: Both tokens get stored in HTTP-only cookies, making them inaccessible to client-side JavaScript and protecting against XSS attacks.</p><p><strong>6. Session Cleanup</strong>: The requestId gets deleted from Redis immediately after use, ensuring each QR code or magic link can only be used once.</p><h3>Why the Dual Token Approach?</h3><p>This authentication strategy balances security with user experience:</p><p><strong>Short Access Tokens</strong> mean that if a token is compromised, the exposure window is limited to just one hour.</p><p><strong>Long Refresh Tokens</strong> allow users to stay logged in for weeks without re-authentication, but they’re stored securely and can be revoked if needed.</p><p><strong>HTTP-Only Cookies</strong> protect both tokens from client-side attacks while still allowing automatic inclusion in requests.</p><p>The refresh token gets hashed before storage — even if someone gains database access, they can’t use the stored hash to authenticate.</p><h3>Service Architecture: Why Classes Over Functions</h3><p>Before we wrap up, I want to address an architectural choice that might seem old-fashioned in the modern JavaScript ecosystem: using classes for services instead of simple functions or modules.</p><p>I could have structured the authentication services as collections of functions:</p><pre>// The typical functional approach<br>export const sendMagicLink = async (email: string) =&gt; {<br>  /* ... */<br>};<br>export const validateToken = async (token: string) =&gt; {<br>  /* ... */<br>};</pre><p>But I chose a class-based approach for my services:</p><pre>const magicLinkService = new MagicLinkServiceImpl({<br>  magicLinkBaseUrl:<br>    process.env.BACKEND_URL ||<br>    &quot;http://localhost:4000/api/auth/magiclink/validate&quot;,<br>  jwtSecret: process.env.JWT_SECRET || &quot;your-secret-key&quot;,<br>  tokenExpiry: &quot;1h&quot;,<br>  redisPrefix: &quot;auth:&quot;,<br>});</pre><p>Let me show you exactly why this matters with a concrete comparison.</p><h3>The Functional Approach: What I Could Have Done</h3><p>Here’s how the functional approach typically looks for magic link authentication:</p><pre>// services/magicLinkService.ts (Functional)<br>import { emailService } from &quot;./emailService&quot;;<br>import { generateToken, verifyToken } from &quot;./tokenService&quot;;<br>import { redisUtil } from &quot;../utils/redis&quot;;<br><br>export const sendMagicLink = async (email: string): Promise&lt;void&gt; =&gt; {<br>  try {<br>    const payload = { email, type: &quot;magiclink&quot; };<br>    // Configuration scattered across function calls<br>    const token = await generateToken(payload, {<br>      expiresIn: process.env.TOKEN_EXPIRY || &quot;15m&quot;,<br>      secret: process.env.JWT_SECRET,<br>    });<br>    const baseUrl = process.env.BACKEND_URL || &quot;http://localhost:4000&quot;;<br>    const link = `${baseUrl}/api/auth/magiclink/validate?token=${token}`;<br>    // Redis configuration repeated<br>    const redisKey = `auth:magiclink:${token}`;<br>    const ttl = 15 * 60;<br>    await redisUtil.set(redisKey, email, ttl);<br>    await emailService.sendMagicLink(email, link);<br>  } catch (error) {<br>    throw error;<br>  }<br>};<br>export const validateToken = async (<br>  token: string<br>): Promise&lt;TokenPayload | null&gt; =&gt; {<br>  try {<br>    // Configuration repeated again<br>    const payload = await verifyToken(token, process.env.JWT_SECRET);<br>    const redisKey = `auth:magiclink:${token}`;<br>    const storedEmail = await redisUtil.get(redisKey);<br>    if (!storedEmail || storedEmail !== payload.email) return null;<br>    await redisUtil.del(redisKey);<br>    return payload;<br>  } catch (error) {<br>    return null;<br>  }<br>};</pre><h3>The Class-Based Approach: What I Did</h3><p>Now here’s the same functionality using the class-based architecture:</p><pre>// interfaces/MagicLinkService.ts<br>interface MagicLinkConfig {<br>  magicLinkBaseUrl: string;<br>  jwtSecret: string;<br>  tokenExpiry: string;<br>  redisPrefix: string;<br>}</pre><pre>// services/MagicLinkServiceImpl.ts<br>class MagicLinkServiceImpl implements MagicLinkService {<br>  private tokenService: TokenService;<br>  private config: MagicLinkConfig;</pre><pre>  constructor(config: MagicLinkConfig) {<br>    this.config = config;<br>    // Dependency injection - tokenService configured once<br>    this.tokenService = new JWTTokenService(config.jwtSecret);<br>  }</pre><pre>  async requestMagicLink(email: string): Promise&lt;void&gt; {<br>    try {<br>      const payload = { email, type: &quot;magiclink&quot; };</pre><pre>      // Configuration accessed from instance state<br>      const token = await this.tokenService.generateToken(payload, {<br>        expiresIn: this.config.tokenExpiry,<br>      });</pre><pre>      const link = `${this.config.magicLinkBaseUrl}?token=${token}`;</pre><pre>      // Consistent Redis key generation<br>      const redisKey = this.getRedisKey(token);<br>      const ttl = 15 * 60;<br>      await redisUtil.set(redisKey, email, ttl);<br>      await emailService.sendMagicLink(email, link);<br>    } catch (error) {<br>      throw error;<br>    }<br>  }</pre><pre>  async validateToken(token: string): Promise&lt;TokenPayload | null&gt; =&gt; {<br>    try {<br>      // No need to pass secret - tokenService already configured<br>      const payload = await this.tokenService.verifyToken(token);<br>      const redisKey = this.getRedisKey(token);<br>      const storedEmail = await redisUtil.get(redisKey);</pre><pre>      if (!storedEmail || storedEmail !== payload.email) return null;</pre><pre>      await redisUtil.del(redisKey);<br>      return payload;<br>    } catch (error) {<br>      return null;<br>    }<br>  }</pre><pre>  // Private helper method for consistent key generation<br>  private getRedisKey(token: string): string {<br>    return `${this.config.redisPrefix}magiclink:${token}`;<br>  }<br>}</pre><h3>Why Classes Make Sense for Authentication Services</h3><p>The differences might seem subtle, but they have real impact on maintainability and reliability:</p><h3>1. Configuration Management</h3><p><strong>Functional Problem:</strong></p><pre>// JWT secret scattered across multiple functions<br>const token = await generateToken(payload, {<br>  secret: process.env.JWT_SECRET, // Repeated everywhere<br>});</pre><p><strong>Class Solution:</strong></p><pre>// Configuration centralized and injected once<br>constructor(config: MagicLinkConfig) {<br>  this.tokenService = new JWTTokenService(config.jwtSecret);<br>}</pre><h3>2. Consistency Guarantees</h3><p><strong>Functional Risk:</strong></p><pre>// Redis keys might be inconsistent<br>const redisKey = `auth:magiclink:${token}`; // sendMagicLink<br>const sessionKey = `auth:qr:${requestId}`; // different function</pre><p><strong>Class Protection:</strong></p><pre>// Single method ensures consistency<br>private getRedisKey(token: string): string {<br>  return `${this.config.redisPrefix}magiclink:${token}`;<br>}</pre><h3>3. Testing Simplicity</h3><p>The class approach makes testing dramatically cleaner:</p><pre>// Class-based testing<br>describe(&quot;Magic Link Service&quot;, () =&gt; {<br>  let service: MagicLinkService;<br><br>beforeEach(() =&gt; {<br>    // Clean dependency injection<br>    service = new MagicLinkServiceImpl({<br>      magicLinkBaseUrl: &quot;http://test.com/auth&quot;,<br>      jwtSecret: &quot;test-secret&quot;,<br>      tokenExpiry: &quot;15m&quot;,<br>      redisPrefix: &quot;test:&quot;,<br>    });<br>  });<br><br>it(&quot;should generate consistent redis keys&quot;, () =&gt; {<br>    // Each test gets isolated service instance<br>    // No global mocking needed<br>  });<br>});</pre><p>Compare this to the functional approach, where you’d need to mock process.env variables and deal with global function mocking that can affect other tests.</p><h3>When Functions Still Make Sense</h3><p>I’m not advocating for classes everywhere. For pure utility functions or stateless operations, functions are perfect:</p><pre>// Perfect as functions<br>export const hashPassword = (password: string) =&gt; bcrypt.hash(password, 10);<br>export const validateEmail = (email: string) =&gt;<br>  /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);</pre><p>But for services that:</p><ul><li>Manage configuration state</li><li>Have multiple related operations</li><li>Need dependency injection</li><li>Require consistent behavior across methods</li></ul><p>Classes provide cleaner architecture without the overhead.</p><h3>The Production Impact</h3><p>For my prescription management app, this architectural choice has paid dividends:</p><ul><li><strong>Environment Switching</strong>: Different Redis prefixes and base URLs for dev/staging/production</li><li><strong>Security Updates</strong>: When I needed to rotate JWT secrets, I changed one configuration point</li><li><strong>Feature Additions</strong>: Adding token refresh and session management naturally extended the existing service</li><li><strong>Bug Prevention</strong>: Consistent Redis key generation eliminated a whole class of “token not found” bugs</li></ul><p>This isn’t about being old-school or new-school — it’s about choosing the right tool for the job. Authentication services have enough complexity and state to benefit from the structure that classes provide.</p><h3>Wrapping Up: A Complete Authentication Solution</h3><p>We’ve covered the core implementation of a production-ready magic link authentication system that elegantly handles cross-device scenarios. From token generation and email delivery to QR codes and session management, this approach provides a seamless user experience while maintaining strong security principles.</p><p>While this article covers the essential components, a complete authentication system involves additional considerations like error handling, rate limiting, token refresh mechanisms, and comprehensive logging. The architecture we’ve built provides a solid foundation that can be extended as your application’s needs grow.</p><h3>See the Full Implementation</h3><p>The complete codebase for this magic link authentication system is available on GitHub. You’ll find additional utilities, error handling, and configuration details that weren’t covered in this article.</p><p><a href="https://github.com/Nateight8/medicare"><strong>View the complete project on GitHub</strong></a></p><p>If you found this implementation helpful, I’d appreciate:</p><ul><li>A star on the repository</li><li>Contributions and improvements via pull requests</li><li>Your thoughts and questions in the issues section</li></ul><p>Building authentication systems taught me that the real challenge isn’t just making them work — it’s making them work reliably across different devices, email clients, and user scenarios. I hope this approach helps you create authentication experiences that your users will actually enjoy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa791fa48ea8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I Ditched Passwords for Magic Links: A Developer’s Journey Away from Authentication Complexity]]></title>
            <link>https://javascript.plainenglish.io/why-i-ditched-passwords-for-magic-links-a-developers-journey-away-from-authentication-complexity-a4e437b9936d?source=rss-ccb9dee6e319------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4e437b9936d</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[nextauth]]></category>
            <dc:creator><![CDATA[Mbaocha Jonathan]]></dc:creator>
            <pubDate>Sat, 23 Aug 2025 19:14:12 GMT</pubDate>
            <atom:updated>2025-08-24T02:22:41.022Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Authentication has always been one of those features that seems straightforward until you actually try to implement it well. My journey through different authentication methods taught me that sometimes the simplest solution is also the best one — both for developers and users.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*afzkHJJt0H2dHL5yLJ75hg.png" /></figure><h3>The OAuth Days: When Third-Party Felt Right</h3><p>For the longest time, I was an OAuth evangelist. Back when I was primarily focused on frontend development, using Auth.js (previously NextAuth.js) felt like the perfect solution. Why reinvent the wheel when Google, GitHub, and Facebook had already solved authentication for millions of users?</p><p>OAuth made sense: users got familiar login flows, I avoided the complexity of password management, and security was largely handled by providers with dedicated teams and resources. It seemed like a win-win situation.</p><p>But to be honest, authentication pages feel less complete without email authentication. Just OAuth buttons sitting there aren’t pretty — there’s something missing from the design aesthetically. This was partly what drove me to explore email-based authentication.</p><h3>The Password Reality Check</h3><p>When I dove into Auth.js documentation to implement email/password login, I discovered something that stopped me in my tracks. This authentication method wasn’t just becoming obsolete — it was actively discouraged.</p><p>The technical overhead hit me immediately:</p><ul><li>Password hashing algorithms and security best practices</li><li>Password strength validation</li><li>Secure password recovery flows</li><li>Protection against brute force attacks</li><li>Handling password resets without creating security vulnerabilities</li></ul><p>As someone transitioning from frontend to full-stack development, I realized I was about to take on significant security responsibilities. The documentation’s gentle nudge toward OAuth suddenly made perfect sense.</p><h3>The NeonLink Wake-Up Call</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*77AP2GcKppwc6lIjPazO-w.png" /><figcaption>neonlink authentication page</figcaption></figure><p>Months passed, and I found myself working on <a href="https://neolink-tawny.vercel.app/">NeoLink</a>, a social platform for chess enthusiasts where users could challenge each other to games. I’ll be honest — I was in a hurry to ship something for my portfolio, so I took shortcuts.</p><p>I implemented basic email/password authentication without the password recovery flow. My reasoning? “I’ll add that later.”</p><p>The result was a user experience nightmare. When users forgot their passwords, they hit a dead end. They couldn’t log in, but they also couldn’t create a new account because their email was already in the database. I had essentially created user accounts that could become permanently inaccessible.</p><p>This wasn’t just bad UX — it was embarrassing. Here I was, building a platform meant to bring people together over chess, and I was locking them out over forgotten passwords.</p><h3>The Magic Link Epiphany</h3><p>While reflecting on how to fix NeoLink’s authentication disaster, a different approach came to mind: magic links.</p><p>Before researching existing implementations, I tried to work through the logic myself:</p><ol><li>User provides their email address</li><li>Server generates a secure token and sends it via email (I planned to use Nodemailer)</li><li>User clicks the link, which validates the token</li><li>If valid, user is authenticated</li></ol><p>The beauty of this approach struck me immediately. From a technical standpoint, it was elegantly simple — no password hashing, no complex recovery flows, just token generation and validation.</p><p>But the UX benefits were even more compelling:</p><ul><li><strong>No passwords to remember</strong>: Users’ email inboxes become their authentication vault</li><li><strong>Inherently secure</strong>: Requires both something they know (email) and something they have (inbox access)</li><li><strong>Familiar pattern</strong>: Users already understand and trust email-based workflows</li><li><strong>No provider confusion</strong>: No “Did I sign up with Google or GitHub?” moments</li></ul><h3>The Cross-Device Challenge</h3><p>I wasn’t planning to revisit NeoLink — instead, I wanted to apply this magic link architecture to a new project: a prescription management mobile app built with React Native. I had learned React Native but had no projects to showcase it, and I personally needed a way to track my medications.</p><p>Initially, I planned for mobile-only, but then I considered an edge case that could make or break the user experience.</p><p>Imagine this scenario: A user initiates authentication on their mobile app, requesting a magic link. But their email is open on their PC. When they click the magic link on their computer, how does their mobile app receive the authentication token?</p><p>This cross-device authentication challenge required creative thinking.</p><h3>Designing for Cross-Device Reality</h3><p>My solution involved making the server intelligent about where authentication requests originate:</p><p>When a user clicks a magic link, the server detects the device/platform making the request. If the validation happens on a web browser (likely their PC), the user gets redirected to a web interface with two options:</p><ol><li><strong>QR Code Authentication</strong>: Scan a code with their mobile device to authenticate the app</li><li><strong>Web Authentication</strong>: Continue using the application on their current device</li></ol><p>For the QR code flow, I’m considering either WebSocket connections for real-time communication or polling to sync the mobile authentication state.</p><p>This approach acknowledges that users live in a multi-device world. Rather than forcing them into a single authentication path, it gracefully handles the reality of how people actually use technology.</p><h3>Looking Forward</h3><p>Magic links solved multiple problems simultaneously: they simplified my technical implementation, improved user experience, and eliminated the security overhead of password management. The cross-device flow addresses a real-world usage pattern that many authentication systems ignore.</p><p>In Part 2 of this series, I’ll dive into the technical implementation details, including:</p><ul><li>Why I chose REST endpoints for authentication in a GraphQL-first application</li><li>Token generation and email delivery implementation</li><li>Cross-device detection and routing logic</li><li>The architecture decisions that make this approach scalable</li></ul><p>Sometimes the best solution isn’t the most complex one — it’s the one that works seamlessly for both developers and users.</p><p><em>What’s your experience with different authentication methods? Have you encountered similar cross-device challenges? I’d love to hear about your approach in the comments.</em></p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4e437b9936d" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/why-i-ditched-passwords-for-magic-links-a-developers-journey-away-from-authentication-complexity-a4e437b9936d">Why I Ditched Passwords for Magic Links: A Developer’s Journey Away from Authentication Complexity</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Cloud Computing Blows My Mind: A Software Developer’s Love Letter]]></title>
            <link>https://javascript.plainenglish.io/why-cloud-computing-blows-my-mind-a-software-developers-love-letter-55a7e5a6a16e?source=rss-ccb9dee6e319------2</link>
            <guid isPermaLink="false">https://medium.com/p/55a7e5a6a16e</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cloud-services]]></category>
            <dc:creator><![CDATA[Mbaocha Jonathan]]></dc:creator>
            <pubDate>Fri, 11 Jul 2025 08:54:22 GMT</pubDate>
            <atom:updated>2025-07-13T00:31:00.491Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qIjaRBJibZom3E7wwUbJTA.png" /></figure><p>As a software developer, I’ve witnessed the evolution of computing from physical servers to the cloud revolution we’re living through today. But nothing has made me appreciate the sheer elegance and power of cloud computing quite like witnessing what seemed impossible just a few years ago become routine today.</p><p>This isn’t just about technology — it’s about a fundamental shift in how we think about computing power, accessibility, and what’s possible when brilliant infrastructure meets creative problem-solving. Through exploring the conversations between computers that power our digital world, I want to show you why cloud computing represents one of the most fascinating developments in our field.</p><p>Join me as I break down the magic that happens behind every web interaction, and discover why this technology represents everything I love about modern software development.</p><h3>The Web as Computers Talking to Computers: Understanding Network Communication</h3><p>The web, at its most fundamental level, is just a bunch of computers having conversations with each other using agreed-upon languages and protocols. When you type a URL in your browser, you’re essentially telling your computer “go talk to that computer over there and ask for this specific thing.”</p><h3>The Basic Conversation</h3><p>Your computer (the client) sends a message across the network to another computer (the server) saying something like “Hey, can I have the HTML for example.com?” The server computer reads that message, figures out what you want, and sends back a response — maybe an HTML file, an image, or some JSON data.</p><p>But these computers don’t talk directly to each other. Your request bounces through multiple computers along the way: your router, your ISP’s computers, various network infrastructure — routers, switches, DNS servers — before finally reaching the destination server. Each hop is another computer making a decision about where to forward your message next.</p><p>The elegant part is that all these different computers speak the same basic language: TCP/IP for low-level networking, HTTP for web requests, DNS for looking up addresses. It’s like having a universal translator that lets any computer talk to any other computer.</p><h3>How Pages Actually Load</h3><p>When you visit a page, that initial GET request is like getting a blueprint. The server sends back HTML that says &quot;here&#39;s the basic structure, BUT you&#39;ll also need these other files to make this page complete.&quot;</p><p>Those &lt;link&gt; tags in the &lt;head&gt; are essentially a shopping list for the browser:</p><pre>&lt;head&gt;<br>  &lt;link rel=&quot;stylesheet&quot; href=&quot;styles.css&quot;&gt;<br>  &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdn.example.com/bootstrap.css&quot;&gt;<br>  &lt;script src=&quot;app.js&quot;&gt;&lt;/script&gt;<br>&lt;/head&gt;</pre><p>The browser reads this and immediately fires off separate HTTP requests for each resource. What looks like “visiting one page” is actually multiple computer-to-computer conversations happening in sequence.</p><h3>Making Your Own Requests</h3><p>While browsers handle initial page loads automatically, you can manually make requests using JavaScript’s fetch() API:</p><pre>// Your computer asking another computer for data<br>fetch(&#39;https://api.example.com/users/1&#39;)<br>  .then(response =&gt; response.json())<br>  .then(data =&gt; {<br>    console.log(&#39;Server computer responded with:&#39;, data);<br>  })<br>  .catch(error =&gt; {<br>    console.error(&#39;Computer communication failed:&#39;, error);<br>  });</pre><p>Behind the scenes, this is the actual conversation:</p><pre>// Your browser says:<br>GET /api/users/1 HTTP/1.1<br>Host: api.example.com<br>Accept: application/json</pre><pre>// The server responds:<br>HTTP/1.1 200 OK<br>Content-Type: application/json</pre><pre>{&quot;id&quot;: 1, &quot;name&quot;: &quot;John Doe&quot;}</pre><h3>Three Ways Servers Respond</h3><p>Every page comes from a server, but what the server sends back varies:</p><p><strong>Static Pages</strong> — Server sends complete HTML with all content baked in. One conversation: browser → server → complete HTML.</p><p><strong>Server-Side Rendered</strong> — Server fetches data from other computers first, embeds it in HTML, then sends the complete page. Still one conversation from the browser’s perspective.</p><p><strong>Client-Side Rendered</strong> — Server sends a minimal HTML shell and JavaScript. Then your browser makes additional conversations with API servers to get the actual data.</p><h3>The Distributed Nature</h3><p>Each of these approaches creates different patterns of computer-to-computer communication. A single web page might involve your browser talking to:</p><ul><li>A web server for HTML</li><li>A CDN for CSS and JavaScript files</li><li>An API server for user data</li><li>Another API for product information</li><li>A third-party service for analytics</li></ul><p>All of these are separate computers, often in different data centers around the world, yet they coordinate to create a single, cohesive user experience.</p><h3>Where the Servers Actually Live — Enter the Cloud</h3><p>So far we’ve talked about “servers” and “other computers” in abstract terms. But where do these computers actually exist? In today’s world, they’re not sitting in office closets or basement server rooms. They’re in massive data centers managed by cloud providers like Amazon Web Services (AWS), Google Cloud Platform, and Microsoft Azure. These companies own and operate thousands of physical computers in warehouse-sized buildings around the world.</p><p>Instead of businesses buying and maintaining their own servers, they rent computing power from these providers. When you “deploy to the cloud,” you’re essentially renting space on someone else’s computer. Think of it like this: instead of every restaurant having its own power plant, they all plug into the electrical grid. Cloud computing works the same way — instead of every company running their own servers, they plug into the “computing grid” provided by cloud companies.</p><p>The evolution of how we use these cloud computers is fascinating. In the old days, you’d rent an entire physical computer. If you needed more power, you’d rent another whole computer. Wasteful and expensive. Then cloud providers figured out how to slice one physical computer into multiple virtual computers. Now you could rent just the portion you needed — maybe half a computer’s processing power, or just 2GB of its memory.</p><p>The newest approach packages your application with everything it needs to run in what’s called a container, then runs multiple containers on the same virtual machine. It’s like having apartments in a building instead of everyone needing their own house.</p><p>Here’s where it gets really interesting: in the cloud, computers can be created and destroyed on demand. Need more servers to handle traffic? New ones can be spun up in minutes. Traffic dies down? Shut them down and stop paying for them. This is fundamentally different from the old model where you had to buy physical hardware and hope you estimated your needs correctly. With cloud computing, the infrastructure can adapt to your actual usage in real-time.</p><p>When your application gets popular, a single computer might not be able to handle all the requests. Cloud computing makes it easy to scale in two ways. You can give your computer more power — more CPU, more memory — like upgrading from a small apartment to a bigger one. Or you can add more computers to share the load, like having multiple apartments instead of one huge one. Modern cloud applications often use the second approach because it’s more resilient — if one computer fails, the others keep running.</p><p>What’s remarkable is how invisible this has become. When you make a fetch() request to an API, you have no idea which physical data center is handling your request, whether it&#39;s running on a virtual machine or in a container, if the server was created 5 minutes ago or 5 years ago, or how many other applications are sharing the same physical hardware. The cloud providers handle all of this complexity, presenting a simple interface: &quot;here&#39;s an endpoint, send your requests here.&quot;</p><h3>The Mind-Blowing Reality of Cloud Gaming</h3><p>Think about this for a moment: you can pull out your phone, open an app, and within seconds be playing <em>Cyberpunk 2077</em> with ray tracing enabled and ultra-high settings — on a device that couldn’t normally run a basic puzzle game at those graphics levels. This isn’t magic; it’s cloud computing at its most impressive.</p><p>Services like <strong>NVIDIA GeForce Now</strong>, <strong>Xbox Cloud Gaming</strong>, <strong>Amazon Luna</strong>, and <strong>PlayStation Plus Premium</strong> represent cloud computing’s most audacious promise: turning any screen into a portal to unlimited computing power. Somewhere in a data center hundreds of miles away, a high-end gaming rig with a $1,500 graphics card is rendering your game in real-time. The pixels are being painted on a screen you’ll never see, in a building you’ll never visit, by a computer that was probably created just for your gaming session.</p><p>What’s truly fascinating is the orchestration happening behind the scenes. Your button press travels across the internet to a data center, gets processed by a virtual machine that might be sharing physical hardware with dozens of other gamers, triggers the game engine to render the next frame, and that frame gets encoded into a video stream and sent back to your device — all in under 30 milliseconds to feel responsive.</p><p>The infrastructure required is staggering: these companies maintain thousands of gaming-capable computers across dozens of data centers worldwide, all so you can play the latest AAA title on a device that costs less than a single graphics card. When demand spikes, they spin up more virtual gaming rigs. When it drops, they shut them down and repurpose that hardware for other tasks.</p><p>This is cloud computing’s ultimate demonstration of turning any device into a window to virtually unlimited computational power. Your phone becomes a gaming PC, your tablet becomes a workstation, your browser becomes a portal to software that would otherwise require expensive hardware. It’s the clearest example of how the cloud has fundamentally changed what’s possible with computing.</p><h3>Why This Matters</h3><p>Understanding that the web is fundamentally about computers talking to computers — and that these computers are now dynamically provisioned cloud resources — helps explain:</p><ul><li>Why network latency matters (your request might travel to a data center on another continent)</li><li>Why requests can fail unpredictably (virtual machines can be terminated, containers can crash)</li><li>Why caching strategies are important (reduce the distance between computers)</li><li>Why API design affects performance (efficient communication between cloud resources)</li><li>Why distributed systems are both powerful and complex (coordinating many computers across many data centers)</li></ul><p>The web isn’t just about writing code — it’s about orchestrating conversations between computers across a distributed system that spans the globe, powered by cloud infrastructure that can scale and adapt in real-time. And that’s what makes it both challenging and fascinating to work with.</p><h3>Final Thoughts</h3><p>Cloud computing isn’t just a backend detail — it’s the new foundation of how we build, scale, and even think about software. From API requests to full-blown gaming experiences, we’re no longer bound by the limits of our local machines. As developers, understanding the moving parts behind these interactions gives us not just better tools, but a deeper appreciation of the systems we help create. The future is distributed, dynamic, and powered by cloud — and we’re lucky enough to be building it.</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55a7e5a6a16e" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/why-cloud-computing-blows-my-mind-a-software-developers-love-letter-55a7e5a6a16e">Why Cloud Computing Blows My Mind: A Software Developer’s Love Letter</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Frontend Architecture: A Complete Guide to Building Scalable Next.js Applications]]></title>
            <link>https://medium.com/bitsrc/frontend-architecture-a-complete-guide-to-building-scalable-next-js-applications-d28b0000e2ee?source=rss-ccb9dee6e319------2</link>
            <guid isPermaLink="false">https://medium.com/p/d28b0000e2ee</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Mbaocha Jonathan]]></dc:creator>
            <pubDate>Mon, 07 Jul 2025 08:38:03 GMT</pubDate>
            <atom:updated>2025-07-07T08:38:03.592Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dN9q0DLP70Sth2cuj8_8Pw.png" /></figure><p><em>How to architect modern frontend applications that scale, perform, and delight users</em></p><p>After years of building React applications and watching teams struggle with architectural decisions, I’ve learned that good frontend architecture isn’t just about choosing the right tools — it’s about making informed decisions that serve your application’s specific needs. Today, I want to share what I’ve learned about architecting Next.js applications, from data fetching patterns to deployment strategies.</p><h3>The Foundation: Understanding Frontend Architecture</h3><p>Frontend architecture is essentially the blueprint for how your application is structured, organized, and built. It’s the difference between a codebase that grows gracefully and one that becomes unmaintainable after six months.</p><p>When I start a new Next.js project, I focus on four key areas:</p><ul><li><strong>Component Organization</strong>: How code is structured and components are organized</li><li><strong>State Management</strong>: How data flows through the application</li><li><strong>Data Fetching</strong>: How the frontend communicates with APIs and manages server state</li><li><strong>Performance &amp; Deployment</strong>: How the application is optimized and delivered to users</li></ul><p>Let me walk you through each of these in detail.</p><h3>Component Organization: Building a Scalable Structure</h3><p>The first architectural decision you’ll make is how to organize your components. After experimenting with various approaches, I’ve settled on this pattern, partly inspired by shadcn/ui’s organization philosophy:</p><pre>components/<br>  ui/                    # Shared UI components (inspired by shadcn/ui)<br>    Button.tsx<br>    Modal.tsx<br>    Input.tsx<br>app/<br>  about/<br>    _components/         # Route-specific components<br>      AboutHero.tsx<br>      TeamSection.tsx<br>    page.tsx<br>  dashboard/<br>    _components/<br>      DashboardStats.tsx<br>      UserProfile.tsx<br>    page.tsx</pre><p>This structure creates clear boundaries. Shared components live in components/ui/, while route-specific components stay close to where they&#39;re used. This prevents unnecessary coupling and makes it easier to understand component relationships.</p><h3>State Management: Choosing the Right Tool for the Job</h3><p>One of the most common questions I get is: “Should I use Redux, Context, or just React Query?” The answer depends on what type of state you’re managing.</p><p><strong>For Server State: React Query (TanStack Query)</strong> Server state — data that lives on your backend — should be managed with React Query. It handles caching, background updates, and synchronization beautifully:</p><pre>const { data: user, isLoading, error } = useQuery([&#39;user&#39;], fetchUser)</pre><p><strong>For Global Client State: Context API</strong> For simple global state like theme preferences or authentication status, Context API works perfectly:</p><pre>const { theme, setTheme } = useTheme()</pre><p><strong>For Complex Client State: Redux Toolkit</strong> Only reach for Redux when you have complex state logic that needs to be shared across multiple components or when you need sophisticated debugging capabilities.</p><p>The key insight here is that most applications don’t need Redux if you’re using React Query effectively for server state management.</p><h3>Organizing State Management in Your Project</h3><p>When implementing these state management solutions, here’s how I structure them in the project:</p><pre>lib/<br>  auth/<br>    auth-context.tsx      # Authentication context<br>    auth-provider.tsx     # Auth provider wrapper<br>  store/<br>    store.ts             # Redux store configuration<br>    slices/<br>      user-slice.ts      # User-related state<br>      ui-slice.ts        # UI state (modals, themes)<br>  api/<br>    query-client.ts      # React Query configuration<br>    hooks/<br>      use-users.ts       # User-related queries<br>      use-posts.ts       # Post-related queries<br>providers/<br>  app-providers.tsx      # Combined providers wrapper</pre><p>Then wrap your app with all providers:</p><pre>// components/app-providers.tsx<br>export function AppProviders({ children }: { children: React.ReactNode }) {<br>  return (<br>    &lt;QueryClientProvider client={queryClient}&gt;<br>      &lt;Provider store={store}&gt;<br>        &lt;AuthProvider&gt;<br>          &lt;ThemeProvider&gt;<br>            {children}<br>          &lt;/ThemeProvider&gt;<br>        &lt;/AuthProvider&gt;<br>      &lt;/Provider&gt;<br>    &lt;/QueryClientProvider&gt;<br>  )<br>}</pre><h3>Data Fetching: Patterns That Scale</h3><p>Data fetching is where Next.js really shines, especially with the App Router. Understanding when to use each pattern is crucial for building performant applications.</p><h3>Server Components (The New Default)</h3><p>With the App Router, Server Components are the default and perfect for most data fetching:</p><pre>// app/dashboard/page.tsx<br>async function Dashboard() {<br>  const users = await fetch(&#39;https://api.example.com/users&#39;)<br>  const data = await users.json()<br>  <br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Dashboard&lt;/h1&gt;<br>      &lt;UserList users={data} /&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>Server Components fetch data on the server and stream HTML to the client. They’re perfect for initial page loads and SEO-critical content.</p><h3>Static Generation with App Router</h3><p>For content that doesn’t change frequently, use static generation:</p><pre>// app/blog/[slug]/page.tsx<br>export async function generateStaticParams() {<br>  const posts = await fetch(&#39;https://api.example.com/posts&#39;)<br>  const data = await posts.json()<br>  <br>  return data.map((post) =&gt; ({<br>    slug: post.slug,<br>  }))<br>}</pre><pre>async function BlogPost({ params }: { params: { slug: string } }) {<br>  const post = await fetch(`https://api.example.com/posts/${params.slug}`)<br>  const data = await post.json()<br>  <br>  return &lt;Article post={data} /&gt;<br>}</pre><h3>Dynamic Rendering with Revalidation</h3><p>For semi-dynamic content, use time-based revalidation:</p><pre>// app/products/page.tsx<br>async function Products() {<br>  const products = await fetch(&#39;https://api.example.com/products&#39;, {<br>    next: { revalidate: 3600 } // Revalidate every hour<br>  })<br>  const data = await products.json()<br>  <br>  return &lt;ProductGrid products={data} /&gt;<br>}</pre><h3>Client Components for Interactivity</h3><p>For interactive features, use Client Components with React Query:</p><pre>&#39;use client&#39;</pre><pre>import { useQuery } from &#39;@tanstack/react-query&#39;</pre><pre>function UserProfile({ userId }: { userId: string }) {<br>  const { data: user, isLoading, error } = useQuery({<br>    queryKey: [&#39;user&#39;, userId],<br>    queryFn: () =&gt; fetchUser(userId)<br>  })<br>  <br>  if (isLoading) return &lt;UserSkeleton /&gt;<br>  if (error) return &lt;ErrorMessage /&gt;<br>  <br>  return &lt;UserCard user={user} /&gt;<br>}</pre><h3>Streaming with Suspense</h3><p>For complex pages with multiple data sources, use Suspense boundaries:</p><pre>// app/dashboard/page.tsx<br>function Dashboard() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Dashboard&lt;/h1&gt;<br>      &lt;Suspense fallback={&lt;UserSkeleton /&gt;}&gt;<br>        &lt;UserProfile /&gt;<br>      &lt;/Suspense&gt;<br>      &lt;Suspense fallback={&lt;PostsSkeleton /&gt;}&gt;<br>        &lt;RecentPosts /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><h3>Optimistic Updates</h3><p>For real-time interactions, optimistic updates create a responsive user experience:</p><pre>&#39;use client&#39;</pre><pre>const mutation = useMutation({<br>  mutationFn: updateUser,<br>  onMutate: async (newData) =&gt; {<br>    await queryClient.cancelQueries({ queryKey: [&#39;user&#39;, userId] })<br>    <br>    const previousData = queryClient.getQueryData([&#39;user&#39;, userId])<br>    queryClient.setQueryData([&#39;user&#39;, userId], newData)<br>    <br>    return { previousData }<br>  },<br>  onError: (err, variables, context) =&gt; {<br>    queryClient.setQueryData([&#39;user&#39;, userId], context?.previousData)<br>  }<br>})</pre><h3>Performance Optimization: Speed That Scales</h3><p>Performance optimization in Next.js happens at multiple levels:</p><h3>Bundle Optimization</h3><p>Next.js automatically splits your code, but you can optimize further:</p><pre>// Dynamic imports for large components<br>const Chart = dynamic(() =&gt; import(&#39;./Chart&#39;), {<br>  loading: () =&gt; &lt;ChartSkeleton /&gt;<br>})</pre><pre>// Lazy load route components<br>const Dashboard = lazy(() =&gt; import(&#39;./Dashboard&#39;))</pre><h3>Image Optimization</h3><p>Always use Next.js Image component for automatic optimization:</p><pre>import Image from &#39;next/image&#39;</pre><pre>&lt;Image<br>  src=&quot;/hero-image.jpg&quot;<br>  alt=&quot;Hero&quot;<br>  width={800}<br>  height={600}<br>  priority // For above-the-fold images<br>/&gt;</pre><h3>Caching Strategies</h3><p>Implement smart caching at multiple levels:</p><pre>// React Query caching<br>const queryClient = new QueryClient({<br>  defaultOptions: {<br>    queries: {<br>      staleTime: 5 * 60 * 1000, // 5 minutes<br>      cacheTime: 10 * 60 * 1000, // 10 minutes<br>    }<br>  }<br>})</pre><pre>// API route caching<br>export default function handler(req, res) {<br>  res.setHeader(&#39;Cache-Control&#39;, &#39;s-maxage=60, stale-while-revalidate&#39;)<br>  // ... rest of handler<br>}</pre><h3>Core Web Vitals</h3><p>Monitor and optimize the metrics that matter. You can find these metrics in Chrome DevTools:</p><ol><li><strong>Open Chrome DevTools</strong> (F12 or right-click → Inspect)</li><li><strong>Go to Lighthouse tab</strong> → Run performance audit</li><li><strong>Check the Performance tab</strong> → Record page load</li><li><strong>Use the Core Web Vitals Chrome extension</strong> for real-time monitoring</li></ol><p>Key metrics to track:</p><ul><li><strong>Largest Contentful Paint (LCP)</strong>: Optimize images and fonts</li><li><strong>First Input Delay (FID)</strong>: Minimize JavaScript execution time</li><li><strong>Cumulative Layout Shift (CLS)</strong>: Reserve space for dynamic content</li></ul><p>You can also monitor these in production using tools like Google Search Console or third-party services like Vercel Analytics.</p><h3>Build and Deploy Strategies: From Development to Production</h3><p>A solid deployment strategy ensures your application delivers consistently across environments.</p><h3>Environment Configuration</h3><p>Structure your environments clearly:</p><pre>// next.config.js<br>module.exports = {<br>  env: {<br>    API_URL: process.env.API_URL,<br>    ENVIRONMENT: process.env.NODE_ENV,<br>  },<br>  publicRuntimeConfig: {<br>    // Public variables<br>  },<br>  serverRuntimeConfig: {<br>    // Server-side only variables<br>  }<br>}</pre><h3>Build Optimization</h3><p>Configure Next.js for optimal builds:</p><pre>// next.config.js<br>module.exports = {<br>  compiler: {<br>    removeConsole: process.env.NODE_ENV === &#39;production&#39;,<br>  },<br>  experimental: {<br>    optimizeCss: true,<br>  },<br>  images: {<br>    domains: [&#39;api.example.com&#39;],<br>    formats: [&#39;image/avif&#39;, &#39;image/webp&#39;],<br>  }<br>}</pre><h3>Deployment Patterns</h3><p>Choose the right deployment strategy:</p><p><strong>Static Export</strong>: For purely static sites</p><pre>npm run build &amp;&amp; npm run export</pre><p><strong>Serverless</strong>: For applications with API routes</p><pre>// Deploy to Vercel, Netlify, or AWS Lambda</pre><p><strong>Container Deployment</strong>: For complex applications</p><pre>FROM node:18-alpine<br>COPY package*.json ./<br>RUN npm ci --only=production<br>COPY . .<br>RUN npm run build<br>CMD [&quot;npm&quot;, &quot;start&quot;]</pre><h3>CI/CD Pipeline</h3><p>Automate your deployment process:</p><pre># .github/workflows/deploy.yml<br>name: Deploy to Production<br>on:<br>  push:<br>    branches: [main]<br>jobs:<br>  deploy:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v3<br>      - name: Setup Node.js<br>        uses: actions/setup-node@v3<br>        with:<br>          node-version: &#39;18&#39;<br>      - name: Install dependencies<br>        run: npm ci<br>      - name: Run tests<br>        run: npm test<br>      - name: Build<br>        run: npm run build<br>      - name: Deploy<br>        run: npm run deploy</pre><h3>Testing Architecture: Confidence Through Automation</h3><p>A comprehensive testing strategy ensures your architecture remains stable as it grows.</p><h3>Unit Testing</h3><p>Test individual components and functions:</p><pre>// components/__tests__/Button.test.tsx<br>import { render, screen } from &#39;@testing-library/react&#39;<br>import { Button } from &#39;../Button&#39;</pre><pre>test(&#39;renders button with text&#39;, () =&gt; {<br>  render(&lt;Button&gt;Click me&lt;/Button&gt;)<br>  expect(screen.getByRole(&#39;button&#39;)).toHaveTextContent(&#39;Click me&#39;)<br>})</pre><h3>Integration Testing</h3><p>Test component interactions:</p><pre>// pages/__tests__/Dashboard.test.tsx<br>import { render, screen, waitFor } from &#39;@testing-library/react&#39;<br>import { QueryClient, QueryClientProvider } from &#39;@tanstack/react-query&#39;<br>import Dashboard from &#39;../Dashboard&#39;</pre><pre>test(&#39;displays user data after loading&#39;, async () =&gt; {<br>  const queryClient = new QueryClient({<br>    defaultOptions: { queries: { retry: false } }<br>  })<br>  <br>  render(<br>    &lt;QueryClientProvider client={queryClient}&gt;<br>      &lt;Dashboard /&gt;<br>    &lt;/QueryClientProvider&gt;<br>  )<br>  <br>  await waitFor(() =&gt; {<br>    expect(screen.getByText(&#39;Welcome, John&#39;)).toBeInTheDocument()<br>  })<br>})</pre><h3>End-to-End Testing</h3><p>Test complete user workflows:</p><pre>// e2e/user-flow.spec.ts<br>import { test, expect } from &#39;@playwright/test&#39;</pre><pre>test(&#39;user can complete purchase flow&#39;, async ({ page }) =&gt; {<br>  await page.goto(&#39;/products&#39;)<br>  await page.click(&#39;[data-testid=&quot;add-to-cart&quot;]&#39;)<br>  await page.click(&#39;[data-testid=&quot;checkout&quot;]&#39;)<br>  await page.fill(&#39;[data-testid=&quot;email&quot;]&#39;, &#39;test@example.com&#39;)<br>  await page.click(&#39;[data-testid=&quot;complete-purchase&quot;]&#39;)<br>  await expect(page.locator(&#39;[data-testid=&quot;success-message&quot;]&#39;)).toBeVisible()<br>})</pre><h3>Testing Strategy</h3><p>Structure your tests in a pyramid:</p><ul><li><strong>70% Unit Tests</strong>: Fast, isolated component tests</li><li><strong>20% Integration Tests</strong>: Component interaction tests</li><li><strong>10% E2E Tests</strong>: Critical user journey tests</li></ul><h3>Additional Architectural Considerations</h3><h3>Error Handling</h3><p>Implement comprehensive error boundaries:</p><pre>// components/ErrorBoundary.tsx<br>class ErrorBoundary extends React.Component {<br>  constructor(props) {<br>    super(props)<br>    this.state = { hasError: false }<br>  }<br>  <br>  static getDerivedStateFromError(error) {<br>    return { hasError: true }<br>  }<br>  <br>  render() {<br>    if (this.state.hasError) {<br>      return &lt;ErrorFallback /&gt;<br>    }<br>    return this.props.children<br>  }<br>}</pre><h3>Security Patterns</h3><ul><li>Validate all inputs on both client and server</li><li>Use Content Security Policy (CSP) headers</li><li>Implement proper authentication flows</li><li>Sanitize user-generated content</li></ul><h3>Accessibility Architecture</h3><ul><li>Use semantic HTML elements</li><li>Implement proper ARIA labels</li><li>Ensure keyboard navigation works</li><li>Test with screen readers</li></ul><h3>Monitoring and Analytics</h3><ul><li>Implement error tracking (Sentry, LogRocket)</li><li>Monitor performance metrics</li><li>Track user behavior and conversion funnels</li><li>Set up alerts for critical failures</li></ul><h3>Conclusion: Architecture as a Living System</h3><p>Good frontend architecture isn’t a one-time decision — it’s an evolving system that grows with your application. The patterns I’ve shared here work well for most Next.js applications, but always adapt them to your specific needs.</p><p>Remember these key principles:</p><ul><li>Start simple and add complexity only when needed</li><li>Choose the right data fetching pattern for each use case</li><li>Optimize for performance from the beginning</li><li>Test the things that matter most</li><li>Deploy with confidence through automation</li></ul><p>The goal isn’t to build the perfect architecture from day one — it’s to build something that can evolve gracefully as your application grows. Focus on making good decisions with the information you have, and don’t be afraid to refactor as you learn more about your users’ needs.</p><p>Happy building! 🚀</p><p><em>What architectural patterns have worked well for your Next.js applications? Share your experiences in the comments below.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d28b0000e2ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/frontend-architecture-a-complete-guide-to-building-scalable-next-js-applications-d28b0000e2ee">Frontend Architecture: A Complete Guide to Building Scalable Next.js Applications</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Caching in Frontend Development]]></title>
            <link>https://medium.com/bitsrc/understanding-caching-in-frontend-development-4cf8b676cf6a?source=rss-ccb9dee6e319------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cf8b676cf6a</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[apollo-client]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Mbaocha Jonathan]]></dc:creator>
            <pubDate>Tue, 29 Apr 2025 21:16:12 GMT</pubDate>
            <atom:updated>2025-04-29T21:16:12.448Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OpW9xs1iHuUhfp8e2hc9Rg.png" /><figcaption>understanding caching</figcaption></figure><h3>Basic Definition of Caching</h3><p>Caching is a technique that stores copies of data or computed results temporarily in a location (the cache) that allows faster access in future requests. Instead of recalculating values or re-fetching data from the original source each time, the system can retrieve the information from the cache, which significantly improves performance and reduces load on resources.</p><p>In frontend development, client-side caching refers to storing data directly in the user’s browser or within the JavaScript memory of your application. This allows your app to:</p><ol><li>Reduce unnecessary network requests</li><li>Speed up page rendering and interactions</li><li>Improve the user experience, especially when dealing with repeated data.</li><li>Provide functionality even when offline or during poor connectivity</li></ol><h3>Caching in Next.js Context</h3><p>For a Next.js application, client-side caching requires special consideration. Since Next.js uses server-side rendering by default, we need to be aware of where our code runs.</p><p>A key point to remember: <strong>localStorage only exists in the browser environment, not on the server</strong>.</p><h3><strong>Using localStorage in Next.js</strong></h3><p>To use localStorage for caching in Next.js, we need to:</p><ul><li>Mark components that use browser APIs with the &#39;use client&#39; directive</li><li>Handle the basic operations of setting and getting cached data</li></ul><p>Example of the most basic caching operation:</p><pre>// Component must be marked as &#39;use client&#39;<br>&#39;use client&#39;<br><br>// Storing a value in cache<br>localStorage.setItem(&quot;hello&quot;, &quot;world&quot;);<br><br>// Retrieving a value from cache<br>const cachedValue = localStorage.getItem(&quot;hello&quot;); // Returns &quot;world&quot;</pre><h3>Important Note About localStorage</h3><p>When we use localStorage.setItem(&quot;hello&quot;, &quot;world&quot;), it&#39;s crucial to understand that:</p><ul><li>Both the key (“hello”) and value (“world”) are stored as strings</li><li>The key used to retrieve the value “world” is “hello”</li><li>localStorage is <strong>not</strong> an object storage system — it’s a string-to-string storage system</li></ul><h3>Working with Complex Data Types</h3><p>Since localStorage only handles strings, we need to convert complex data types like objects and arrays to strings before storing them:</p><pre>// Storing an object in localStorage<br>const user = { name: &quot;John&quot;, age: 20 };<br>localStorage.setItem(&quot;user&quot;, JSON.stringify(user));<br><br>// Retrieving the object from localStorage<br>const getUser = JSON.parse(localStorage.getItem(&quot;user&quot;) || &quot;{}&quot;);<br><br>console.log(getUser);<br>// Returns { name: &#39;John&#39;, age: 20 }</pre><p>Note the || &quot;{}&quot; fallback pattern when retrieving data. This provides an empty object as default in case the key doesn&#39;t exist in localStorage, preventing potential errors from trying to parse a null value.</p><h3>Cleaning Up localStorage</h3><p>Best practice includes removing data from localStorage when it’s no longer needed:</p><pre>// Remove a specific item from localStorage<br>localStorage.removeItem(&quot;user&quot;);<br><br>// Clear all items from localStorage (use with caution)<br>localStorage.clear();</pre><p>The clear() method should be used carefully as it removes all data stored in localStorage for your domain.</p><h3>Common localStorage Methods</h3><p>The localStorage API provides six main methods, with these being the most frequently used:</p><ol><li>setItem(key, value) - Stores a value with the specified key</li><li>getItem(key) - Retrieves the value associated with the key</li><li>removeItem(key) - Removes the item with the specified key</li><li>clear() - Removes all items from localStorage</li><li>key(index) - Returns the name of the key at the specified position</li><li>length - Returns the number of items in localStorage</li></ol><h3>Using localStorage with useEffect in React/Next.js</h3><p>When working with localStorage in React components, it’s often best to use it within useEffect hooks:</p><pre>&#39;use client&#39;<br>import { useEffect, useState } from &#39;react&#39;;<br><br>export default function UserProfile() {<br>  const [user, setUser] = useState(null);<br>  <br>  // Load user data from localStorage on component mount<br>  useEffect(() =&gt; {<br>    const savedUser = localStorage.getItem(&#39;user&#39;);<br>    if (savedUser) {<br>      setUser(JSON.parse(savedUser));<br>    }<br>  }, []);<br>  <br>  // Save user data to localStorage whenever it changes<br>  useEffect(() =&gt; {<br>    if (user) {<br>      localStorage.setItem(&#39;user&#39;, JSON.stringify(user));<br>    }<br>  }, [user]);<br>  <br>  // Component cleanup - remove data if needed<br>  useEffect(() =&gt; {<br>    return () =&gt; {<br>      // Optional: Clean up when component unmounts<br>      // localStorage.removeItem(&#39;user&#39;);<br>    };<br>  }, []);<br>  <br>  // Rest of the component...<br>}</pre><p>Using useEffect ensures that localStorage operations happen at the right time in the component lifecycle and only run in the browser environment.</p><h3>Inspecting localStorage in the Browser</h3><p>All data stored in localStorage can be viewed and inspected in the browser’s developer tools:</p><ol><li>Open your browser’s developer tools (F12 or right-click and select “Inspect”)</li><li>Navigate to the “Application” tab</li><li>In the left sidebar, under “Storage”, expand “Local Storage”</li><li>Click on your website’s domain</li></ol><p>Here you can see all key-value pairs stored in localStorage for your application. This is extremely useful for debugging and verifying that your caching implementation is working as expected.</p><h3>A Real-World Use Case</h3><p>I was recently working on an onboarding flow that required the user to first submit their date of birth (to verify they’re above 18), email (to check uniqueness and avoid duplicates), and name. Specifically, we had to call a <em>validate email</em> endpoint before allowing the user to proceed to the next step — which was username and password submission.</p><p>At that point, I had a choice: use a state management library like Redux or Zustand, or go with something simpler. Since the user data needed to persist across steps and be submitted all at once, I decided to store it in localStorage. After the final submission, I simply cleared the cached data.</p><p>Sure, Redux and Zustand support persistence with a bit of setup — but in this case, localStorage was the most straightforward option. No extra boilerplate, no overengineering. Just what I needed to get the job done without breaking a sweat.</p><h3>Advanced Caching with Apollo Client</h3><p>Moving beyond the basics of localStorage caching, we’ll now explore caching in the context of data fetching with Apollo Client for GraphQL applications. We’ll focus on the caching mechanisms rather than the setup process.</p><h3>Understanding Apollo Client’s In-Memory Cache</h3><p>Apollo Client includes a sophisticated in-memory caching system. Unlike localStorage, which persists data across browser sessions, Apollo’s in-memory cache:</p><ul><li>Stores data directly in the browser’s memory (RAM)</li><li>Automatically caches query results without additional code</li><li>Normalizes data by extracting objects and storing them separately by ID</li><li>Is cleared when the user refreshes the page or closes the browser</li></ul><p>TanStack Query (formerly React Query) follows a similar approach with its own in-memory caching system.</p><h3>Fetching Data with Apollo Client</h3><p>Retrieving data on the client side with Apollo is quite simple. Let’s use this example to briefly discuss caching too. Once users log in, I use Apollo Client to fetch their data — a process that’s easy and intuitive.</p><p>I’ve already set up my Next.js application to use Apollo Client. I won’t go deep into the intricacies of this setup in this article, so we’ll dive straight into data fetching, which is quite simple and straightforward:</p><pre>const { data: loggedInUser } = useQuery(GET_LOGGEDIN_USER);</pre><p>You might be tempted to check localStorage to see if the data is cached, but it doesn’t live there. It resides in your RAM, and you can access this in two ways:</p><ol><li>Use the Apollo Client DevTools browser extension</li><li>Use the useApolloClient() hook(programically)</li></ol><p>Now you can begin to see your data is indeed cached, and you can retrieve it anywhere in your app — I’ll prove that in a bit.</p><h3>Retrieving Cached Data in Apollo Client</h3><p>As previously noted, Apollo Client provides a powerful in-memory cache that allows you to store and retrieve GraphQL data efficiently. Sometimes, you may want to access this cached data directly, without triggering a network request — for example, to check if a user is already logged in or to read previously fetched data. Let’s explore how to do just that using the useApolloClient hook.</p><h4>Accessing the Apollo Client Instance</h4><p>The first step is to get access to the Apollo Client instance itself. This can be done using the useApolloClient hook:</p><pre>&quot;use client&quot;;<br>import { useApolloClient } from &quot;@apollo/client&quot;;<br><br>export default function ApolloClientTest() {<br>  const client = useApolloClient();<br>  console.log(client); // Logs all methods and properties available on the Apollo Client<br>  <br>  return &lt;div&gt;Test&lt;/div&gt;;<br>}</pre><p>When you log the client, you&#39;ll see an object full of useful methods such as readQuery, writeQuery, readFragment, and more. These give you fine-grained control over your cache.</p><p>To read cached data, simply use the readQuery method and provide the same GraphQL query that was used to fetch the data:</p><pre>const GET_LOGGEDIN_USER = gql`<br>  query GetLoggedInUser {<br>    getLoggedInUser {<br>      user {<br>        id<br>        username<br>        email<br>        image<br>      }<br>    }<br>  }<br>`;</pre><pre>export default function ApolloClientTest() {<br>  const client = useApolloClient();<br>  <br>  console.log(<br>    client.readQuery({<br>      query: GET_LOGGEDIN_USER,<br>    })<br>  );<br>  <br>  return &lt;div&gt;Test&lt;/div&gt;;<br>}</pre><p>If the result of GET_LOGGEDIN_USER is already in the cache, it will be returned instantly, without any network call. If it&#39;s not in the cache, readQuery will return null.</p><h3>Is client.readQuery() Like localStorage.getItem()?</h3><p>You can loosely think of client.readQuery() as similar to localStorage.getItem() — both retrieve client-side data. However, Apollo&#39;s cache is much more structured and integrated with your app&#39;s data layer.</p><p>So while the concept of “retrieving client-side data” is shared, Apollo’s readQuery is a lot more specialized and powerful in the context of data-driven UIs.</p><h3>Conclusion</h3><p>Accessing the Apollo Client cache directly with readQuery can be incredibly useful when you want to work with already-fetched data or manage your own logic without hitting the server. It&#39;s quick, efficient, and tightly integrated with your GraphQL schema.</p><p>In forth-coming articles, we’ll explore how to take this further by performing <strong>optimistic UI updates</strong>, using this same caching system to enhance user experience by updating the UI before the server confirms changes.</p><p>Stay tuned! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cf8b676cf6a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/understanding-caching-in-frontend-development-4cf8b676cf6a">Understanding Caching in Frontend Development</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Authentication with Auth.js]]></title>
            <link>https://javascript.plainenglish.io/implementing-authentication-with-auth-js-c4bcde1f9ebc?source=rss-ccb9dee6e319------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4bcde1f9ebc</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[nextauthjs]]></category>
            <category><![CDATA[apollo-server]]></category>
            <category><![CDATA[authjs]]></category>
            <dc:creator><![CDATA[Mbaocha Jonathan]]></dc:creator>
            <pubDate>Tue, 10 Dec 2024 15:41:12 GMT</pubDate>
            <atom:updated>2024-12-17T11:43:00.491Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementing Authentication with Auth.js v5: Recieving session from a react app in an express server</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CW2Z0lba9YJ7jLZE20PIfQ.png" /></figure><p>Implementing authentication can be a daunting task. While Auth.js v5 simplifies much of this process, integrating it with an Express server and passing sessions from a React app can be challenging at first. In this guide, I’ll walk you through the exact steps I took to make this work, sparing you the days of trial and error I experienced.</p><h4><strong>Implementing Authentication in Apollo Server with Auth.js</strong></h4><p>Setting up authentication in Apollo Server using Auth.js was a challenging yet rewarding experience that took me nearly a week to figure out. I’m writing this article to streamline the process for you and provide a clear, step-by-step guide. While the focus will remain on the core topic, let’s start with a quick overview to set the stage.</p><p>For this guide, I assume you already have your client set up — most likely a Next.js application — and have configured Auth.js as outlined in its documentation. Kudos to the Auth.js team for making the setup process intuitive and user-friendly. Additionally, you should have your adapters configured to serve as a bridge between NextAuth.js and your database. By now, I hope it’s clear that we’ll be using the server strategy for session management.</p><p>Since this article is dedicated to the server-side implementation, I won’t delve into the frontend setup. However, if you encounter issues on that front, feel free to leave a comment — I’d be happy to assist!</p><p>Now, let’s dive into the exciting part: implementing authentication in Apollo Server.</p><h4>Getting Started</h4><p>The project I’m working on is a GraphQL server built with Apollo Server. To keep this article focused and concise, I won’t dive into the details of setting up an Apollo Server. Doing so would not only make this piece longer but also stray from the main topic. If you need guidance on that, the <a href="https://www.apollographql.com/docs/apollo-server/getting-started">Apollo Server documentation</a> is an excellent resource to get you started.</p><p>For the purpose of this guide, I’ll assume you already have your Express server up and running. With that foundation in place, let’s gear up and dive right in.</p><p>I wouldn’t call the Auth.js installation guide entirely intuitive, especially since it required extra effort on my part to figure out how to set up authentication on an Express server. Or perhaps, I was just less experienced five days ago. Either way, here’s how my journey unfolded.</p><p>I started with the <a href="https://authjs.dev/getting-started/installation?framework=Express">Getting Started guide</a> on the Auth.js <a href="https://authjs.dev/getting-started/installation?framework=Express">documentation</a>, right under the section titled “Start by installing the appropriate package for your framework.” Since I was using Express, I followed the recommendation and installed the package using:</p><pre>pnpm add @auth/express</pre><p>use whichever package manager you are comfortable with.</p><p>Next, I copied the .env variables from my client configuration. It’s crucial that these variables match exactly across the client and server environments. For example, you’ll need variables like AUTH_GOOGLE_ID, AUTH_SECRET, and AUTH_SECRETE to be consistent. This alignment ensures seamless communication between your client and server.</p><h3>Simplifying the Setup</h3><p>To keep this article as straightforward as possible, I’ll skip my initial thought process — you’re here to implement authentication, not follow my learning curve. Let’s focus on what works: the key package you need to configure authentication is @auth/express.</p><pre>pnpm add @auth/express</pre><h4>Step 1: Create the auth.ts File</h4><p>Start by creating an auth.ts file that exports your authentication configuration. This file can live in your src directory. Here’s what the code looks like :</p><pre>import Google from &quot;@auth/express/providers/google&quot;;<br><br>// Authentication configuration<br>export const authConfig = {<br>  trustHost: true,<br>  providers: [Google],<br>};</pre><p>You can add as many providers as you want, but for now, we’ll stick to the Google provider. If u noticed, unlike before no need to pass the client id and secrete. I think the v5 does this behind the hood so you need to make sure your variables in the .env file is defined as recommended by the <a href="https://authjs.dev/getting-started/providers/google">auth.dev docs</a>. For example, setting up with google provider, the recommended variable is:</p><pre>AUTH_GOOGLE_ID<br>AUTH_GOOGLE_SECRET</pre><h4>Step 2: Configure Auth Middleware</h4><p>Next, set up the middleware to handle authentication. This file can live in the directory where other middlewares live. or you can create a middleware directory inside your src folder and create a file auth.middleware.ts Here’s the current implementation:</p><pre><br>import { getSession } from &quot;@auth/express&quot;;<br>import { authConfig } from &quot;../config/auth.config.js&quot;;<br>import type { NextFunction, Request, Response } from &quot;express&quot;;<br>// Middleware to check for an authenticated user<br>export async function authenticatedUser(<br> req: Request,<br> res: Response,<br> next: NextFunction<br>) {<br> const session =<br> res.locals.session ?? (await getSession(req, authConfig)) ?? undefined;<br>res.locals.session = session;<br>if (session) {<br> return next();<br> }<br>res.status(401).json({ message: &quot;Not Authenticated&quot; });<br>}<br>// Middleware to get the current session<br>export async function currentSession(<br> req: Request,<br> res: Response,<br> next: NextFunction<br>) {<br> const session = (await getSession(req, authConfig)) ?? undefined;<br> res.locals.session = session;<br> return next();<br>}</pre><p><strong>Note:</strong> TypeScript may complain about the res.locals.session property, as it’s not defined by default in the Response type. Let’s address that next.</p><h4>Step 3: Extend TypeScript Definitions</h4><p>To make TypeScript happy, extend the Response type to include the locals.session property. Create an index.d.ts file in your types directory and add the following:</p><pre>declare namespace Express {<br>  interface Response {<br>    locals: {<br>      session?: any;<br>    };<br>  }<br>}</pre><p>Now TypeScript is content, and your middleware is almost ready for use.</p><h4>Step 4: Integrate Middleware Into Your Server</h4><p>Finally, integrate the middleware into your server. If your server entry point is index.ts, add the middleware there.</p><h4>Current Server Setup</h4><p>If you are like me, working with apollo server then your server will probably look like this:</p><pre>import express from &quot;express&quot;;<br>import http from &quot;http&quot;;<br>import { ApolloServer } from &quot;@apollo/server&quot;;<br>import { ApolloServerPluginDrainHttpServer } from &quot;@apollo/server/plugin/drainHttpServer&quot;;<br>import cors from &quot;cors&quot;;<br>import { expressMiddleware } from &quot;@apollo/server/express4&quot;;<br>import { currentSession } from &quot;./middleware/auth&quot;;<br>import { authConfig } from &quot;./config/auth.config.js&quot;;<br>import ExpressAuth from &quot;@auth/express&quot;;<br><br>interface MyContext {<br>  token?: string;<br>}<br><br>const corsOptions = {<br>  // origin: process.env.BASE_URL,<br>  // credentials: true,<br>};<br><br>const app = express();<br>const httpServer = http.createServer(app);<br><br>// Set session in res.locals<br>app.use(currentSession);<br><br>// Set up ExpressAuth to handle authentication<br>// IMPORTANT: It is highly encouraged to set up rate limiting on this route<br>app.use(&quot;/api/auth/*&quot;, ExpressAuth(authConfig));<br><br>const server = new ApolloServer&lt;MyContext&gt;({<br>  typeDefs,<br>  resolvers,<br>  csrfPrevention: true,<br>  plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],<br>});<br><br>await server.start();<br><br>app.use(<br>  &quot;/graphql&quot;,<br>  cors&lt;cors.CorsRequest&gt;(corsOptions),<br>  express.json(),<br>  expressMiddleware(server, {<br>    context: async ({ req, res }) =&gt; {<br>      const session = res.locals.session;<br><br>      console.log(&quot;SESSION:&quot;, res.locals);<br>      console.log(&quot;Cookies:&quot;, req.headers.cookie);<br><br>      return { token: req.headers.token };<br>    },<br>  })<br>);<br><br>await new Promise&lt;void&gt;((resolve) =&gt;<br>  httpServer.listen({ port: 4000 }, resolve)<br>);<br><br>console.log(`🚀 Server ready at http://localhost:4000/graphql`);</pre><p>Our server is not yet ready to recieve credentials unless we:</p><ol><li><strong>CORS Configuration:</strong> If you send a request without properly configuring the CORS options (as intentionally commented out in my code), the session data won’t be passed to the server. Make sure to configure your corsOptions correctly, including setting the origin and enabling credentials. This is critical to avoid issues with sessions being undefined.</li><li><strong>Session Configuration:</strong> Even after fixing CORS, you might notice that res.locals.session logs as undefined. If you inspect the request, the error message may mention JWT—even though we’re not using JWT in our frontend. The solution? Configure your session middleware to explicitly use the <strong>database</strong> as its strategy instead of JWT. Once this change is made, your sessions will start working as expected.</li></ol><h3>Final Middleware Code</h3><p>Here’s the final implementation of the middleware to handle authentication and session management. This version incorporates the necessary adjustments to ensure proper session handling with a database strategy.</p><h4>Authentication Middleware</h4><p>This middleware checks whether a user is authenticated. If a session exists, the request proceeds; otherwise, it returns a 401 Unauthorized response.</p><pre>// @ts-nocheck<br>import { getSession } from &quot;@auth/express&quot;;<br>import { authConfig } from &quot;../config/auth.js&quot;;<br>import type { NextFunction, Request, Response } from &quot;express&quot;;<br><br>// Middleware to check authentication<br>export async function authenticatedUser(<br>  req: Request,<br>  res: Response,<br>  next: NextFunction<br>) {<br>  const session =<br>    res.locals.session ?? (await getSession(req, authConfig)) ?? undefined;<br><br>  res.locals.session = session;<br><br>  if (session) {<br>    return next();<br>  }<br><br>  res.status(401).json({ message: &quot;Not Authenticated&quot; });<br>}</pre><h4>Current Session Middleware</h4><p>This middleware fetches the current session and configures it to use the database as the session strategy. It also allows optional session expiration via maxAge.</p><pre>import { DrizzleAdapter } from &quot;@auth/drizzle-adapter&quot;;<br>import { db } from &quot;../db/index.js&quot;;<br><br>const maxAge = 300; // Session expiration time (in seconds)<br><br>export async function currentSession(<br>  req: Request,<br>  res: Response,<br>  next: NextFunction<br>) {<br>  const session =<br>    (await getSession(req, {<br>      ...authConfig, // Spread existing authConfig to retain base settings<br>      session: {<br>        strategy: &quot;database&quot;, // Use database strategy for sessions<br>        maxAge, // Optional session expiration<br>      },<br>      adapter: DrizzleAdapter(db), // Required for database strategy<br>    })) ?? undefined;<br><br>  res.locals.session = session; // Store session in res.locals for later access<br>  return next();<br>}</pre><p>That’s all for now and thanks for reading.</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li><li>Have a story to share? <a href="https://formulatools.co/f/cJh1CStlo9jJmhIegBM9"><strong>Join our global community of writers today!</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4bcde1f9ebc" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/implementing-authentication-with-auth-js-c4bcde1f9ebc">Implementing Authentication with Auth.js</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering GraphQL Development: A Comprehensive Guide to Building Robust Servers with TypeScript…]]></title>
            <link>https://medium.com/@mbaochajonathan/mastering-graphql-development-a-comprehensive-guide-to-building-robust-servers-with-typescript-32da0ab76c17?source=rss-ccb9dee6e319------2</link>
            <guid isPermaLink="false">https://medium.com/p/32da0ab76c17</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mbaocha Jonathan]]></dc:creator>
            <pubDate>Thu, 30 Nov 2023 19:58:40 GMT</pubDate>
            <atom:updated>2023-12-01T12:25:47.106Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering GraphQL Development: A Comprehensive Guide to Building Robust Servers with TypeScript, Apollo Server, and Nodemon</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JhtQYEMoFESZBkQBHv0Ccg.png" /><figcaption>Apollo server sandbox</figcaption></figure><p>Setting up a project for success begins with a solid foundation. Building a server in Node.jst, leveraging TypeScript and Apollo Server can significantly enhance the development experience.</p><p>This article aim is to guide you through the initial steps to kickstart a project that combines the power of TypeScript and Apollo Server.</p><h3>Project Initialization and Setup</h3><p>To get started, navigate to your desired project directory and initiate Node.js by running the following command:</p><pre>npm init -y<br></pre><p>This quick setup generates a `package.json` file with default values, saving you from the hassle of manual configuration.</p><h3>TypeScript and @types/node Installation</h3><p>Now, let&#39;s bring TypeScript into the mix. Execute the following commands in your terminal (whether you&#39;re using VSCode or CMD):</p><pre>npm install --save-dev typescript @types/node<br></pre><h4>What Are These Packages?</h4><p>— <strong>TypeScript (`typescript`):</strong> TypeScript is a superset of JavaScript that introduces static typing. This means you can catch potential errors during development and enjoy improved code quality. Installing TypeScript ensures that your project embraces type safety.</p><p>— <strong>Types/Node (`@types/node`)</strong>: While TypeScript empowers JavaScript with types, it needs to understand the shapes of objects and functions in the Node.js environment. `@types/node` provides TypeScript with the necessary type definitions, making your code Node.js-friendly.</p><p>By installing these packages as dev dependencies, you keep your production environment lightweight while enjoying the benefits of robust development tools. This sets the stage for a successful journey into building a GraphQL server with Apollo Server, combining the strengths of TypeScript and Apollo to create a development experience that is both enjoyable and efficient.</p><h3>TypeScript Compiler Configuration</h3><p>Now that TypeScript is part of your project, let&#39;s configure it to align with your development preferences. Run the following command:</p><pre>npx tsc --init --module commonjs --rootDir ./src --outDir ./build<br></pre><p>This initializes a `tsconfig.json` with the the following configurations:</p><pre>{<br><br>  &quot;compilerOptions&quot;: {<br><br>    &quot;module&quot;: &quot;commonjs&quot;,<br><br>    &quot;rootDir&quot;: &quot;./src&quot;,<br><br>    &quot;outDir&quot;: &quot;./build&quot;,<br><br>    // ... other configurations<br><br>  },<br><br>  // ... other configurations<br><br>}<br><br><br></pre><p>These configurations specify that your project will use the CommonJS module system, your source code resides in the `src` directory, and the compiled JavaScript will be output to the `build` directory.</p><p>Configuring TypeScript with `tsconfig.json` is important because Node.js inherently understands JavaScript, not TypeScript. TypeScript is a superset of JavaScript that introduces static typing, which means it needs to be transpiled or compiled into JavaScript for Node.js to execute it.</p><p>By configuring TypeScript, you&#39;re providing instructions on how to transpile your TypeScript code into JavaScript. This includes specifying the module system, setting the root directory of your source code, and defining the output directory for the compiled JavaScript files. In the context of Node.js, using the CommonJS module system is a common choice.</p><p>Without this configuration, Node.js would not be able to interpret your TypeScript code directly. The compilation step ensures that your TypeScript code is transformed into JavaScript, making it compatible with Node.js and allowing your application to run successfully.</p><h3>Create Your First TypeScript File</h3><p>Now, create a `src` folder in your project directory. Inside it, add your first TypeScript file, `index.ts`, with the following content:</p><pre>// src/index.ts<br><br>console.log(&quot;Hello, World!&quot;);<br></pre><h3>Compilation ts to js</h3><p>Execute the following command to compile your TypeScript code:</p><pre>npx tsc<br></pre><p>This command takes your TypeScript files, compiles them, and outputs the JavaScript into the specified `outDir` (in this case, the `build` folder).</p><p>With this setup, you&#39;ve laid the groundwork for a structured TypeScript project. Running `npx tsc` will compile your TypeScript code, making it ready for execution.</p><h3>Nodemon: Enhancing Your Development Workflow.</h3><p><strong>Nodemon</strong> is a utility that monitors for changes in your source code and automatically restarts your server. This is particularly useful during development, as it saves you the hassle of manually stopping and restarting your server every time you make a change.</p><h3>Installation</h3><p>Let’s integrate Nodemon into your project:</p><pre>npm install --save-dev nodemon ts-node<br></pre><h3>Customizing Nodemon Configuration.</h3><p>Create a `nodemon.json` file in the root directory of your app with the following configurations:</p><pre><br><br>{<br>  &quot;watch&quot;: [&quot;src&quot;],<br><br>  &quot;ext&quot;: &quot;.ts,.js&quot;,<br><br>  &quot;ignore&quot;: [],<br><br>  &quot;exec&quot;: &quot;ts-node ./src/index.ts&quot;<br><br>}<br><br></pre><p>These configurations specify that Nodemon should watch the `src` directory for changes in files with the extensions `.ts` and `.js`. The `exec` property defines the command to execute when changes are detected.</p><h3>Updating package.json</h3><p>Now, let’s add scripts to your `package.json` file:</p><pre>&quot;scripts&quot;: {<br><br>  &quot;build&quot;: &quot;tsc&quot;,<br><br>  &quot;dev&quot;: &quot;nodemon&quot;<br><br>}<br></pre><p>The `&quot;build&quot;` script runs the TypeScript compiler (`tsc`), and the `&quot;dev&quot;` script uses Nodemon to monitor your codebase. Nodemon will read the configuration from the `nodemon.json` file, automatically restarting your server when changes occur.</p><h3>Running the Development Environment</h3><p>Execute the following command in your terminal:</p><pre>npm run dev<br></pre><p>Now, Nodemon will keep an eye on your codebase. Whenever you make changes, it will automatically restart the server, streamlining your development workflow.</p><h3>Introducing Apollo Server to the Mix</h3><p>Moving forward, consulting the Apollo Server documentation for building your GraphQL server is the recommended path. Honestly, I’m adhering to the provided code snippet without alterations. Feel free to explore the details in their documentation. Here’s the code snippet:</p><pre>import { ApolloServer } from &#39;@apollo/server&#39;;<br><br>import { expressMiddleware } from &#39;@apollo/server/express4&#39;;<br><br>import { ApolloServerPluginDrainHttpServer } from &#39;@apollo/server/plugin/drainHttpServer&#39;;<br><br>import { createServer } from &#39;http&#39;;<br><br>import express from &#39;express&#39;;<br><br>import { makeExecutableSchema } from &#39;@graphql-tools/schema&#39;;<br><br>import { WebSocketServer } from &#39;ws&#39;;<br><br>import { useServer } from &#39;graphql-ws/lib/use/ws&#39;;<br><br>import cors from &#39;cors&#39;;<br><br>import resolvers from &#39;./resolvers&#39;;<br><br>import typeDefs from &#39;./typeDefs&#39;;<br><br><br><br>async function main() {<br>// Create the schema, used by ApolloServer and the WebSocket server.<br><br>const schema = makeExecutableSchema({ typeDefs, resolvers });<br><br><br><br><br>// Create an Express app and HTTP server; WebSocket and ApolloServer will attach to this HTTP server.<br><br>const app = express();<br><br>const httpServer = createServer(app);<br><br><br><br><br>// Create our WebSocket server using the HTTP server.<br><br>const wsServer = new WebSocketServer({<br><br>  server: httpServer,<br><br>  path: &#39;/subscriptions&#39;,<br><br>});<br><br>// Save the returned server&#39;s info for future shutdown.<br><br>const serverCleanup = useServer({ schema }, wsServer);<br><br><br><br><br>// Set up ApolloServer.<br><br>const server = new ApolloServer({<br><br>  schema,<br><br>  plugins: [<br><br>    // Proper shutdown for the HTTP server.<br><br>    ApolloServerPluginDrainHttpServer({ httpServer }),<br><br><br><br><br>    // Proper shutdown for the WebSocket server.<br><br>    {<br><br>      async serverWillStart() {<br><br>        return {<br><br>          async drainServer() {<br><br>            await serverCleanup.dispose();<br><br>          },<br><br>        };<br><br>      },<br><br>    },<br><br>  ],<br><br>});<br><br><br><br><br>await server.start();<br><br>app.use(&#39;/graphql&#39;, cors&lt;cors.CorsRequest&gt;(), express.json(), expressMiddleware(server));<br><br><br><br><br>const PORT = 4000;<br><br>// Now that our HTTP server is set up, we can listen to it.<br><br>httpServer.listen(PORT, () =&gt; {<br><br>  console.log(`Server is now running on http://localhost:${PORT}/graphql`);<br><br>});<br><br>}<br><br>main().catch((err) =&gt; console.log(err));<br><br></pre><p>Our server is listening on Port 4000 (localhost:400/graphql). If you observe the console logging “`Server is now running on <a href="http://localhost:${PORT}/graphql`">http://localhost:${PORT}/graphql`</a>” in the terminal, you’re good and only means you have your schemas setup but if you haven’t, I will be giving a high-level overview of typeDefs and resolvers as I plan to dive into details in a forthcoming article. However lets briefly talk about context.</p><h3>Passing Contexts to Resolvers</h3><p>Contexts play a pivotal role in GraphQL resolvers, offering a convenient way to share functions and variables across various resolver functions. Let&#39;s explore how to implement and leverage contexts in your Apollo Server.</p><p>Assume we want to pass a key-value pair, &quot;hello: world,&quot; across all resolvers. The magic happens in the `applyMiddleware` function when setting up your Apollo Server:</p><pre><br>expressMiddleware(server, {<br><br>  context: async ({ req }) =&gt; {<br><br>    return { hello: &quot;world&quot; };<br><br>  },<br><br>});<br><br><br></pre><p>In this example, the context function receives an object containing the `req` (request) parameter. You can extract information from the request or perform asynchronous operations as needed. Whatever you return from this context function becomes accessible in all your resolvers.</p><p>While we won&#39;t dive deeply into resolvers here, this initial exposure to contexts provides a glimpse of the flexibility they bring to your GraphQL server. Stay tuned for the upcoming articles, where we&#39;ll delve further into resolvers and explore more advanced use cases.</p><p>Structuring Your GraphQL Server: A Glimpse into the Future<br>In preparation for future features, I have set up the apolloserver to allow subscriptions for real-time updates in the application. Below is how I love to structure my apollo server:</p><pre>src/<br>|-- schema/<br>|   |-- typeDefs/<br>|   |   |-- index.ts<br>|   |   |-- comment.ts<br>|   |-- resolvers/<br>|       |-- index.ts<br>|       |-- comment.ts<br>|-- index.ts<br><br></pre><p>The `index.ts` file in the src dir is where our server lives and thus serves as the entry point. While the index.ts in the resolvers and typeDefs folder is the entry point respectively.</p><h3>Type Definitions (typeDefs):</h3><p>The index.ts in our typeDefs folder looks like this:</p><pre>// src/schema/typeDefs/index.ts<br><br>const typeDefs = [];<br><br>export default typeDefs;<br><br></pre><p>Here, we’ve initiated an empty array to hold our type definitions. Import the typeDefs into your Apollo Server. Right now there are no typeDefs, so let’s write one quickly.</p><p>Create a comment.ts and for now, paste the code snippet below. We will dive deeper into typeDefs and resolvers in forthcoming article:</p><pre>// src/schema/typeDefs/comment.ts<br><br>import gql from &quot;graphql-tag&quot;,<br><br>const comments = gql`<br><br>  type Query {<br><br>    getComments: [Comment]<br><br>  }<br><br><br><br><br>  type Mutation {<br><br>    createComment(comment: String): String<br><br>  }<br><br>`;<br><br><br></pre><p>Ps: install graphql tag run the command npm i graphql-tag</p><p>Resolvers:</p><p>In the `schema` directory, create a `resolvers` folder. Similar to typeDefs, the entry point for your resolvers is the `index.ts` file.</p><pre>// src/schema/resolvers/index.ts<br>import merge from &quot;lodash.merge&quot;;<br><br>const resolvers = merge({});<br><br>export default resolvers;<br></pre><p>We&#39;re using `merge` from `lodash` to combine all resolvers that will be developed in future articles. The `merge` function takes an empty object and other objects to merge.</p><p>Example Resolver for Comments:</p><pre>// src/schema/resolvers/comment.ts<br>const comments = {<br>  Query: {<br>    getComments: () =&gt; {},<br>  },<br>  Mutation: {<br>    createComment: () =&gt; {},<br>  },<br>};<br><br>export default comments;<br></pre><p>Then import this into the index.ts file and modify this file like this:</p><pre>// src/schema/resolvers/index.ts<br>import merge from &quot;lodash.merge&quot;;<br>import comments from &quot;./comments&quot;;<br><br>const resolvers = merge({}, comments);<br><br>export default resolvers;<br></pre><p>To maintain simplicity and ensure your server works, we’ve provided basic resolver functions. Corresponding type definitions (`typeDefs`) for these resolvers are also created.</p><p>With these in place our server should work perfectly, head over localhost:400/graphql to access the Apollo server playground(sandbox).</p><p>Note that the Apollo Server Playground requires an internet connection for access because it’s a cloud-based service provided by Apollo GraphQL, and to use it, you need to connect to their servers. If you&#39;re working in an environment without internet access, you won&#39;t be able to use Apollo Server Studio.</p><p>Keep this structure and setup in mind for upcoming features involving subscriptions and a deeper dive into type definitions and resolvers in the next article.</p><p>In conclusion, this guide has laid out the foundational steps to elevate your GraphQL server using TypeScript and Apollo Server. From project initialization and TypeScript setup to integrating Nodemon for an efficient development workflow, you&#39;ve established a robust groundwork. The introduction of Apollo Server brings the power of GraphQL to the mix, emphasizing the significance of well-defined schemas.</p><p>As you look ahead, consider the suggested folder structure and examples for type definitions and resolvers. These insights provide a glimpse into structuring your GraphQL server for future features, including real-time updates through subscriptions. Armed with TypeScript, Apollo Server, and a thoughtful project structure, you&#39;re well-equipped to embark on a successful journey in building powerful and maintainable GraphQL servers. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32da0ab76c17" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>