<?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 Jagan Reddy on Medium]]></title>
        <description><![CDATA[Stories by Jagan Reddy on Medium]]></description>
        <link>https://medium.com/@jagan_reddy?source=rss-62681386e359------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CQPlxPdomiW3qxCMg1V1Lg.jpeg</url>
            <title>Stories by Jagan Reddy on Medium</title>
            <link>https://medium.com/@jagan_reddy?source=rss-62681386e359------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 09:32:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jagan_reddy/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[The Keyboard Shortcuts That Save the Most Time]]></title>
            <link>https://medium.com/@jagan_reddy/the-keyboard-shortcuts-that-save-the-most-time-6c97da105583?source=rss-62681386e359------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c97da105583</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[keyboard-shortcuts]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[text-editing]]></category>
            <category><![CDATA[text-navigation]]></category>
            <dc:creator><![CDATA[Jagan Reddy]]></dc:creator>
            <pubDate>Tue, 01 Sep 2026 16:12:00 GMT</pubDate>
            <atom:updated>2026-09-01T16:12:00.329Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A Keyboard with multi color glowing keys on desk." src="https://cdn-images-1.medium.com/max/1024/1*HMcBljagWuIU0z8KTdGd3g.jpeg" /></figure><blockquote><strong>In the age of AI</strong>, typing fast and moving through your screen without friction is still one of the <strong>most underrated productivity skills</strong> you can have. <strong>Keyboard shortcuts</strong> are a big part of that.</blockquote><h3>Why This Matters</h3><p><strong>For most of my life, I used a keyboard the way almost everyone does:</strong> hunting for arrow keys, reaching for the mouse, retyping things I could have just navigated to. I had never really sat down and learned the <strong>shortcuts my Mac </strong>already gave me.</p><p>Once I started using them, everything changed. <strong>Small pockets of time added up fast</strong>, and that time went straight back into the work I actually needed to do. <strong>My typing got smoother too</strong>. I stopped looking down at the keyboard nearly as often.</p><p>There is a simple reason for this. <strong>Shortcuts group your hand and finger movements </strong>into specific regions of the keyboard. <strong>Your brain starts to treat those regions as zones </strong>instead of individual keys, and that separation is what makes fast, fluid typing possible. <strong>My hands still drift out of their zone sometimes</strong>, but the more I’ve memorized where each shortcut lives, the less that happens.</p><blockquote>Here are the shortcuts that made the biggest difference for me.</blockquote><h3>Basic Navigation</h3><ul><li><strong>Cmd + Right Arrow</strong> — jump to the end of the current line</li><li><strong>Cmd + Left Arrow</strong> — jump to the beginning of the current line</li><li><strong>Cmd + Up Arrow</strong> — jump to the top of the document or text field</li><li><strong>Cmd + Down Arrow</strong> — jump to the bottom of the document or text field</li><li><strong>Option + Right Arrow</strong> — move right one word at a time</li><li><strong>Option + Left Arrow</strong> — move left one word at a time</li><li><strong>Control + Left Arrow</strong> — switch to the full-screen app to your left</li><li><strong>Control + Right Arrow</strong> — switch to the full-screen app to your right</li></ul><h3>App and Window Management</h3><ul><li><strong>Cmd + T</strong> — open a new tab (works in browsers, Finder, and Terminal)</li><li><strong>Cmd + W</strong> — close the current tab, or minimize/close the window in apps outside the browser</li><li><strong>Cmd + Q</strong> — quit an app entirely</li><li><strong>Cmd + Tab</strong> — switch between open apps</li><li><strong>Option + Up Arrow</strong> — show all open windows, then navigate between them with Option + the arrow keys</li></ul><h3>Advanced Combinations</h3><ul><li><strong>Cmd + Shift + Left Arrow</strong> — select text back to the beginning of the line</li><li><strong>Cmd + Shift + Right Arrow</strong> — select text forward to the end of the line</li><li><strong>Option + Shift + Left Arrow</strong> — select the word to the left</li><li><strong>Option + Shift + Right Arrow</strong> — select the word to the right</li><li><strong>Cmd + Shift + W</strong> — close an entire browser window</li></ul><h3>Why This Is Worth Learning:</h3><p>None of these shortcuts are complicated, and that’s exactly the point. <strong>You don’t need to be a developer or a “power user” to benefit from them</strong>. Anyone who <strong>writes emails, fills out forms, browses the web,</strong> <strong>or switches between a handful of apps</strong> during the day is doing the exact motions these shortcuts replace: reaching for the mouse, dragging to select text, clicking to close a tab, hunting for an app in the dock. <strong>Every one of those small manual actions costs a few seconds</strong>, and those seconds are <strong>happening dozens of times a day without you noticing.</strong></p><p>What surprised me most is how much this changes the feel of using a computer, not just the speed. Once your hands learn where these shortcuts live, you stop thinking about the mechanics of typing and navigating, and <strong>you stay focused on the actual task in front of you</strong>. It becomes <strong>muscle memory the same way touch typing does.</strong> For me, that’s translated into <strong>fewer interruptions, less mental context-switching,</strong> and a genuine sense that my hands and my thinking are working together instead of one waiting on the other.</p><blockquote>If you use a Mac every day, even for something as simple as writing or browsing, learning this short list is one of the highest-return habits you can build.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c97da105583" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a Secure Signup System (OTP + Attempt Limits)]]></title>
            <link>https://medium.com/@jagan_reddy/sentinel-secure-user-signup-in-fastapi-done-right-09f071d8c5d2?source=rss-62681386e359------2</link>
            <guid isPermaLink="false">https://medium.com/p/09f071d8c5d2</guid>
            <category><![CDATA[sqlalchemy]]></category>
            <category><![CDATA[user-authentication]]></category>
            <category><![CDATA[fastapi-pydantic]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Jagan Reddy]]></dc:creator>
            <pubDate>Sat, 21 Feb 2026 06:39:19 GMT</pubDate>
            <atom:updated>2026-09-02T21:55:51.484Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Sentinel Swagger Docs" src="https://cdn-images-1.medium.com/max/1024/1*1oRa-R8eCJpvhg-fMGdP6g.png" /></figure><blockquote>Every application needs <strong>authentication and authorization</strong>. Done right, it becomes <strong>invisible</strong>, <strong>reliable</strong>, and <strong>unbreakable</strong>.</blockquote><h3><strong>What’s Sentinel?</strong></h3><p>Sentinel is my attempt to build auth the right way from the ground up. It’s a <strong>FastAPI</strong>-based <strong>auth service</strong> built on <strong>PostgreSQL</strong> (<strong>Neon</strong>), <strong>async SQLAlchemy</strong>, and <strong>Pydantic v2.</strong> The goal isn’t just to make it work. It’s to make it secure, maintainable, and architecturally clean.</p><p>This article walks through the <strong>first piece: user signup.</strong> Every decision along the way, schema design, password hashing, token strategy, database writes, and the layer separation that holds it all together.</p><h3><strong>Architecture First:</strong></h3><p>Most auth bugs aren’t<strong> cryptographic mistakes</strong>. They tend to be <strong>structural ones: </strong>business <strong>logic creeping into route handlers</strong>, <strong>database calls scattered across the codebase</strong>, <strong>models that try to do too much.</strong> The code works, but it becomes impossible to test in isolation and painful to change without breaking something else.</p><h4>Sentinel follows a strict three-layer model:</h4><ul><li><strong>Route Handler</strong> : Handles <strong>HTTP</strong> only. Reads the request, calls the service, sets cookies, returns the response. No business logic here.</li><li><strong>Service Layer</strong> : Owns all the work. <strong>Builds models, hashes passwords, generates tokens, </strong>writes to the DB.</li><li><strong>Schema Layer</strong> : <strong>Validates and structures data</strong>. Request schemas validate incoming data. Internal schemas model DB records. Response schemas control what gets returned.</li></ul><blockquote>This means the service is fully testable without spinning up FastAPI. The route handler stays simple. Each layer can change without breaking the others.</blockquote><h4><strong>The Schema Problem</strong></h4><p>The most common early mistake in <strong>FastAPI</strong> projects is inheriting DB models from request schemas. It looks convenient:</p><pre># looks fine, but causes problems<br>class UserDBModel(UserSignUpRequest):<br>    id: str = ...<br>    created_at: int = ...</pre><p>The problem shows up fast. UserSignUpRequest has password as a required field. UserDBModel shouldn&#39;t store plain text passwords at all. So you either store them <strong>(terrible)</strong> or override as optional <strong>(a hack that papers over a design smell)</strong>.</p><p>It also means anything you add to the signup form like confirm_password, terms_accepted, referral_code silently bleeds into your DB model.</p><p>Sentinel solves this with a shared <strong>UserBase</strong>:</p><pre>class UserBase(BaseModel):<br>    email: EmailStr<br>    username: str<br>    first_name: str<br>    last_name: str<br>    phone_number: Optional[str] = None<br>    country_code: Optional[str] = None</pre><p>Then two separate schemas extend it independently:</p><pre>class UserSignUpRequest(UserBase):<br>    password: str        # validated for strength<br>    terms_accepted: bool # gate only, never stored</pre><pre>class UserDBModel(UserBase):<br>    id: str<br>    email_verified: bool = False<br>    is_active: bool = True<br>    is_locked: bool = False<br>    failed_login_count: int = 0<br>    created_at: int | None = None<br>    updated_at: int | None = None</pre><blockquote>Neither inherits from the other. Changes to the signup form don’t affect the DB model. Simple rule, saves a lot of pain later.</blockquote><h3><strong>Timestamps</strong></h3><p>Timestamps in Sentinel are stored as <strong>Unix integers</strong> rather than datetime strings or timezone-aware objects. This keeps things simple: <strong>no parsing, no timezone conversion, no formatting issues. </strong>An integer is just a number, and comparing two numbers is always unambiguous.</p><p>One thing worth noting: if you declare timestamps using two separate default_factory calls, they&#39;re evaluated independently and could technically differ. Sentinel avoids this by declaring now once in the service layer and passing it everywhere:</p><pre>now = int(utc_now().timestamp())<br># passed to UserDBModel, PasswordDBModel, and refresh token<br># every record in a signup shares the exact same timestamp</pre><blockquote>This also makes testing much easier since you can inject a fixed value and assert exact timestamps.</blockquote><h3>Why Passwords Get Their Own Table</h3><p>Passwords in Sentinel live in a separate passwords table, not alongside the user record. <strong>This is a pattern borrowed from enterprise authentication systems.</strong></p><p><strong>A few reasons this is worth the extra table:</strong></p><ul><li>Password rotation stays clean.</li><li>You can keep a previous_passwords list and prevent reuse without touching users at all.</li><li>A query fetching user profile data can never accidentally return password data.</li><li><em>password_changed_at</em> gives you a clear audit trail of credential rotations.</li><li>If you ever move to a different hashing algorithm, migration is isolated to one table.</li></ul><p>The user_id column has unique=True enforcing the one-to-one relationship at the DB level, not just in application code.</p><h3>Why Argon2id?</h3><p>Sentinel hashes passwords with <strong>Argon2id</strong>. Not bcrypt, not SHA-256 Because, Argon2id won the <strong>Password Hashing Competition in 2015</strong> and<strong> </strong>is the current<strong> OWASP recommendation</strong>.</p><p>The key advantage over<strong> bcrypt</strong> is that it’s <strong>memory-hard</strong>. To crack an <strong>Argon2id hash</strong>, an attacker needs significant memory per attempt, not just CPU cycles. This makes GPU-based brute force attacks dramatically more expensive.</p><h4><strong>A hashed password looks like:</strong></h4><pre> $argon2id$v=19$m=7168,t=5,p=1$&lt;salt&gt;$&lt;hash&gt;</pre><p>The format itself is self-describing. <strong>Algorithm, cost parameters, </strong>and<strong> salt</strong> are all embedded in the string. This is by design and it’s not a security concern. The<strong> salt prevents rainbow table attacks</strong>. The cost parameters need to be stored somewhere so verification knows how to rehash.<strong> None of it helps an attacker without the raw password.</strong></p><h3><strong>The Signup Service</strong></h3><p>The signup service is where everything comes together. A single now is declared at the top and passed to every model: the user record, the password record, and the refresh token all share the <strong>exact same timestamp</strong>. From there, the models are built in order, tokens are generated, and everything gets persisted inside a <strong>single database transaction</strong>.</p><pre>async def signup_user(user: UserSignUpRequest, db: AsyncSession) -&gt; SignupServiceResult:<br>    now = int(utc_now().timestamp())<br><br>    existing_result = await db.execute(<br>        select(UserModel).where(<br>            (UserModel.email == user.email) | (UserModel.username == user.username)<br>        )<br>    )<br>    if existing_result.scalar_one_or_none():<br>        raise HTTPException(<br>            status_code=status.HTTP_409_CONFLICT,<br>            detail=&quot;Email or username already exists&quot;,<br>        )<br><br>    # hash password<br>    hashed_password = hash_password(user.password)<br><br>    # build pydantic DB models<br>    user_in_db = UserDBModel.from_signup(user, now)<br>    password_in_db = PasswordDBModel.from_signup(user_in_db.id, hashed_password, now)<br><br>    # build ORM models<br>    user_orm = UserModel(**user_in_db.model_dump())<br>    password_orm = PasswordModel(**password_in_db.model_dump())<br><br>    # persist all in a single transaction<br>    try:<br>        db.add(user_orm)<br>        await db.flush()<br>        db.add(password_orm)<br>        await db.commit()<br>    except Exception:<br>        await db.rollback()<br>        raise HTTPException(<br>            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,<br>            detail=&quot;Failed to create user&quot;,<br>        )<br><br>    sent = await send_otp(user_in_db.id, user.email, db)<br>    if not sent:<br>        return SignupServiceResult(<br>            user_id=user_in_db.id,<br>            message=&quot;Account created but failed to send verification email. Please use resend.&quot;,<br>        )<br><br>    return SignupServiceResult(<br>        user_id=user_in_db.id,<br>        message=&quot;Verification code sent to your email&quot;,<br>    )</pre><p>The <strong>db.flush()</strong> after the user insert matters. <strong>SQLAlchemy</strong> <strong>doesn&#39;t guarantee insert order within a transaction</strong>. Without it, the <strong>password insert</strong> could run before the <strong>user</strong> <strong>insert and fail the foreign key constraint. Flushing </strong>sends the user <strong>INSERT immediately</strong> within the open transaction so the user exists when the FK is checked. Everything still commits or rolls back as one unit.</p><blockquote>The response is also built after the transaction succeeds. You don’t construct a success response for a write that might have failed.</blockquote><h3><strong>What the Client Gets</strong></h3><p><strong>Response body:</strong></p><pre>{<br>  &quot;user_id&quot;:&quot;4c5a65c6-0de9-4a20-8e66-7d428c1c1370&quot;,<br>  &quot;message&quot;:&quot;Verification code sent to your email&quot;<br>}  <br></pre><p>Notice what we send back in the response: only user_id and a message. We do not include any other fields because they aren’t required by the client. An API response should contain only what the frontend needs to proceed—nothing more. Fields such as is_locked, failed_login_count, hashed_password, and previous_passwords are internal security and system fields. They exist purely for backend logic, auditing, and protection, and therefore should never be exposed to the client.</p><blockquote>It&#39;s not a dump of the database record with a few fields removed, it&#39;s a separate model built with a specific purpose. This distinction matters more than it seems because as the application grows, new fields get added to the DB model regularly. Without a strict response model, sensitive data has a way of quietly showing up in API responses.</blockquote><h3>The Verification Service:</h3><p>The verification service ensures that user’s email addresses are authenticated securely and efficiently. It provides three core functionalities: sending OTPs, verifying emails, and resending OTPs when needed.</p><p>When a user signs up, the service generates a time-sensitive One-Time Password (OTP), hashes it for security, and stores it in the database. The OTP is then sent to the user’s email, providing a seamless verification experience. If the user enters the OTP, the service validates it against the hashed value, ensures it hasn’t expired, and checks for maximum retry attempts before marking the email as verified.</p><p>To enhance usability, the service also supports resending OTPs with a cooldown mechanism to prevent abuse. Each action is handled asynchronously, leveraging SQLAlchemy’s async session for database operations, and is wrapped with proper error handling to maintain data integrity and reliability.</p><p><strong>A sneek peek at the service, to get an idea on how it works:</strong></p><pre>async def send_otp(user_id: str, email: str, db: AsyncSession) -&gt; tuple[bool, str]:<br>    now = int(utc_now().timestamp())<br>    raw_otp = generate_otp()<br>    otp_hash = hash_otp(raw_otp)<br>    verification = EmailVerificationDBModel.from_signup(user_id, otp_hash, now)<br><br>    try:<br>        db.add(EmailVerificationModel(**verification.model_dump()))<br>        await db.commit()<br>    except Exception:<br>        await db.rollback()<br>        return False, &quot;Failed to save verification record&quot;<br><br>    try:<br>        sent = send_verification_email(email, raw_otp)<br>        if not sent:<br>            return False, &quot;Failed to send verification email&quot;<br>        return True, &quot;OTP sent successfully&quot;<br>    except Exception:<br>        return False, &quot;Catch all: Failed to send verification email&quot;</pre><h3>Token Strategy:</h3><p>Sentinel issues two tokens after email verification and each one serves a distinct purpose. The first is a <strong>JWT access token</strong>, short-lived token, returned in the response body so the client can attach it to subsequent requests. The second is a <strong>Refresh token</strong>, long-lived and configurable, used to get a new JWT when the current one expires.</p><h4>JWT (Access Token):</h4><ul><li>Short-lived, 5 minutes.</li><li>JWT is returned in the response body.</li><li>The client attaches it to subsequent requests as <strong>Authorization: Bearer &lt;token&gt;</strong>.</li><li>It contains the user ID as the sub claim so the client can decode it without making a separate API call.</li></ul><h4>Refresh Token (Long-lived):</h4><ul><li>Configurable via <strong>REFRESH_TOKEN_EXPIRE_DAYS</strong>Variable in .env</li><li>If we send Refresh Token in Request body, JavaScript can read it, which means XSS can steal it.</li><li>So, Sentinel sends it as an HttpOnly cookie instead:</li></ul><p><strong>Set-Cookie: refresh_token=&lt;raw&gt;; HttpOnly; Secure; SameSite=Strict</strong></p><p><strong>HttpOnly</strong> means JavaScript cannot access it at all. The browser sends it automatically on matching requests. An XSS attack can steal your JWT from localStorage but it cannot touch the refresh token.</p><blockquote>One more thing: the raw token goes in the cookie, the hashed version goes in the database. If your database is ever compromised, the stored hashes are useless without the raw values.</blockquote><h3>Conclusion:</h3><p><strong>Sentinel</strong> is still early. Only signup is done, but the foundation is solid, clean schema separation, Argon2id hashing, a proper token strategy, and atomic database writes. Every decision made here makes the next piece easier to build correctly.</p><p>Login is next. That’s where the interesting edge cases live: failed attempts, account lockouts, credential verification, and token issuance for an existing user. After that, refresh token rotation, revocation, and a /me endpoint.</p><blockquote>Authentication is one of those things that’s easy to get working and hard to get right. Sentinel is an attempt to do both.</blockquote><blockquote>GitHub: <a href="https://github.com/JaganReddy-dev/sentinel">https://github.com/JaganReddy-dev/sentinel</a></blockquote><blockquote><strong><em>If you found this useful, you might like the next article:</em></strong><em><br>→ </em><a href="https://medium.com/@jagan_reddy/the-keyboard-shortcuts-that-save-the-most-time-6c97da105583">The Keyboard Shortcuts That Save the Most Time</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09f071d8c5d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JWT in FastAPI, the Secure Way (Refresh Tokens Explained)]]></title>
            <link>https://medium.com/@jagan_reddy/jwt-in-fastapi-the-secure-way-refresh-tokens-explained-f7d2d17b1d17?source=rss-62681386e359------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7d2d17b1d17</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pydantic]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Jagan Reddy]]></dc:creator>
            <pubDate>Sun, 25 Jan 2026 03:20:00 GMT</pubDate>
            <atom:updated>2026-09-15T04:01:05.848Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="PyAuthUI connected to PyAuth Server" src="https://cdn-images-1.medium.com/max/1024/1*39gmG3qsDAgndt6sMpMPqQ.png" /></figure><h3>What’s PyAuth?</h3><blockquote><strong>PyAuth</strong> is a FastAPI-based authentication service providing JWT (JSON Web Token) and refresh-token management. Built for user identity and session management, it handles secure token generation, verification, rotation, and revocation.</blockquote><p>In PyAuth, each user (the JWT “sub” or subject) gets an access token (JWT) and a hashed refresh token. PyAuth’s core features include configurable JWT issuance and refresh-token system with hashing and revocation support.</p><p>A companion frontend, <strong>PyAuthUI</strong>, is a Next.js app that interacts with PyAuth’s API to demonstrate creating, verifying, refreshing, and revoking tokens. Together, they show a full-stack example, but the following guide focuses on using PyAuth itself as an auth microservice.</p><h3><strong>Key Features of PyAuth:</strong></h3><p>PyAuth exposes REST endpoints for token operations and relies on environment-configured secrets. It supports:</p><ul><li><strong>JWT Token Management:</strong> Create and verify JWTs with configurable expiration.</li><li><strong>Secure Refresh Tokens:</strong> Each refresh token is hashed (via Argon2) and stored with metadata (ID, user ID, timestamp, expiry, revoked flag).</li><li><strong>Token Verification &amp; Revocation:</strong> JWTs are validated (with proper error handling), and refresh tokens can be revoked or rotated.</li></ul><p>These features align with best practices: keeping JWTs short-lived and using rotating refresh tokens to limit risk.</p><h3>Setup and Configuration</h3><p>To run PyAuth, clone the repository and install its dependencies (FastAPI, PyJWT, python-dotenv, Uvicorn, etc.). Configure the required secrets in a .env file.</p><p><strong>For example:</strong></p><pre>SECRET=your-secret-key<br>ALGORITHM=HS256<br>REFRESH_TOKEN_SECRET=your-refresh-token-secret<br>REFRESH_TOKEN_EXPIRE_DAYS=30</pre><p>These environment variables define the JWT signing secret, algorithm, refresh-token hashing secret, and refresh-token lifetime (in days). After setting up, launch the FastAPI app <strong>(e.g. with Uvicorn):</strong></p><pre>uvicorn main:app --reload</pre><p>Now the PyAuth service will listen (by default) on http://localhost:8000, exposing API endpoints under /tokens.</p><h3>API Endpoints</h3><p>PyAuth provides four main token-related endpoints. Below is a brief overview of each, with example request/response payloads drawn from the documentation.</p><ul><li><strong>Create Tokens (</strong><strong>POST /tokens/create):</strong> Generate a new JWT and refresh token for a user. The request is a simple JSON with the subject (sub). For example:<br><strong>Endpoint</strong> <strong>:</strong>POST /tokens/create</li></ul><pre>{   &quot;sub&quot;: &quot;user123&quot; }</pre><ul><li>The response contains a JWT and a refresh-token object. The JWT includes fields like token, sub, iss (issuer), aud (audience), iat (issued-at), and exp (expiry). The refresh token response includes an id, user_id, the hashed token string, creation timestamp, expiry, and a revoked flag.<br>For instance, a successful response looks like:</li></ul><pre>{   &quot;jwt_token&quot;: <br>              {     &quot;token&quot;: &quot;eyJhbGci... (JWT here)&quot;,<br>                    &quot;sub&quot;: &quot;user123&quot;,     <br>                    &quot;iss&quot;: &quot;localhost&quot;,     <br>                    &quot;aud&quot;: &quot;user&quot;,     <br>                    &quot;iat&quot;: 1697056891,     <br>                     &quot;exp&quot;: 1697060491   <br>              },   <br>    &quot;refresh_token&quot;: <br>              {     &quot;id&quot;: &quot;uuid&quot;,     <br>                    &quot;user_id&quot;: &quot;user123&quot;,<br>                    &quot;token: &quot;64dfqbv....&quot;,     <br>                    &quot;hashed_token&quot;: &quot;hashed_string&quot;,     <br>                    &quot;created_at&quot;: 1697056891,     <br>                    &quot;expiry&quot;: 1699658891,     <br>                    &quot;revoked&quot;: false   <br>               } <br>}</pre><ul><li>This creates an access token (JWT) and a corresponding refresh token, stored safely on the server side is hashed refresh token and send the regular tokens to client.</li><li><strong>Verify Token (</strong><strong>POST /tokens/verify):</strong> Validate a JWT’s signature and expiry. Send the JWT in the body:<br><strong>Endpoint</strong> <strong>:</strong> POST /tokens/verify</li></ul><pre>{   &quot;token&quot;: &quot;eyJhbGci...&quot; }</pre><p>If the token is valid, the response returns its claims (e.g. sub, iss, aud). If invalid or expired, PyAuth returns a 401 Unauthorized error.</p><ul><li><strong>Refresh Tokens (</strong><strong>POST /tokens/refresh):</strong> Use an existing refresh token to get a new JWT and rotate the refresh token. The request body includes the full refresh-token object (as issued previously, including its id, user_id, and the refresh tokentoken).</li></ul><p>For example:</p><pre>{   &quot;id&quot;: &quot;uuid&quot;,   <br>    &quot;user_id&quot;: &quot;user123&quot;,   <br>    &quot;token&quot;: &quot;refresh_token_string&quot;,   <br>    &quot;created_at&quot;: 1697056891,   <br>    &quot;expiry&quot;: 1699658891,   <br>    &quot;revoked&quot;: false <br>}</pre><blockquote>The response returns a new JWT plus a new refresh-token object, and typically also marks the old refresh token as revoked. (In PyAuth, the key &quot;revoked&quot; indicates the previous token being invalidated.)</blockquote><ul><li><strong>Revoke Token :</strong> Revoke a given refresh token so it can no longer be used. Provide the refresh-token object in the body.</li></ul><p><strong>Endpoint:DELETE /tokens/revoke</strong></p><pre>{   &quot;id&quot;: &quot;uuid&quot;,   <br>    &quot;user_id&quot;: &quot;user123&quot;,   <br>    &quot;token&quot;: &quot;refresh_token_string&quot;,   <br>    &quot;created_at&quot;: 1697056891,   <br>    &quot;expiry&quot;: 1699658891,   <br>    &quot;revoked&quot;: false <br>}</pre><ul><li>The response is the same refresh-token object with &quot;revoked&quot;: true, indicating it’s invalidated.</li></ul><h3>Refresh Token Rotation (Best Practice):</h3><p>An important security practice is <strong>refresh token rotation</strong>: each time a refresh token is used, the server issues a brand-new refresh token and invalidates the old one. This means stolen or replayed refresh tokens lose their utility quickly.</p><blockquote><em>PyAuth’s refresh endpoint embodies this, when you call </em><em>/tokens/refresh, PyAuth will generate a new refresh token and revoke the previous one (as shown by the </em><em>&quot;revoked&quot; field in the response).This follows the OAuth-recommended approach. Each time a refresh token is used to acquire a new access token, a brand new refresh token is also generated and the previous one is invalidated.</em></blockquote><p>This rotation greatly reduces the risk window if a refresh token is compromised. For even stronger security, systems can also detect reuse of an already-rotated token (indicating token theft) and revoke all user tokens, but PyAuth’s core strategy is the one-time use rotation.</p><p><strong>PyAuth also checks token expiry on refresh:</strong> PyAuth performs validation to ensure an expired refresh token cannot be rotated, preventing reuse of stale tokens. This aligns with security best practices. In practice, always use HTTPS and store JWTs and refresh tokens securely on the client (e.g. HttpOnly cookies or secure storage) to complement PyAuth’s server-side protections.</p><h3>Integrating PyAuth (Setup &amp; Deployment)</h3><p>PyAuth is designed as a standalone service (a microservice) that can run independently. You can deploy it alongside your application stack: for example, run PyAuth on its own server or container, and have your frontend or backend call its /tokens endpoints to handle authentication. The provided <strong>PyAuthUI</strong> is a separate Next.js frontend that simply calls the PyAuth API. If you see the <strong>README</strong> of <strong>PyAuthUI</strong>, it clearly notes that <em>“This application requires the PyAuth backend to be running”</em>.</p><p>To integrate PyAuth:</p><ol><li><strong>Backend Setup:</strong> As I said above, run PyAuth (e.g. via uvicorn main:app). Ensure the required environment variables are set. For production, configure logging, host binding, and use a production server (like Gunicorn or Uvicorn with workers).</li><li><strong>Database (Optional):</strong> PyAuth doesn’t include a user database by default (it’s focused on token logic). You may integrate it with your own user store. The refresh tokens (and hashed values) could be stored in a database or in-memory store. If scaling beyond a single instance, ensure a shared storage for tokens.</li><li><strong>Frontend Integration:</strong> Point your app (or PyAuthUI) at PyAuth’s base URL. For example, PyAuthUI expects NEXT_PUBLIC_FASTAPI_BASE_URL (like http://localhost:8000) . Your own frontend or mobile app would similarly POST to the token endpoints.</li><li><strong>Deployment:</strong> Package PyAuth with Docker or host it on any cloud. Use HTTPS (configure an SSL certificate) for all calls. If deploying PyAuthUI (or other clients), ensure the environment’s API URL matches the deployed PyAuth.</li></ol><p>The <strong>PyAuthUI</strong> repository provides an example setup: cloning the UI, installing Node dependencies, and configuring NEXT_PUBLIC_FASTAPI_BASE_URL to point at the running PyAuth instance. For PyAuth itself, after installation one typically just runs the service. The README (linked from PyAuthUI) walks through the steps.</p><h3>Conclusion</h3><p>PyAuth abstracts the common JWT auth workflow into a reusable FastAPI service. By following security best practices short-lived JWTs, rotating refresh tokens, and secure hashing for tokens and passwords, it provides a solid foundation. Full-stack developers can deploy PyAuth as a dedicated microservice (as demonstrated by PyAuthUI) or incorporate its logic into larger apps. Always remember to use HTTPS and keep secrets out of code.</p><p>With PyAuth handling the heavy lifting of token logic, you can focus on your application’s business logic, confident that authentication is following modern best practices.</p><h3><strong>Note:</strong></h3><p>I’ve used <strong>“HS256”</strong> to make it easy for folks to understand, the ideal algorithm would be <strong>RS256</strong> (or <strong>ES256</strong>), an asymmetric signing scheme where PyAuth holds the <strong>private key to sign tokens</strong>, and any service that only needs to verify them holds just the public key. That way, <strong>a service that can check a token’s validity can’t also mint new ones</strong>, which matters once you have more than one verifier in the system.</p><p>And if someone wants to know more about <strong>how services can trust each other</strong>, like <strong>signed service-to-service tokens</strong> or <strong>mTLS</strong>, let me know and I can cover that in another article. Thanks!</p><blockquote><strong>GitHub:</strong><br><a href="https://github.com/JaganReddy-dev/PyAuth">https://github.com/JaganReddy-dev/PyAuth</a> <br><a href="https://github.com/JaganReddy-dev/PyAuthUI">https://github.com/JaganReddy-dev/PyAuthUI</a></blockquote><blockquote><strong>If you found this useful, you might like the next article:</strong><br>→ <a href="https://medium.com/@jagan_reddy/sentinel-secure-user-signup-in-fastapi-done-right-09f071d8c5d2">Designing a Secure Signup System (OTP + Attempt Limits)</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7d2d17b1d17" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Custom Analytics Tracker: Taking Back Control of Your Data]]></title>
            <link>https://javascript.plainenglish.io/building-a-custom-analytics-tracker-taking-back-control-of-your-data-0bfbf73beb2b?source=rss-62681386e359------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bfbf73beb2b</guid>
            <category><![CDATA[insights]]></category>
            <category><![CDATA[data-driven-decisions]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[user-metrics]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Jagan Reddy]]></dc:creator>
            <pubDate>Mon, 06 Oct 2025 21:34:53 GMT</pubDate>
            <atom:updated>2026-09-02T21:53:57.545Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DgHd3bC5mqJxSX7BERIqLw.png" /><figcaption>Analytics Data</figcaption></figure><h3><strong>Why Your Website Deserves Better Than Off-the-Shelf Analytics</strong></h3><p><strong>Picture this:</strong> You’ve just launched your <strong>website</strong>. Traffic is trickling in. You open <strong>Google Analytics</strong>, and… wait, what does any of this mean? Why are <strong>half your</strong> <strong>visitors</strong> showing up as <strong>“(not set)”?</strong> And why don’t you have the <strong><em>exact</em></strong> metric you need for your <strong>business</strong>?</p><p>Here’s the uncomfortable truth: <strong>you don’t own your analytics data</strong>. Those <strong>third-party tools? </strong>They’re <strong>sampling your traffic</strong>, imposing arbitrary limits, and making you conform to <em>their</em> idea of what matters.</p><p>What if you could track exactly what you care about? What if every click, scroll, and interaction was stored <strong><em>your way</em></strong>, in <strong><em>your database</em>?</strong></p><p><strong>That’s what we’re building in this series:</strong> <strong>a custom analytics tracker that puts you back in the driver’s seat.</strong></p><h3>Why Build Your Own? (Spoiler: It’s Not Just About Control)</h3><p><strong>🔒 Own Your Data, Own Your Destiny</strong><br> Third-party analytics platforms can change pricing, deprecate features, or even shut down. Your custom tracker? It’s yours forever. No vendor lock-in, no surprise bills.</p><p><strong>🕵️ Privacy-First by Design</strong><br> With <strong>GDPR, CCPA,</strong> and growing privacy concerns, respecting your users isn’t optional. It’s <strong>mandatory</strong>. Build <strong>privacy</strong> into your tracker from day one, collecting only what you need and being <strong>transparent</strong> about it.</p><p><strong>🎯 Track What Actually Matters</strong><br> Want to know how many <strong>users scroll past 75%</strong> of your pricing page? Or which <strong>CTA button</strong> performs better on mobile? Stop wrestling with custom event limitations. Just build the metrics you need.</p><p><strong>🚀 Learn Full-Stack Development the Right Way</strong><br> This isn’t a toy project. You’ll build a production-ready system involving:</p><ul><li><strong>RESTful APIs</strong> and <strong>data validation</strong></li><li><strong>Database schema design </strong>and <strong>optimization</strong></li><li><strong>Frontend</strong> <strong>tracking scripts</strong> and <strong>browser APIs</strong></li><li><strong>Event processing</strong> and <strong>real-time data ingestion</strong></li></ul><p>By the end, you’ll have a portfolio piece that actually impresses.</p><h3>The Anatomy of an Analytics System</h3><p>Before we write a single line of code, let’s understand what we’re building. Every analytics system has three core components:</p><h3>1. The Visitor → Who’s on your site right now?</h3><p>Could be a first-time visitor or a returning user. We’ll track them (anonymously if they prefer) across sessions.</p><h3>2. The Session → What are they doing during this visit?</h3><p>A session groups all the events from a single visit, from landing on your homepage to checking out or bouncing.</p><h3>3. The Event → What specific actions are they taking?</h3><p>Every <strong>click</strong>, <strong>scroll</strong>, <strong>form submission</strong>, <strong>video play</strong>. These are <strong>events</strong>. They’re the atomic units of behavior.</p><p><strong>The hierarchy looks like this:</strong></p><pre>Visitor<br>  └─ Session (Visit on Dec 5, 2025, 2:30pm)<br>      ├─ Event: Pageview → Homepage<br>      ├─ Event: Click → &quot;See Pricing&quot; button  <br>      ├─ Event: Scroll → 80% depth on Pricing page<br>      └─ Event: Exit</pre><p>Understanding this structure is crucial. It’s how we’ll organize our database and query our insights later.</p><h3>The Tech Stack: Modern, Practical, Battle-Tested</h3><p>We’re not chasing trends here. We’re using tools that scale and won’t make you pull your hair out. Everything is built with <strong>JavaScript/Node.js</strong> for a unified full-stack experience.</p><h3>Backend: Where the Magic Happens</h3><ul><li><strong>Node.js + Express</strong> → Fast, minimal, and perfect for APIs</li><li><strong>Prisma + PostgreSQL</strong> → Intuitive ORM meets robust relational database</li><li><strong>Zod + Zod-OpenAPI</strong> → Runtime validation with automatic API documentation</li><li><strong>Swagger UI Express</strong> → Interactive API documentation</li></ul><h3>Development Tools</h3><ul><li><strong>dotenv</strong> → Environment variable management</li><li><strong>Nodemon</strong> → Auto-restart server during development</li><li><strong>Terser</strong> → Minify and optimize production code</li></ul><h3>Frontend: Data Visibility</h3><ul><li><strong>React</strong> → Component-based architecture for building the tracker and dashboard</li><li><strong>TailwindCSS</strong> → Style your admin dashboard without writing a single CSS file</li></ul><h3>Infrastructure: Production-Ready from Day One</h3><ul><li><strong>Docker</strong> → Containerize everything for consistent environments</li><li><strong>Redis/Kafka</strong> → Queue and batch events when you scale to thousands of events per second</li><li><strong>AWS Free Tier</strong> → Deploy without breaking the bank</li><li><strong>Git + GitHub Actions</strong> → Version control and automated deployments</li></ul><h3>How It All Fits Together: The Big Picture</h3><p>Here’s the 30,000-foot view of what we’re building:</p><pre>┌─────────────────┐<br>│ Visitor Browser │<br>│   [Your Site]   │<br>└────────┬────────┘<br>         │<br>         ▼<br>┌─────────────────┐<br>│  Tracker.js     │  ← Collects events (clicks, scrolls, pageviews)<br>│  (React)        │<br>└────────┬────────┘<br>         │<br>         │ HTTP POST (or sendBeacon)<br>         │<br>         ▼<br>┌─────────────────┐<br>│  Express API    │  ← Validates, processes, stores<br>│  (Backend)      │<br>└────────┬────────┘<br>         │<br>         ▼<br>┌─────────────────┐<br>│  PostgreSQL DB  │  ← Stores Visitors, Sessions, Events<br>└─────────────────┘<br>         │<br>         ▼<br>┌─────────────────┐<br>│  Dashboard      │  ← Visualize insights (coming later)<br>│  (React)        │<br>└─────────────────┘</pre><p><strong>The Flow:</strong></p><ol><li>A visitor lands on your site</li><li>tracker.js fires, collecting pageview data (URL, referrer, screen size, etc.)</li><li>As they interact (click, scroll, etc.), more events are captured</li><li>Events are sent to your backend API using fetch() or navigator.sendBeacon()</li><li>The backend validates the data with Zod and stores it in PostgreSQL via Prisma</li><li>Later, you query this data to build dashboards, reports, or trigger automations</li></ol><h3>What You’ll Build in This Series</h3><p>This isn’t just theory. By the end of this series, you’ll have:</p><p>✅ A <strong>production-ready backend API</strong> that ingests and stores analytics events<br>✅ A <strong>React-based tracking component</strong> that works on any website<br>✅ A <strong>PostgreSQL database</strong> properly normalized for querying performance<br>✅ <strong>Privacy controls</strong> like IP anonymization and consent management<br>✅ A <strong>React dashboard</strong> to visualize your data<br>✅ <strong>Deployment on AWS</strong> using Docker and CI/CD pipelines</p><h3>Up Next: Building the Backend</h3><p>In <strong>Part 2</strong>, we’re diving straight into code. You’ll build:</p><ul><li>An Express server with RESTful endpoints and Swagger documentation</li><li>Prisma schemas for Visitor, Session, and Event tables</li><li>Input validation using <strong>Zod</strong> with <strong>OpenAPI</strong> integration</li><li>Development environment setup with <strong>dotenv</strong> and <strong>nodemon</strong></li><li>Your first <strong>API endpoint </strong>that accepts and stores a <strong>pageview </strong>event</li></ul><p>By the end of the next post, you’ll be able to send a test event from Postman and see it appear in your database. That’s when things get real.</p><h3>Ready to Take Control?</h3><p>Stop letting third-party analytics dictate what you can measure. Stop paying for features you don’t need. Stop worrying about data ownership and privacy compliance.</p><p><strong>Build your own tracker. Own your data. Learn full-stack development.</strong></p><p>Hit follow, and let’s build something remarkable together.</p><p><strong>Next in Series:</strong> <strong>[Part 2: Building the Backend API →]</strong></p><blockquote><em>Have questions or ideas? Drop them in the comments below. Let’s build this together.</em></blockquote><blockquote>I hope you found this guide to the Temporal API helpful! I love talking about modern JavaScript and web development. Feel free to reach out or see what else I’m working on.</blockquote><blockquote><em>Connect with me on </em><a href="https://www.linkedin.com/in/jaganspace/"><em>LinkedIn</em></a><em><br>Check out my projects on </em><a href="https://github.com/ParigiJ"><em>Github</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bfbf73beb2b" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/building-a-custom-analytics-tracker-taking-back-control-of-your-data-0bfbf73beb2b">Building a Custom Analytics Tracker: Taking Back Control of Your Data</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript’s Date is Broken. Here's Why Temporal is the Future.]]></title>
            <link>https://medium.com/@jagan_reddy/javascripts-date-is-broken-heres-why-temporal-is-the-future-a9f29cb9f89e?source=rss-62681386e359------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9f29cb9f89e</guid>
            <category><![CDATA[javascript-temporal-api]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[ecmascript]]></category>
            <dc:creator><![CDATA[Jagan Reddy]]></dc:creator>
            <pubDate>Wed, 06 Aug 2025 01:34:55 GMT</pubDate>
            <atom:updated>2026-03-15T04:12:08.697Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>An introduction to the new, modern API that fixes decades of date and time headaches in JavaScript.</strong></blockquote><figure><img alt="Javascript Temporal API is Here.PNG" src="https://cdn-images-1.medium.com/max/1024/1*29X70KcYj6Fm7hXXaPArFg.png" /></figure><p>If you’ve ever built a scheduler, handled international users, or calculated a subscription renewal, you’ve felt the pain. You write what looks like perfectly logical date-handling code, ship it, and then wake up to bug reports: “My appointment is showing on the wrong day!” or “I was billed a day early!”</p><p>The culprit, almost every time, is JavaScript’s built-in Date object.</p><p>Let’s be honest: the Date object is a relic from 1997, and it’s broken in ways that trip up even the most experienced developers. Let’s walk through why it’s so problematic and how the new <strong>Temporal API</strong> completely redefines how we work with time in JavaScript.</p><blockquote><strong>The Problems with </strong><strong>Date: The Walking Dead of APIs 🧟</strong></blockquote><p>JavaScript’s original Date API is a minefield of unexpected behaviors.</p><p><strong>It’s Mutable:</strong> Modifying a date object changes it in place. This is a huge source of bugs, as a change in one part of your code can unexpectedly affect another part that references the same object.</p><p><strong>Nightmarish Time Zone Handling:</strong> Date aggressively tries to work in the user&#39;s local time zone, often converting to and from UTC under the hood without you realizing it. This leads to constant off-by-one errors.</p><p><strong>Inconsistent Parsing:</strong> new Date(&quot;2025-01-01&quot;) can produce different results across browsers and environments. Some will parse it as UTC, others as local time. Yikes.</p><p><strong>One Size Fits None:</strong> You can’t represent a “date-only” (like a birthday) or a “time-only” value. Everything is a full, timezone-aware timestamp, even when you don’t want it to be.</p><p><strong>Unintuitive Arithmetic:</strong> Date math is notoriously weird. Just look at this classic example:</p><pre>// What happens when we set the month to 12 (the 13th month)?<br>const date = new Date(&quot;2025-01-01&quot;);<br>date.setMonth(12);<br><br>// You might expect an error or January 1st, 2026. Instead you get...<br>// 🤯 Feb 1, 2026 (in some environments)<br>console.log(date.toISOString()); // &quot;2026-02-01T00:00:00.000Z&quot;</pre><p>This kind of behavior is a recipe for subtle, production-grade bugs; especially in financial apps, booking systems, and anything timezone-sensitive.</p><h3>Enter Temporal: The Modern API We Deserve 🤩</h3><p>The new <strong>Temporal API</strong> (currently at TC39 Stage 3) fixes all of this. It doesn’t just patch Date; it introduces a suite of new, precise, and purpose-built objects for every date/time use case.</p><p>Here’s how Temporal changes the game.</p><h3>🔐 Immutability by Default</h3><p>Unlike Date, Temporal objects are <strong>immutable</strong>. Every operation returns a new instance, leaving the original untouched. This completely eliminates accidental side effects.</p><p>Here’s how Temporal changes the game:</p><pre>const d1 = Temporal.PlainDate.from(&quot;2025-08-01&quot;);<br>const d2 = d1.add({ days: 5 });<br><br>console.log(d1.toString()); // =&gt; &quot;2025-08-01&quot; (d1 is unchanged)<br>console.log(d2.toString()); // =&gt; &quot;2025-08-06&quot; (d2 is a new object)</pre><p>This is functional, predictable, and fundamentally safer.</p><h3><strong>🧠 Clearer Types for Clearer Intent</strong></h3><p>Temporal provides distinct classes for different concepts. No more overloading one bloated object for everything. You express exactly what you mean.</p><ul><li>Temporal.PlainDate — A calendar date without time or a timezone (e.g., &quot;December 25, 2025&quot;).</li><li>Temporal.PlainTime — A time of day without a date or timezone (e.g., &quot;13:45:30&quot;).</li><li>Temporal.PlainDateTime — A date and time, but still without a timezone.</li><li>Temporal.ZonedDateTime — A complete, timezone-aware timestamp (the most precise).</li><li>Temporal.Instant — A fixed point in universal time, independent of calendar or timezone (similar to a UNIX timestamp).</li><li>Temporal.Duration — A length of time (e.g., &quot;3 hours and 30 minutes&quot;).</li></ul><p>This clarity makes code self-documenting and eliminates ambiguity. Need to calculate the days between two dates?</p><blockquote><strong>The Old Way: </strong><strong>Date</strong></blockquote><p>To do this with the Date object, you have to get the timestamps in milliseconds, subtract them, and then manually calculate the number of days. It&#39;s messy and error-prone.</p><pre>// Before: Using the legacy Date object<br>const d1 = new Date(&#39;2025-08-01&#39;);<br>const d2 = new Date(&#39;2025-08-15&#39;);<br><br>const msDifference = d2.getTime() - d1.getTime();<br>const daysDifference = msDifference / (1000 * 60 * 60 * 24); // Manual calculation<br><br>console.log(daysDifference); // =&gt; 14</pre><blockquote><strong>The </strong><strong>TemporalWay:</strong></blockquote><p>With Temporal, this becomes a simple, readable, one-line operation that expresses your intent perfectly.</p><pre>// After: Using the modern Temporal API<br>const start = Temporal.PlainDate.from(&quot;2025-08-01&quot;);<br>const end = Temporal.PlainDate.from(&quot;2025-08-15&quot;);<br><br>const duration = end.since(start); // That&#39;s it!<br>console.log(duration.toString()); // =&gt; &quot;P14D&quot; (a 14-day duration)</pre><h3>🌍 Time Zones and Calendars That Actually Work</h3><p>Working with IANA time zones (America/New_York, Asia/Tokyo) used to require heavy third-party libraries like moment-timezone or luxon. With Temporal, it&#39;s built-in and trivial.</p><p>Let’s tackle a classic, real-world problem: converting a specific date and time from one time zone to another.</p><p><strong>Our Goal:</strong> Imagine an event is scheduled for <strong>9:18 AM on August 5, 2025, in Chicago</strong>. We need to show this time correctly to a user in <strong>Tokyo</strong>.</p><blockquote><strong>The Old Way: </strong><strong>Date</strong></blockquote><p>To accomplish this with the Date object, you can&#39;t simply set a time zone. You have to know the UTC offset for that date and time yourself (Chicago in August is UTC-5). Then, to &quot;convert&quot; it, you can only format it as a string for the target time zone; you can&#39;t create a new, workable Date object for that zone.</p><pre>// Before: Using the legacy Date object<br><br>// Create the date. You must manually provide the UTC offset<br>// to create the date reliably across systems.<br>const eventTime = new Date(&#39;2025-08-05T09:18:00-05:00&#39;);<br><br>// This shows the local time on the machine running the code, which may be confusing.<br>console.log(eventTime.toString());<br><br>// To &quot;convert&quot; to Tokyo time, you can&#39;t get a new Date object.<br>// You can only format the original date into a string for that locale.<br>const options = {<br>  timeZone: &#39;Asia/Tokyo&#39;,<br>  year: &#39;numeric&#39;, month: &#39;2-digit&#39;, day: &#39;2-digit&#39;,<br>  hour: &#39;2-digit&#39;, minute: &#39;2-digit&#39;, second: &#39;2-digit&#39;,<br>  hour12: false,<br>};<br><br>const inTokyo = new Intl.DateTimeFormat(&#39;en-US&#39;, options).format(eventTime);<br><br>console.log(inTokyo);<br>// =&gt; &quot;08/05/2025, 23:18:00&quot;</pre><blockquote><strong>The </strong><strong>Temporal Way:</strong></blockquote><p>You can now convert, shift, or compare across time zones, while retaining accuracy.</p><pre>const eventTime = Temporal.ZonedDateTime.from({<br>  timeZone: &quot;America/Chicago&quot;,<br>  year: 2025, month: 8, day: 5, hour: 9, minute: 18<br>});<br><br>console.log(eventTime.toString());<br>// =&gt; 2025-08-05T09:18:00-05:00[America/Chicago]<br><br>// Want to see what time that is in Tokyo?<br>const inTokyo = eventTime.withTimeZone(&quot;Asia/Tokyo&quot;);<br>console.log(inTokyo.toString());<br>// =&gt; 2025-08-05T23:18:00+09:00[Asia/Tokyo]</pre><p>It’s clean, declarative, and you always know what you’re working with.</p><h3>⚖️ Arithmetic That Respects Human Logic</h3><p>Remember how Date choked when adding months? Temporal&#39;s arithmetic is calendar-aware. It understands that months have different lengths, accounts for leap years, and handles daylight saving time transitions gracefully.</p><pre>const jan31 = Temporal.PlainDate.from(&quot;2025-01-31&quot;);<br><br>// Add one month. Temporal correctly lands on the last day of February.<br>const feb28 = jan31.add({ months: 1 });<br>console.log(feb28.toString()); // =&gt; &quot;2025-02-28&quot;<br><br>// Try that with `Date` and you get weird rollovers</pre><h3>📅 No More Weird Parsing</h3><p>Ever notice new Date(“2020–01–01”) behaves differently in some environments?</p><blockquote><strong>The Old Way: </strong><strong>Date</strong></blockquote><pre>const date = new Date(&#39;2020-01-01&#39;);</pre><p>This is a gamble. Depending on the user&#39;s browser and its JavaScript engine, this simple string can be interpreted in two different ways.</p><ul><li><strong>It might be treated as Local Time:</strong> Some engines will assume you mean midnight on January 1st in the <strong>user’s local time zone</strong>.</li><li><strong>It might be treated as UTC (Coordinated Universal Time):</strong> Other engines will follow the specification and assume you mean midnight on January 1st at <strong>UTC</strong>. For a user in New York (which is behind UTC), this date is actually <strong>December 31, 2019</strong>!</li></ul><blockquote><strong>The </strong><strong>Temporal Way:</strong></blockquote><p>With Temporal, there is no ambiguity. What you write is what you get.</p><pre>const date = Temporal.PlainDate.from(“2020–01–01”); <br>// Always valid, always consistent</pre><p>You can also safely parse ISO strings, add durations, format output; all without relying on moment, date-fns, or hacks.</p><h3>👇 So, How Can You Use It Today?</h3><p>This is the important part: <strong>Temporal is a TC39 Stage 3 proposal.</strong></p><p>This means the API design is stable and complete, but it is not yet an official part of the ECMAScript standard. It has not landed in all major browsers by default yet.</p><blockquote><strong>To use it today:</strong></blockquote><p><strong>In Production Web Apps (Recommended):</strong> <br>Use a polyfill. This library will provide the Temporal global object if the user&#39;s browser doesn&#39;t have it yet.</p><p>npm install @js-temporal/polyfill</p><p>Then import it at the top of your application’s entry point:<br>import { Temporal, ZonedDateTime } from &#39;@js-temporal/polyfill&#39;;</p><p><strong>In Node.js:</strong> <br>It is available behind a flag in recent versions (v18+).<br>node --harmony-temporal my-script.js</p><p><strong>In Deno:</strong> <br>Temporal is available out-of-the-box in recent versions.<br>Start experimenting with Temporal in your next project. Once you experience its clarity and power, you&#39;ll wonder how you ever managed with Date.</p><blockquote><em>I hope you found this guide to the Temporal API helpful! I love talking about modern JavaScript and web development. Feel free to reach out or see what else I’m working on.</em></blockquote><blockquote>Connect with me on <a href="https://www.linkedin.com/in/jagan368/">LinkedIn</a><br>Check out my projects on <a href="https://github.com/ParigiJ">Github</a></blockquote><blockquote><strong><em>If you found this useful, you might like the new article:</em></strong><em><br>→ </em><a href="https://medium.com/@jagan_reddy/sentinel-secure-user-signup-in-fastapi-done-right-09f071d8c5d2"><em>Designing a Secure Signup System (OTP + Attempt Limits)</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9f29cb9f89e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>