<?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 Natsuko on Medium]]></title>
        <description><![CDATA[Stories by Natsuko on Medium]]></description>
        <link>https://medium.com/@natsuko-dev-blog?source=rss-0b5502fff6f2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Natsuko on Medium</title>
            <link>https://medium.com/@natsuko-dev-blog?source=rss-0b5502fff6f2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 08:41:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@natsuko-dev-blog/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[SSRF and Link Preview: Why Your Server Must Never Blindly Fetch User-Supplied URLs]]></title>
            <link>https://medium.com/@natsuko-dev-blog/ssrf-and-link-preview-why-your-server-must-never-blindly-fetch-user-supplied-urls-e7285bc385d4?source=rss-0b5502fff6f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7285bc385d4</guid>
            <dc:creator><![CDATA[Natsuko]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 23:19:35 GMT</pubDate>
            <atom:updated>2026-11-02T23:19:35.803Z</atom:updated>
            <content:encoded><![CDATA[<h3>Table of Contents</h3><ol><li><a href="https://chatgpt.com/c/6ae91746-2150-83e8-b910-ba27dd9b6cac#1-introduction">Introduction</a></li><li><a href="https://chatgpt.com/c/6ae91746-2150-83e8-b910-ba27dd9b6cac#2-what-is-ssrf">What Is SSRF?</a></li><li><a href="https://chatgpt.com/c/6ae91746-2150-83e8-b910-ba27dd9b6cac#3-how-link-preview-becomes-an-ssrf-vector">How Link Preview Can Enable SSRF Attacks</a></li><li><a href="https://chatgpt.com/c/6ae91746-2150-83e8-b910-ba27dd9b6cac#4-understanding-ip-addresses-public-private-and-special-use">Understanding IP Addresses: Public, Private, and Special-Use</a></li><li><a href="https://chatgpt.com/c/6ae91746-2150-83e8-b910-ba27dd9b6cac#5-why-these-address-ranges-are-dangerous">Why These Address Ranges Are Dangerous</a></li><li><a href="https://chatgpt.com/c/6ae91746-2150-83e8-b910-ba27dd9b6cac#6-dns-how-domain-names-become-ip-addresses">DNS: How Domain Names Become IP Addresses</a></li><li><a href="https://chatgpt.com/c/6ae91746-2150-83e8-b910-ba27dd9b6cac#7-why-checking-the-domain-name-is-not-enough">Why Checking the Domain Name Is Not Enough</a></li><li><a href="https://chatgpt.com/c/6ae91746-2150-83e8-b910-ba27dd9b6cac#8-dns-rebinding-when-ip-checking-is-not-enough">DNS Rebinding: When IP Checking Is Not Enough</a></li><li><a href="https://chatgpt.com/c/6ae91746-2150-83e8-b910-ba27dd9b6cac#9-beyond-is_safe_url-building-a-safe-fetching-workflow">Beyond </a><a href="https://chatgpt.com/c/6ae91746-2150-83e8-b910-ba27dd9b6cac#9-beyond-is_safe_url-building-a-safe-fetching-workflow">is_safe_url: Building a Safe Fetching Workflow</a></li><li><a href="https://chatgpt.com/c/6ae91746-2150-83e8-b910-ba27dd9b6cac#10-conclusion">Conclusion</a></li></ol><h3>1. Introduction</h3><p>Link preview is a feature you see everywhere. Paste a URL into Slack, a social platform, or a messaging app, and a card appears showing the page’s <strong>title, description, and thumbnail image</strong>.</p><p>Building this feature seems straightforward:</p><ol><li>Take the URL the user provides.</li><li>Fetch the page on the server.</li><li>Parse its Open Graph metadata.</li><li>Return the preview.</li></ol><p>Simple.</p><p>But that simplicity hides a serious security risk.</p><p>When your server fetches a URL on behalf of a user, <strong>YOUR SERVER makes the network request</strong>. Your server may be able to reach resources the user cannot: internal APIs, admin tools, and cloud metadata endpoints.</p><p>An attacker can exploit that access by submitting a URL that points somewhere the server should never fetch on their behalf.</p><p>This class of attack is called <strong>SSRF: Server-Side Request Forgery</strong>.</p><blockquote><strong><em>KEY IDEA:</em></strong><em> A user-supplied URL controls where your server connects. That makes URL fetching a security boundary.</em></blockquote><p>This post explains what SSRF is, why link preview is a common entry point, which IP address ranges matter, and how to build a safer fetching workflow.</p><h3>2. What Is SSRF?</h3><p><strong>Server-Side Request Forgery</strong> is an attack in which someone tricks a server into making a request to a destination they choose.</p><p>That destination might be an internal service that cannot be reached directly from the public internet.</p><p>The crucial distinction is:</p><blockquote><strong><em>The request comes from the SERVER, not the user’s browser.</em></strong></blockquote><p>Servers often run inside private networks alongside databases, caches, internal APIs, and cloud infrastructure.</p><p>A user’s browser usually cannot reach those resources directly. The application server may be able to.</p><p>SSRF exploits that difference by turning the server into a proxy.</p><p><strong>The attacker supplies the destination. The server supplies the network access.</strong></p><h3>3. How Link Preview Can Enable SSRF Attacks</h3><h3>The normal flow</h3><p>A typical link preview request works like this:</p><p>StepAction1The user submits https://github.com to the link preview endpoint.2The server fetches the page.3The server extracts og:title, og:description, and og:image.4The user receives a preview card.</p><h3>The attack flow</h3><p>Now imagine the attacker submits this URL instead:</p><pre>http://169.254.169.254/latest/meta-data/iam/security-credentials/my-role</pre><p>Under certain AWS EC2 configurations, this points to an endpoint that returns temporary credentials for the instance’s IAM role.</p><p>StepAction1The attacker submits the metadata URL.2The server requests it from inside its own environment.3If metadata access is permitted, the endpoint returns credentials.4If the application exposes that response, the attacker receives them.</p><p><strong>Two conditions matter:</strong> the server must be able to retrieve the credentials, and the application must expose them to the attacker.</p><p>A link preview implementation that returns only selected HTML metadata will not necessarily reveal a JSON response. However, SSRF can still let an attacker probe internal services or trigger actions without seeing the response.</p><p>AWS also supports <strong>IMDSv2</strong>, which requires a session token. A simple URL-only GET request is insufficient when IMDSv2 is required.</p><blockquote><strong><em>TAKEAWAY:</em></strong><em> SSRF does not require a feature designed to access internal systems. A feature designed to fetch public pages can create that access accidentally.</em></blockquote><h3>4. Understanding IP Addresses: Public, Private, and Special-Use</h3><p>Before deciding whether a URL is safe to fetch, you need to understand where its IP address points.</p><h3>Public IP addresses</h3><p>Public IP addresses are intended for routing across the public internet.</p><p>When your server fetches a website, DNS translates its hostname into one or more IP addresses. The server then connects to one of those addresses.</p><p>However, <strong>publicly routable does not automatically mean reachable or trustworthy</strong>. Firewalls and other access controls still apply.</p><h3>Private and special-use IP addresses</h3><p>Some address ranges are reserved for private networks or special purposes.</p><p>These categories are related, but they are <strong>not interchangeable</strong>:</p><p>CategoryIPv4 rangeTypical purposePrivate10.0.0.0/8Corporate and cloud networksPrivate172.16.0.0/12Corporate and cloud networksPrivate192.168.0.0/16Home and office networksLoopback127.0.0.0/8The local host’s network environmentLink-local169.254.0.0/16Communication on the local link; also used for cloud metadata</p><p>The first three are the <strong>RFC 1918 private ranges</strong>. Loopback and link-local addresses belong to separate special-use categories.</p><p>Private addresses are not globally routable, but they <strong>can be routed within private networks</strong>, including between private subnets.</p><p>That is why a server may reach an internal address that an outside user cannot.</p><h3>Remember IPv6</h3><p>IPv4 filtering alone is insufficient if the server can also connect over IPv6.</p><p>Relevant examples include:</p><p>CategoryIPv6 address or rangeLoopback::1Unique localfc00::/7Link-localfe80::/10</p><p>These tables are an introduction, <strong>not a complete address-filtering policy</strong>. A production implementation must account for other special-use ranges and address representations.</p><h3>5. Why These Address Ranges Are Dangerous</h3><h3>A. 127.0.0.1: The server itself</h3><p>127.0.0.1 is a loopback address. From a server process, it points back to its own network environment.</p><p>For example:</p><pre>http://127.0.0.1:8080/admin</pre><p>This requests a service on port 8080 in that environment.</p><p>Some internal HTTP services listen only on localhost because they are intended to be accessible solely from the local system.</p><p><strong>SSRF can make those local services reachable through the application.</strong></p><p>For containerized applications, localhost usually refers to the container’s network namespace. The exact resources exposed depend on the deployment.</p><blockquote><strong><em>RISK:</em></strong><em> A service’s “localhost only” restriction does not protect it from another process that can be manipulated into making local requests.</em></blockquote><h3>B. Private addresses: The internal network</h3><p>In production, an application may share a private network with:</p><ul><li>Database servers</li><li>Cache servers</li><li>Internal admin dashboards</li><li>Other application services</li></ul><p>Some services rely heavily on network restrictions for protection.</p><p>An attacker who controls the server’s request destination may be able to probe internal HTTP endpoints, such as:</p><pre>http://10.0.0.15:8080/internal-status<br><br>http://192.168.1.20/admin/</pre><p>Even failed requests can reveal information through differences in response times or error messages.</p><p>A protocol detail matters here: <strong>an HTTP client cannot automatically communicate with every service it can reach</strong>. PostgreSQL and Redis, for example, use their own protocols. An HTTP request to a database port will not necessarily return a useful banner.</p><p>The central risk remains:</p><blockquote><strong><em>The application becomes a gateway into its own infrastructure.</em></strong></blockquote><h3>C. 169.254.169.254: Cloud instance metadata</h3><p>Cloud platforms commonly expose metadata services through addresses accessible from their compute environments.</p><p>On AWS EC2, the IPv4 metadata endpoint is:</p><pre>http://169.254.169.254/</pre><p>Depending on configuration, instance metadata can include:</p><ul><li>Instance identity and deployment information</li><li>The IAM role associated with the instance</li><li><strong>Temporary credentials for that role</strong></li></ul><p>An illustrative credentials response looks like this:</p><pre>{<br>  &quot;AccessKeyId&quot;: &quot;ASIA_EXAMPLE&quot;,<br>  &quot;SecretAccessKey&quot;: &quot;EXAMPLE_SECRET&quot;,<br>  &quot;Token&quot;: &quot;EXAMPLE_SESSION_TOKEN&quot;,<br>  &quot;Expiration&quot;: &quot;2026-11-03T12:00:00Z&quot;<br>}</pre><p>These values are placeholders.</p><p>If exposed, valid credentials may allow an attacker to perform AWS API operations within the role’s permissions and applicable restrictions. Temporary credentials include a <strong>session token</strong>, as well as an access key ID and secret access key.</p><p><strong>These are not credentials for every AWS account.</strong> They belong to the role associated with that instance.</p><p>The potential damage depends on that role’s permissions.</p><blockquote><strong><em>HIGH-VALUE TARGET:</em></strong><em> Metadata services can expose credentials. Their protection must include application controls, cloud configuration, and appropriately limited permissions.</em></blockquote><p>Other cloud providers have their own metadata behavior and request requirements. Do not assume every provider exposes credentials through an unrestricted GET request.</p><h3>6. DNS: How Domain Names Become IP Addresses</h3><p><strong>DNS — the Domain Name System — translates hostnames into IP addresses.</strong></p><p>For example, before fetching:</p><pre>https://github.com</pre><p>the server needs to determine which IP address to connect to.</p><p>Conceptually, it asks:</p><blockquote><em>“What IP addresses belong to </em><em>github.com?”</em></blockquote><p>The resolver returns one or more addresses, and the HTTP client establishes a connection.</p><p>In Python, socket.getaddrinfo() is one interface used to obtain address information for a hostname.</p><h3>DNS and CDNs</h3><p>A <strong>Content Delivery Network</strong>, or CDN, distributes content across multiple locations.</p><p>Some CDNs use DNS responses to help direct traffic toward suitable servers. Others also use mechanisms such as anycast routing.</p><p>As a result, the same hostname may resolve to different addresses depending on the resolver, location, configuration, or time.</p><p>LookupPossible resultA lookup associated with a user in JapanAn address serving traffic near JapanA lookup associated with a user in North AmericaA different address serving that regionA later lookupAn updated address after routing or infrastructure changes</p><p>These are simplified examples. DNS-based routing does not always identify the end user’s exact location.</p><p>For SSRF, the important point is:</p><blockquote><strong><em>A hostname is not a permanent guarantee of a particular destination IP.</em></strong></blockquote><h3>7. Why Checking the Domain Name Is Not Enough</h3><p>A basic defense might reject a few known destinations:</p><pre>localhost<br>169.254.169.254<br>internal.example.com</pre><p>That is insufficient.</p><p>An attacker can control a different hostname and configure it to resolve to a prohibited address.</p><p>For example:</p><ol><li>The attacker controls preview.attacker.example.</li><li>They configure its DNS record to return an internal IP.</li><li>They submit a URL using that hostname.</li><li>The server resolves the hostname and connects to the internal destination.</li></ol><p><strong>The hostname’s appearance tells you little about where the connection goes.</strong></p><p>Whether the target actually responds also depends on factors such as HTTP host handling and TLS. A hostname resolving to a metadata IP does not guarantee that an HTTPS request will succeed.</p><h3>Validate the destination</h3><p>A safer workflow begins with:</p><ol><li>Parse the URL.</li><li>Permit only supported schemes.</li><li>Extract and validate the hostname and port.</li><li>Resolve the hostname’s IPv4 and IPv6 addresses.</li><li>Apply the destination policy to every returned address.</li><li>Reject the request if any address is prohibited.</li></ol><p>OWASP recommends checking both IPv4 and IPv6 resolution results when validating destinations.</p><p>But validation alone leaves another problem: <strong>the address used during the check may differ from the address used during the connection.</strong></p><h3>8. DNS Rebinding: When IP Checking Is Not Enough</h3><p><strong>DNS rebinding</strong> can exploit the gap between checking a hostname and connecting to it.</p><p>Consider this sequence:</p><p>StageDNS answerResultSafety checkPublic IP addressValidation passesHTTP client resolves the hostname againInternal IP addressConnection reaches a prohibited destination</p><p>The attacker arranges for different lookups to receive different answers. Short DNS lifetimes can help, although resolver caching and behavior affect whether the attack succeeds.</p><h3>The defense: bind validation to the connection</h3><p>The server must connect to an address that <strong>actually passed validation</strong>.</p><p>Conceptually:</p><ol><li>Resolve the hostname.</li><li>Validate the returned addresses.</li><li>Select an approved address.</li><li>Make the connection using that address without an uncontrolled second lookup.</li></ol><p>For HTTPS, the client must still preserve the original hostname for <strong>TLS certificate verification and SNI</strong>. HTTP host handling must also remain correct.</p><p>Simply replacing the hostname with an IP address in the URL can break these requirements.</p><blockquote><strong><em>VALIDATE THE ADDRESS YOU CONNECT TO.</em></strong></blockquote><h3>Mixed DNS answers</h3><p>For a preview service restricted to public destinations, rejecting a hostname if <strong>any returned address is prohibited</strong> is a conservative policy.</p><p>However, mixed public and private answers do not, by themselves, prove an attack. Nor does rejecting mixed answers eliminate DNS rebinding: separate lookups can still return different results.</p><p><strong>Checking DNS results and controlling the actual connection are separate requirements.</strong></p><h3>9. Beyond is_safe_url: Building a Safe Fetching Workflow</h3><p>A function named is_safe_url() can perform useful validation.</p><p>However, <strong>a Boolean result cannot guarantee the safety of a later, independent fetch</strong>.</p><p>The validation, DNS resolution, connection, and redirect behavior need to work together.</p><h3>Destination and connection checks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*ZDjevNsggNKL7nOxKJEr6A.png" /></figure><h3>Redirects need their own protection</h3><p>A public URL can redirect to an internal destination.</p><p><strong>Validating only the first URL is insufficient.</strong></p><p>Disable automatic redirects, or explicitly handle them with the same validation and connection controls at every hop. OWASP recommends disabling automatic redirect following to prevent validation bypasses.</p><h3>Protect the rest of the fetching workflow</h3><p>SSRF controls should be accompanied by practical limits:</p><ul><li><strong>Timeouts:</strong> Limit connection time and total request time.</li><li><strong>Response limits:</strong> Bound download size and decompression.</li><li><strong>Content handling:</strong> Parse only the formats needed for previews.</li><li><strong>Credential isolation:</strong> Do not forward application cookies, authorization headers, or secrets.</li><li><strong>Network restrictions:</strong> Limit which destinations the preview service can reach.</li><li><strong>Cloud hardening:</strong> Require IMDSv2 where applicable and keep role permissions narrow.</li><li><strong>Safe rendering:</strong> Treat extracted titles, descriptions, and image URLs as untrusted content.</li></ul><p>If your server separately downloads an og:image URL, <strong>that fetch needs the same destination protections</strong>.</p><h3>The design principle: FAIL CLOSED</h3><p>If the destination cannot be verified, reject the request.</p><p>SituationDecisionDNS lookup failsRejectA resolved address is prohibitedRejectA redirect points to an unverified destinationRejectThe connection cannot be bound to an approved addressReject</p><blockquote><strong><em>Safety must be established before the request — and preserved throughout it.</em></strong></blockquote><h3>10. Conclusion</h3><p>Link preview turns a user-supplied URL into an outbound request from your infrastructure.</p><p>That creates a security boundary: the server may be able to reach destinations the user cannot.</p><p>A safer implementation must:</p><ol><li><strong>Validate the URL and its resolved destinations.</strong></li><li><strong>Cover IPv4, IPv6, and relevant special-use addresses.</strong></li><li><strong>Connect only to an address that passed validation.</strong></li><li><strong>Control redirects and secondary fetches.</strong></li><li><strong>Apply request limits and network restrictions.</strong></li><li><strong>Reject destinations that cannot be verified.</strong></li></ol><p><strong>The rule is simple: user input must never become unrestricted network access from your server.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7285bc385d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby on Rails + Hotwire]]></title>
            <link>https://medium.com/@natsuko-dev-blog/ruby-on-rails-hotwire-69e4417365f6?source=rss-0b5502fff6f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/69e4417365f6</guid>
            <dc:creator><![CDATA[Natsuko]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 23:57:59 GMT</pubDate>
            <atom:updated>2026-09-23T23:57:59.805Z</atom:updated>
            <content:encoded><![CDATA[<h4>Table of Contents</h4><h4>1. The Overall Flow: Route → Controller → Action → View</h4><h4>2. Routes</h4><h4>3. Controllers and Actions</h4><h4>4. Views</h4><h4>5. Hotwire</h4><h3>1. The Overall Flow: Route → Controller → Action → View</h3><h3>1.1 The Big Picture</h3><p>A Rails application can be understood through this basic flow:</p><pre>Browser<br>   │<br>   │ HTTP request<br>   │ e.g. GET /users<br>   ↓<br>config/routes.rb<br>   │<br>   │ GET /users → UsersController#index<br>   ↓<br>UsersController<br>   │<br>   │ index action<br>   ↓<br>app/views/users/index.html.erb<br>   │<br>   │ ERB generates HTML<br>   ↓<br>HTML sent to the browser</pre><p>The important roles are:</p><pre>Route<br>  ↓<br>decides which controller action handles the request<br><br>Controller<br>  ↓<br>receives the request and coordinates what should happen<br>Action<br>  ↓<br>a method inside the controller that handles a particular request<br>View<br>  ↓<br>generates the HTML that the browser receives</pre><p>A second relationship is important for understanding views:</p><pre>　　　　　　　　　　　　　　　config/routes.rb<br>                                │<br>                 ┌──────────────┴──────────────┐<br>                 ↓                             ↓<br>        Routes / URL mapping            Route helper methods<br>                 ↓                             ↓<br>        Controller#Action                     ERB<br>                 ↓                             ↓<br>               View                    Generated HTML</pre><p>So:</p><blockquote><em>routes.rb connects HTTP requests to controller actions.</em></blockquote><p>And:</p><blockquote><em>Rails conventions connect controller actions to views.</em></blockquote><p>Route helpers are generated from the routes and are commonly used inside ERB templates to generate URLs in the resulting HTML.</p><h3>1.2 URL vs. Route</h3><p>A <strong>URL path</strong> and a <strong>route</strong> are not the same thing.</p><p>For example:</p><pre>/users</pre><p>is a URL path.</p><p>It does not specify an HTTP method.</p><p>These are two different HTTP requests:</p><pre>GET  /users<br>POST /users</pre><p>They have the same URL path, /users, but they are <strong>different routes</strong> because they use different HTTP methods and map to different controller actions.</p><p>A useful definition is:</p><pre>Route<br>= HTTP method + URL pattern → Controller#Action</pre><p>For example:</p><pre>GET /users<br>    ↓<br>UsersController#index</pre><p>This mapping is defined in config/routes.rb.</p><p>Therefore:</p><pre>URL:<br>  /users<br><br>Route:<br>  GET /users → UsersController#index</pre><p>The URL is the address. The route is the rule that tells Rails what to do when a request arrives at that address using a particular HTTP method.</p><h3>1.3 Controller and Action</h3><p>A controller groups related request-handling logic.</p><p>For example:</p><pre>class UsersController &lt; ApplicationController<br>end</pre><p>is a controller for users.</p><p>An <strong>action</strong> is a method inside that controller:</p><pre>class UsersController &lt; ApplicationController<br>  def index<br>  end<br><br>def show<br>  end<br>end</pre><p>Here:</p><pre>UsersController<br>├── index action<br>└── show action</pre><p>A route can point to a particular action:</p><pre>GET /users<br>    ↓<br>UsersController#index</pre><p>The # notation means:</p><pre>Controller#Action</pre><p>So:</p><pre>UsersController#index</pre><p>means:</p><blockquote><em>the </em><em>index action of </em><em>UsersController.</em></blockquote><h3>1.4 How a Request Becomes HTML</h3><p>Consider:</p><pre>GET /users</pre><p>Rails processes it like this:</p><pre>GET /users<br>    ↓<br>routes.rb<br>    ↓<br>UsersController#index<br>    ↓<br>app/views/users/index.html.erb<br>    ↓<br>HTML<br>    ↓<br>Browser</pre><p>The route does <strong>not</strong> directly point to the ERB file.</p><p>The route points to:</p><pre>UsersController#index</pre><p>Then Rails follows its conventions to determine which view to render.</p><h3>2. Routes</h3><h3>2.1 config/routes.rb</h3><p>Rails routes are normally defined in:</p><pre>config/routes.rb</pre><p>For example:</p><pre>Rails.application.routes.draw do<br>  resources :users<br>end</pre><p>Rails.application.routes.draw do ... end is a Ruby block used to define the application&#39;s routes.</p><p>resources :users is a Rails routing DSL command that generates the conventional routes for the User resource.</p><h3>2.2 resources :users</h3><p>Instead of manually writing seven routes, Rails provides:</p><pre>resources :users</pre><p>This generates seven conventional routes:</p><pre>index<br>show<br>new<br>create<br>edit<br>update<br>destroy</pre><p>These names are conventional Rails terminology.</p><p>The complete mapping is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*4azLrtqEd39eMndH6bJQyw.png" /></figure><p>The <strong>action name</strong> and the <strong>route</strong> are different concepts.</p><p>For example:</p><pre>index</pre><p>is the conventional controller action name.</p><p>The corresponding route is:</p><pre>GET /users → UsersController#index</pre><h3>2.3 The Seven Conventional Routes</h3><p>The easiest way to understand the seven routes is to read them as instructions.</p><h3>INDEX</h3><pre>GET /users</pre><p>Meaning:</p><blockquote><em>“Show me all users.”</em></blockquote><p>It normally displays a list of users.</p><pre>GET /users<br>    ↓<br>UsersController#index<br>    ↓<br>app/views/users/index.html.erb</pre><p>Why index?</p><p>In programming and traditional lists/tables, an <strong>index</strong> is a listing or organized collection of items.</p><h3>SHOW</h3><pre>GET /users/123</pre><p>Meaning:</p><blockquote><em>“Show me User #123.”</em></blockquote><p>The 123 is the user&#39;s ID.</p><pre>GET /users/123<br>    ↓<br>UsersController#show</pre><p>show means that Rails should display one particular resource.</p><h3>NEW</h3><pre>GET /users/new</pre><p>Meaning:</p><blockquote><em>“Give me a form to create a new user.”</em></blockquote><p>This does <strong>not</strong> create a user.</p><p>It only displays the form.</p><pre>GET /users/new<br>    ↓<br>UsersController#new<br>    ↓<br>app/views/users/new.html.erb</pre><p>The fact that new uses GET is important.</p><p>GET is appropriate because the browser is simply asking:</p><blockquote><em>“Give me the page containing the form.”</em></blockquote><p>No database record needs to be created.</p><h3>CREATE</h3><pre>POST /users</pre><p>Meaning:</p><blockquote><em>“Create this new user.”</em></blockquote><p>This is the request that actually attempts to create the database record.</p><p>A typical flow is:</p><pre>User fills out new-user form<br>        ↓<br>POST /users<br>        ↓<br>UsersController#create<br>        ↓<br>User.new(...)<br>        ↓<br>@user.save<br>        ↓<br>database</pre><p>Notice that new and create are different:</p><pre>GET  /users/new<br>     = display the form<br><br>POST /users<br>     = process the submitted form and create the record</pre><h3>EDIT</h3><pre>GET /users/123/edit</pre><p>Meaning:</p><blockquote><em>“Give me a form to edit User #123.”</em></blockquote><p>Again, this does <strong>not</strong> modify the database.</p><p>It displays an editing form:</p><pre>GET /users/123/edit<br>    ↓<br>UsersController#edit<br>    ↓<br>app/views/users/edit.html.erb</pre><h3>UPDATE</h3><pre>PATCH /users/123</pre><p>Meaning:</p><blockquote><em>“Update User #123 with this data.”</em></blockquote><p>This is the request that actually attempts to modify the existing record.</p><p>So:</p><pre>GET /users/123/edit<br>    = display the edit form<br><br>PATCH /users/123<br>    = submit changes and update the record</pre><h3>DESTROY</h3><pre>DELETE /users/123</pre><p>Meaning:</p><blockquote><em>“Delete User #123.”</em></blockquote><p>This normally leads to:</p><pre>UsersController#destroy</pre><p>where the controller calls the model to delete the record.</p><h3>2.4 Understanding index, show, new, create, edit, update, and destroy</h3><p>The seven actions can be memorized as:</p><pre>index<br>&quot;Show me the collection.&quot;<br><br>show<br>&quot;Show me one existing resource.&quot;<br>new<br>&quot;Give me a form for creating a new resource.&quot;<br>create<br>&quot;Create the resource using this submitted data.&quot;<br>edit<br>&quot;Give me a form for editing an existing resource.&quot;<br>update<br>&quot;Update the existing resource using this submitted data.&quot;<br>destroy<br>&quot;Delete the existing resource.&quot;</pre><p>The most important pairs are:</p><pre>new    → show a creation form<br>create → actually create<br><br>edit   → show an editing form<br>update → actually update</pre><p>The form-displaying actions use GET because they are retrieving a page.</p><p>The actions that modify data use methods such as POST, PATCH, and DELETE.</p><h3>2.5 Route Helper Methods</h3><p>When Rails creates routes, it also generates <strong>route helper methods</strong>.</p><p>For example:</p><pre>users_path</pre><p>returns:</p><pre>/users</pre><p>and:</p><pre>user_path(@user)</pre><p>might return:</p><pre>/users/123</pre><p>Other examples:</p><pre>new_user_path<br># =&gt; /users/new<br><br>edit_user_path(@user)<br># =&gt; /users/123/edit</pre><p>These helper methods are commonly used in views, especially ERB templates.</p><p>For example:</p><pre>&lt;%= link_to &quot;Create a new user&quot;, new_user_path %&gt;</pre><p>Rails generates HTML equivalent to:</p><pre>&lt;a href=&quot;/users/new&quot;&gt;Create a new user&lt;/a&gt;</pre><p>The helper itself is Ruby code:</p><pre>new_user_path</pre><p>The result is a URL:</p><pre>/users/new</pre><p>The URL then becomes part of the generated HTML:</p><pre>&lt;a href=&quot;/users/new&quot;&gt;</pre><p>This gives us:</p><pre>Route helper<br>    ↓<br>URL<br>    ↓<br>HTML</pre><p>_path generates a relative path.</p><p>Rails also provides _url variants, such as:</p><pre>users_url</pre><p>which generates a full URL, such as:</p><pre>https://example.com/users</pre><h3>2.6 collection and member</h3><p>You can add custom routes to resources.</p><h3>collection</h3><pre>resources :users do<br>  collection do<br>    get :search<br>  end<br>end</pre><p>This means:</p><blockquote><em>Add a route related to the collection of users.</em></blockquote><p>Rails creates:</p><pre>GET /users/search<br>    ↓<br>UsersController#search</pre><p>and a helper:</p><pre>search_users_path</pre><p>which produces:</p><pre>/users/search</pre><p>There is no :id because the action applies to the collection rather than one particular user.</p><p>Think:</p><pre>collection<br>= the group as a whole</pre><h3>member</h3><pre>resources :users do<br>  member do<br>    get :profile<br>  end<br>end</pre><p>This means:</p><blockquote><em>Add a route related to one specific user.</em></blockquote><p>Rails creates:</p><pre>GET /users/:id/profile<br>    ↓<br>UsersController#profile</pre><p>For example:</p><pre>/users/123/profile</pre><p>The helper is:</p><pre>profile_user_path(@user)</pre><p>Think:</p><pre>member<br>= one specific resource</pre><p>The distinction is:</p><pre>collection<br>GET /users/search<br>     ↓<br>the collection of users<br><br>member<br>GET /users/123/profile<br>     ↓<br>one specific user</pre><h3>2.7 path:, only:, and except:</h3><h3>path:</h3><p>You can change the URL path while keeping the resource name and helper naming based on users.</p><pre>resources :users, path: &quot;members&quot;</pre><p>This produces URLs such as:</p><pre>/members<br>/members/123<br>/members/new</pre><p>but the helpers remain based on users, such as:</p><pre>users_path<br>user_path(@user)</pre><p>So the resource name and URL path do not have to be identical.</p><h3>only:</h3><p>Generate only the routes you need:</p><pre>resources :users, only: [:index, :show]</pre><p>This generates only:</p><pre>GET /users<br>GET /users/:id</pre><h3>except:</h3><p>Generate the resource routes except for specified actions:</p><pre>resources :users, except: [:destroy]</pre><p>This creates the standard routes other than destroy.</p><h3>3. Controllers and Actions</h3><h3>3.1 What Is a Controller?</h3><p>A controller handles HTTP requests and coordinates what the application should do.</p><p>For example:</p><pre>class UsersController &lt; ApplicationController<br>end</pre><p>A controller commonly:</p><ol><li>receives information from the request,</li><li>calls the model when data needs to be read or changed</li><li>chooses what response to return,</li><li>renders a view or redirects the browser.</li></ol><h3>3.2 What Is an Action?</h3><p>An action is a method inside a controller.</p><pre>class UsersController &lt; ApplicationController<br>  def index<br>  end<br><br>def show<br>  end<br>end</pre><p>Here:</p><pre>index<br>show</pre><p>are actions.</p><p>A route connects an incoming request to one of these actions:</p><pre>GET /users<br>    ↓<br>UsersController#index</pre><h3>3.3 The Seven Conventional Controller Actions</h3><p>A conventional UsersController might contain:</p><pre>class UsersController &lt; ApplicationController<br>  def index<br>  end<br><br>def show<br>  end<br>  def new<br>  end<br>  def create<br>  end<br>  def edit<br>  end<br>  def update<br>  end<br>  def destroy<br>  end<br>end</pre><p>These action names correspond to the seven routes generated by:</p><pre>resources :users</pre><p>The names are conventions, not arbitrary requirements.</p><p>Rails uses these conventions to make the relationship between routes, controllers, and views predictable.</p><h3>3.4 How Controller Actions Connect to Views</h3><p>Suppose we have:</p><pre>def index<br>end</pre><p>inside:</p><pre>UsersController</pre><p>Rails conventionally looks for:</p><pre>app/views/users/index.html.erb</pre><p>Similarly:</p><pre>UsersController#show<br>        ↓<br>app/views/users/show.html.erb<br><br>UsersController#new<br>        ↓<br>app/views/users/new.html.erb<br>UsersController#edit<br>        ↓<br>app/views/users/edit.html.erb</pre><p>The general convention is:</p><pre>Controller:<br>UsersController<br><br>↓<br>View directory:<br>app/views/users/<br>        ↓<br>Action:<br>index<br>        ↓<br>View:<br>index.html.erb</pre><p>This is why Rails knows to use index.html.erb.</p><p>The route does not directly say:</p><pre>&quot;render index.html.erb&quot;</pre><p>Instead:</p><pre>GET /users<br>    ↓<br>UsersController#index<br>    ↓<br>Rails convention<br>    ↓<br>app/views/users/index.html.erb</pre><p>This is an important Rails convention.</p><h3>3.5 new vs. create</h3><p>Consider:</p><pre>def new<br>  @user = User.new<br>end</pre><p>User.new creates a Ruby object in memory.</p><p>It does <strong>not</strong> save a database record.</p><p>The purpose of new is usually to prepare an object for the form:</p><pre>GET /users/new<br>    ↓<br>UsersController#new<br>    ↓<br>@user = User.new<br>    ↓<br>new.html.erb<br>    ↓<br>form</pre><p>Then the user submits the form:</p><pre>POST /users<br>    ↓<br>UsersController#create</pre><p>A typical create action is:</p><pre>def create<br>  @user = User.new(user_params)<br><br>if @user.save<br>    redirect_to @user<br>  else<br>    render :new<br>  end<br>end</pre><p>Line by line:</p><h3>@user = User.new(user_params)</h3><pre>User.new(...)</pre><p>creates a User object in memory.</p><p>It does not save it yet.</p><p>user_params supplies the permitted attributes.</p><h3>if @user.save</h3><pre>@user.save</pre><p>asks Active Record to save the object to the database.</p><p>It returns:</p><pre>true</pre><p>if the save succeeds, or:</p><pre>false</pre><p>if it fails, for example because model validations failed.</p><h3>redirect_to @user</h3><p>After successful creation:</p><pre>redirect_to @user</pre><p>tells the browser to navigate to that user’s page.</p><p>For a user with ID 123, this is approximately:</p><pre>redirect_to user_path(@user)</pre><p>which results in:</p><pre>/users/123</pre><p>The browser then makes another request:</p><pre>GET /users/123<br>    ↓<br>UsersController#show</pre><p>Therefore:</p><blockquote><em>redirect_to is HTTP/navigation behavior. It is not a database operation.</em></blockquote><h3>render :new</h3><p>If saving fails:</p><pre>render :new</pre><p>renders:</p><pre>app/views/users/new.html.erb</pre><p>in the current request.</p><p>It does <strong>not</strong> make another HTTP request.</p><p>The distinction is:</p><pre>render<br>= render a view now<br><br>redirect_to<br>= tell the browser to make another request</pre><h3>3.6 edit vs. update</h3><p>A typical edit action might be:</p><pre>def edit<br>  @user = User.find(params[:id])<br>end</pre><p>Its purpose is to retrieve the existing user and display an editing form.</p><p>The actual modification happens later:</p><pre>GET /users/123/edit<br>    ↓<br>UsersController#edit<br>    ↓<br>edit.html.erb<br>    ↓<br>user submits changes<br>    ↓<br>PATCH /users/123<br>    ↓<br>UsersController#update</pre><p>A typical update action is:</p><pre>def update<br>  @user = User.find(params[:id])<br><br>if @user.update(user_params)<br>    redirect_to @user<br>  else<br>    render :edit<br>  end<br>end</pre><h3>params[:id]</h3><p>For:</p><pre>/users/123</pre><p>Rails provides:</p><pre>params[:id]</pre><p>with the value:</p><pre>123</pre><h3>User.find(params[:id])</h3><p>This asks Active Record to find the existing database record.</p><h3>@user.update(user_params)</h3><p>This updates the existing record using the permitted parameters and attempts to save the changes to the database.</p><h3>redirect_to @user</h3><p>After success, the browser is redirected to the user’s show page.</p><h3>render :edit</h3><p>If validation fails, Rails renders the edit form again in the current request.</p><h3>3.7 render vs. redirect_to</h3><p>The distinction is fundamental:</p><pre>render</pre><p>means:</p><blockquote><em>Render a view as the response to the current request.</em></blockquote><pre>redirect_to</pre><p>means:</p><blockquote><em>Send a redirect response to the browser and tell it to make another request.</em></blockquote><p>For example:</p><pre>render :new</pre><p>does not cause:</p><pre>GET /users/new</pre><p>to happen again.</p><p>But:</p><pre>redirect_to @user</pre><p>causes the browser to make another request, typically:</p><pre>GET /users/123</pre><h3>3.8 Database Operations and Active Record</h3><p>In normal Rails code, the controller coordinates database operations, while the model/Active Record layer performs the actual persistence work.</p><p>For example:</p><pre>@user = User.find(params[:id])</pre><p>asks the User model/Active Record to retrieve a record.</p><pre>@user.save</pre><p>asks Active Record to save the object.</p><pre>@user.update(user_params)</pre><p>asks Active Record to update and save the record.</p><p>The controller is responsible for the request flow:</p><pre>HTTP request<br>    ↓<br>Controller<br>    ↓<br>Model / Active Record<br>    ↓<br>Database</pre><p>The controller normally does not manually write SQL.</p><h3>3.9 Strong Parameters: params, require, and permit</h3><p>A common controller method is:</p><pre>def user_params<br>  params.require(:user).permit(:name, :email)<br>end</pre><p>This is normally defined in the <strong>controller</strong>, not the model.</p><p>For example:</p><pre>class UsersController &lt; ApplicationController<br>  def create<br>    @user = User.new(user_params)<br><br>if @user.save<br>      redirect_to @user<br>    else<br>      render :new<br>    end<br>  end<br>  private<br>  def user_params<br>    params.require(:user).permit(:name, :email)<br>  end<br>end</pre><h3>What is params?</h3><p>params contains parameters supplied with the HTTP request.</p><p>Conceptually, a submitted form might produce:</p><pre>{<br>  user: {<br>    name: &quot;Alice&quot;,<br>    email: &quot;alice@example.com&quot;<br>  }<br>}</pre><p>Then:</p><pre>params</pre><p>contains that data.</p><h3>What does require(:user) do?</h3><pre>params.require(:user)</pre><p>means:</p><blockquote><em>Require a </em><em>user parameter to be present, and return that part of the parameters.</em></blockquote><p>Conceptually:</p><pre>params</pre><p>contains:</p><pre>{<br>  user: {<br>    name: &quot;Alice&quot;,<br>    email: &quot;alice@example.com&quot;<br>  }<br>}</pre><p>Then:</p><pre>params.require(:user)</pre><p>selects:</p><pre>{<br>  name: &quot;Alice&quot;,<br>  email: &quot;alice@example.com&quot;<br>}</pre><p>If the user parameter is missing, Rails raises an error.</p><h3>What does permit(:name, :email) do?</h3><pre>permit(:name, :email)</pre><p>means:</p><blockquote><em>Only allow </em><em>name and </em><em>email to be passed through as permitted parameters.</em></blockquote><p>For example, suppose someone submits:</p><pre>{<br>  user: {<br>    name: &quot;Alice&quot;,<br>    email: &quot;alice@example.com&quot;,<br>    admin: true<br>  }<br>}</pre><p>With:</p><pre>params.require(:user).permit(:name, :email)</pre><p>the permitted parameters contain only:</p><pre>{<br>  name: &quot;Alice&quot;,<br>  email: &quot;alice@example.com&quot;<br>}</pre><p>admin is not permitted.</p><p>This is the important security property of <strong>strong parameters</strong>.</p><p>The application explicitly defines which incoming attributes are allowed to reach the model.</p><p>The flow is:</p><pre>HTTP request<br>    ↓<br>params<br>    ↓<br>require(:user)<br>    ↓<br>select the user parameter<br>    ↓<br>permit(:name, :email)<br>    ↓<br>allow only specified attributes<br>    ↓<br>User.new(user_params)</pre><p>Without this filtering, blindly passing user-controlled parameters into a model could allow attributes that the application did not intend to be changed through that request.</p><p>The key line is:</p><pre>permit(:name, :email)</pre><p>because it creates the allowlist of permitted attributes.</p><h3>4. Views</h3><h3>4.1 What Is a View?</h3><p>A view is responsible for presenting application data as HTML.</p><p>Rails views are normally stored under:</p><pre>app/views/</pre><p>For UsersController, the conventional directory is:</p><pre>app/views/users/</pre><p>For example:</p><pre>app/views/users/index.html.erb<br>app/views/users/show.html.erb<br>app/views/users/new.html.erb<br>app/views/users/edit.html.erb</pre><h3>4.2 ERB</h3><p>ERB stands for <strong>Embedded Ruby</strong>.</p><p>An .html.erb file is primarily HTML, but it can contain Ruby code.</p><p>For example:</p><pre>&lt;h1&gt;Users&lt;/h1&gt;</pre><pre>&lt;% @users.each do |user| %&gt;<br>  &lt;p&gt;&lt;%= user.name %&gt;&lt;/p&gt;<br>&lt;% end %&gt;</pre><p>The Ruby code runs on the server and produces HTML.</p><p>Two important ERB forms are:</p><pre>&lt;%= ... %&gt;</pre><p>and:</p><pre>&lt;% ... %&gt;</pre><p>&lt;%= ... %&gt; evaluates Ruby and outputs the result into the HTML.</p><p>&lt;% ... %&gt; evaluates Ruby without directly outputting its return value.</p><h3>4.3 How Rails Finds index.html.erb</h3><p>Suppose the request is:</p><pre>GET /users</pre><p>The route maps it to:</p><pre>UsersController#index</pre><p>If the action does not explicitly render another view, Rails follows its convention and looks for:</p><pre>app/views/users/index.html.erb</pre><p>The mapping is:</p><pre>UsersController<br>      ↓<br>app/views/users/<br><br>index action<br>      ↓<br>index.html.erb<br>show action<br>      ↓<br>show.html.erb<br>new action<br>      ↓<br>new.html.erb<br>edit action<br>      ↓<br>edit.html.erb</pre><p>This is convention over configuration.</p><p>You do not normally need to write:</p><pre>render &quot;app/views/users/index.html.erb&quot;</pre><p>inside every index action.</p><p>Rails can infer the view from the controller and action names.</p><h3>4.4 Using Route Helpers in ERB</h3><p>Route helpers are particularly useful in views.</p><p>For example:</p><pre>&lt;%= link_to &quot;Users&quot;, users_path %&gt;</pre><p>Here:</p><pre>users_path</pre><p>is a Ruby method generated by Rails from the routes.</p><p>It returns:</p><pre>/users</pre><p>Then link_to uses that URL to generate HTML:</p><pre>&lt;a href=&quot;/users&quot;&gt;Users&lt;/a&gt;</pre><p>Another example:</p><pre>&lt;%= link_to &quot;Edit&quot;, edit_user_path(@user) %&gt;</pre><p>For User #123, the helper returns:</p><pre>/users/123/edit</pre><p>and Rails generates a link to that URL.</p><p>The important distinction is:</p><pre>users_path<br>= Ruby helper method<br><br>/users<br>= URL<br>&lt;a href=&quot;/users&quot;&gt;<br>= HTML</pre><h3>4.5 From ERB to HTML</h3><p>A simplified server-side flow is:</p><pre>Controller provides data<br>        ↓<br>ERB template uses the data<br>        ↓<br>Rails evaluates the Ruby<br>        ↓<br>HTML is generated<br>        ↓<br>Browser receives HTML</pre><p>For example:</p><pre>&lt;h1&gt;&lt;%= @user.name %&gt;&lt;/h1&gt;</pre><p>If:</p><pre>@user.name</pre><p>is &quot;Alice&quot;, the generated HTML is approximately:</p><pre>&lt;h1&gt;Alice&lt;/h1&gt;</pre><p>This is why ERB is useful: it allows server-side Ruby to generate dynamic HTML.</p><h3>5. Hotwire</h3><h3>5.1 What Is Hotwire?</h3><p><strong>Hotwire</strong> is a web development approach associated with 37signals and Rails.</p><p>It consists primarily of:</p><pre>Turbo<br>Stimulus</pre><p>The basic idea is to make web applications feel more dynamic while continuing to work heavily with HTML and server-side Rails.</p><h3>5.2 Turbo</h3><p>Turbo focuses on navigation and HTML updates.</p><p>Its major pieces are:</p><pre>Turbo Drive<br>Turbo Frames<br>Turbo Streams</pre><p>They solve different problems:</p><pre>Turbo Drive<br>→ page-level navigation<br><br>Turbo Frames<br>→ navigation/update within a specific region<br>Turbo Streams<br>→ specific DOM operations</pre><h3>5.3 Stimulus</h3><p>Stimulus is a JavaScript framework designed around attaching behavior to HTML.</p><p>A Stimulus controller can respond to browser events such as:</p><pre>click<br>input<br>submit<br>change</pre><p>For example, JavaScript behavior can be attached to an HTML element using Stimulus attributes.</p><p>The conceptual distinction is:</p><pre>Turbo<br>= navigation and HTML updates<br><br>Stimulus<br>= JavaScript behavior and interaction</pre><p>Turbo can often handle an interaction without writing custom JavaScript.</p><p>Stimulus is useful when the browser needs additional client-side behavior.</p><h3>5.4 Turbo Drive</h3><p>Turbo Drive handles normal page navigation.</p><p>Consider:</p><pre>&lt;%= link_to &quot;Users&quot;, users_path %&gt;</pre><p>The link still looks like an ordinary Rails link.</p><p>Turbo Drive intercepts the navigation, requests the new HTML, and updates the page without requiring the browser to perform a traditional full-page reload.</p><p>Conceptually:</p><pre>User clicks link<br>      ↓<br>GET /users<br>      ↓<br>Server returns HTML<br>      ↓<br>Turbo Drive updates the current document</pre><p>The application still uses normal Rails routes and controllers.</p><p>You generally do not need to write a special Turbo Drive tag for every link.</p><p>Turbo Drive is enabled by default when Turbo is installed.</p><p>It can be disabled for a particular element with:</p><pre>data-turbo=&quot;false&quot;</pre><h3>5.5 Turbo Frames</h3><p>Turbo Frames allow a specific region of a page to be updated independently.</p><p>For example:</p><pre>&lt;%= turbo_frame_tag &quot;user_2&quot; do %&gt;<br>  &lt;p&gt;Bob&lt;/p&gt;<br>  &lt;%= link_to &quot;Edit&quot;, edit_user_path(2) %&gt;<br>&lt;% end %&gt;</pre><p>This generates an element similar to:</p><pre>&lt;turbo-frame id=&quot;user_2&quot;&gt;<br>  &lt;p&gt;Bob&lt;/p&gt;<br>  &lt;a href=&quot;/users/2/edit&quot;&gt;Edit&lt;/a&gt;<br>&lt;/turbo-frame&gt;</pre><p>user_2 is simply the HTML element&#39;s ID.</p><p>It is <strong>not</strong> a special Rails keyword.</p><p>When navigation occurs inside a frame, Turbo can use the response to update that frame rather than replacing the entire page.</p><p>The mental model is:</p><pre>Whole page<br>┌──────────────────────────────┐<br>│ Header                       │<br>│                              │<br>│ ┌──────────────────────────┐ │<br>│ │ turbo-frame              │ │<br>│ │                          │ │<br>│ │ User #2                  │ │<br>│ │ Edit                      │ │<br>│ │                          │ │<br>│ └──────────────────────────┘ │<br>│                              │<br>│ Footer                       │<br>└──────────────────────────────┘</pre><p>The frame defines a region that Turbo can navigate within.</p><h3>5.6 Turbo Streams</h3><p>Turbo Streams are different from Frames.</p><p>A Turbo Frame defines a <strong>region</strong>.</p><p>A Turbo Stream gives Turbo an <strong>operation to perform on the DOM</strong>.</p><p>For example:</p><pre>&lt;turbo-stream action=&quot;remove&quot; target=&quot;user_2&quot;&gt;<br>&lt;/turbo-stream&gt;</pre><p>means:</p><pre>Find the element with id=&quot;user_2&quot;<br>        ↓<br>Remove it from the DOM</pre><p>Other common stream actions include:</p><pre>append<br>prepend<br>replace<br>update<br>remove<br>before<br>after</pre><p>For example:</p><pre>&lt;turbo-stream action=&quot;append&quot; target=&quot;comments&quot;&gt;<br>  &lt;template&gt;<br>    &lt;p&gt;Hello&lt;/p&gt;<br>  &lt;/template&gt;<br>&lt;/turbo-stream&gt;</pre><p>means:</p><pre>Find #comments<br>        ↓<br>Append the supplied HTML inside it</pre><p>A Turbo Stream is therefore an <strong>instruction</strong>.</p><p>It is not itself a button or event listener.</p><h3>5.7 What Triggers a Turbo Stream?</h3><p>A Turbo Stream does not spontaneously execute merely because you wrote the markup somewhere.</p><p>Something has to cause Turbo to <strong>receive and process</strong> the stream.</p><p>A common example is a form submission.</p><p>Suppose a page contains:</p><pre>&lt;%= button_to &quot;Delete&quot;,<br>              user_path(@user),<br>              method: :delete %&gt;</pre><p>The user clicks the button.</p><p>The flow is:</p><pre>User clicks &quot;Delete&quot;<br>        ↓<br>DELETE /users/2<br>        ↓<br>UsersController#destroy<br>        ↓<br>@user.destroy<br>        ↓<br>Server returns a Turbo Stream response<br>        ↓<br>Turbo processes the stream<br>        ↓<br>Target element is removed</pre><p>The server could return:</p><pre>&lt;%= turbo_stream.remove dom_id(@user) %&gt;</pre><p>which produces a Turbo Stream instruction similar to:</p><pre>&lt;turbo-stream action=&quot;remove&quot; target=&quot;user_2&quot;&gt;<br>&lt;/turbo-stream&gt;</pre><p>Turbo then performs the instructed DOM operation.</p><p>The button is therefore the <strong>trigger for the HTTP request</strong>.</p><p>The Turbo Stream is the <strong>instruction in the response</strong>.</p><p>These are different things.</p><h3>append works the same way</h3><p>Consider:</p><pre>&lt;turbo-stream action=&quot;append&quot; target=&quot;comments&quot;&gt;<br>  &lt;template&gt;<br>    &lt;p&gt;Hello&lt;/p&gt;<br>  &lt;/template&gt;<br>&lt;/turbo-stream&gt;</pre><p>This does not contain a button.</p><p>It does not need to.</p><p>A common flow is:</p><pre>User submits &quot;Add comment&quot; form<br>        ↓<br>POST /comments<br>        ↓<br>CommentsController#create<br>        ↓<br>Comment is saved<br>        ↓<br>Server returns Turbo Stream<br>        ↓<br>Turbo processes:<br><br>action=&quot;append&quot;<br>target=&quot;comments&quot;<br>        ↓<br>New comment is appended</pre><p>So:</p><pre>Button / form / link / browser event<br>        ↓<br>causes a request or other interaction<br>        ↓<br>server or client produces a Turbo Stream<br>        ↓<br>Turbo processes the stream instruction<br>        ↓<br>DOM changes</pre><p>The &lt;turbo-stream&gt; element itself is not the trigger.</p><h3>5.8 Turbo Drive vs. Turbo Frames vs. Turbo Streams</h3><p>The three can be remembered with these three questions:</p><h3>Turbo Drive</h3><blockquote><em>“Can I navigate to another page without a traditional full-page reload?”</em></blockquote><pre>Link<br>  ↓<br>new page HTML<br>  ↓<br>Turbo updates the document</pre><h3>Turbo Frames</h3><blockquote><em>“Can I navigate or update only this specific region?”</em></blockquote><pre>Page<br>  ↓<br>specific &lt;turbo-frame&gt;<br>  ↓<br>only that region changes</pre><h3>Turbo Streams</h3><blockquote><em>“What specific DOM operation should Turbo perform?”</em></blockquote><pre>Turbo Stream<br>  ↓<br>append / prepend / replace / update / remove / before / after</pre><p>The distinction is:</p><pre>Turbo Drive<br>= page-level navigation</pre><pre>Turbo Frame<br>= defined region</pre><pre>Turbo Stream<br>= DOM operation/instruction</pre><p>Frames and Streams can also be used together.</p><p>For example, a form inside a Turbo Frame can submit to the server, and the server can return a Turbo Stream that updates another part of the page.</p><h3>Final Example: Putting Everything Together</h3><p>Consider this route configuration:</p><pre>Rails.application.routes.draw do<br>  resources :users do<br>    collection do<br>      get :search<br>    end<br>  end<br>end</pre><p>Rails creates the seven standard resource routes plus the custom collection route.</p><h3>The seven standard routes</h3><p>ActionHTTP methodURL pathController actionHelperindexGET/usersUsersController#indexusers_pathshowGET/users/:idUsersController#showuser_path(@user)newGET/users/newUsersController#newnew_user_pathcreatePOST/usersUsersController#createusers_patheditGET/users/:id/editUsersController#editedit_user_path(@user)updatePATCH/PUT/users/:idUsersController#updateuser_path(@user)destroyDELETE/users/:idUsersController#destroyuser_path(@user)</p><p>And the additional collection route is:</p><p>ActionHTTP methodURL pathController actionHelpersearchGET/users/searchUsersController#searchsearch_users_path</p><p>The complete conceptual flow is:</p><pre>config/routes.rb<br>                                │<br>              ┌─────────────────┴─────────────────┐<br>              │                                   │<br>              ↓                                   ↓<br>       HTTP request                         Route helpers<br>       GET /users                            users_path<br>              │                                   │<br>              ↓                                   ↓<br>    UsersController#index                     &quot;/users&quot;<br>              │                                   │<br>              ↓                                   ↓<br>app/views/users/index.html.erb              ERB template<br>              │                                   │<br>              └──────────────┬────────────────────┘<br>                             ↓<br>                       Generated HTML<br>                             ↓<br>                          Browser</pre><p>And when Hotwire is involved:</p><pre>Browser<br>   │<br>   │ User interaction<br>   ↓<br>HTTP request<br>   │<br>   ↓<br>routes.rb<br>   │<br>   ↓<br>Controller#Action<br>   │<br>   ├── Model / Active Record<br>   │       ↓<br>   │    Database<br>   │<br>   ↓<br>HTML / Turbo response<br>   │<br>   ├── Turbo Drive<br>   │      → page-level navigation<br>   │<br>   ├── Turbo Frame<br>   │      → update a specific region<br>   │<br>   └── Turbo Stream<br>          → perform a specific DOM operation<br>   │<br>   ↓<br>Browser DOM</pre><p>The core Rails concepts can therefore be summarized as:</p><pre>URL<br>= address such as /users/123</pre><pre>Route<br>= HTTP method + URL pattern → Controller#Action</pre><pre>Controller<br>= class responsible for handling requests</pre><pre>Action<br>= method inside a controller</pre><pre>View<br>= HTML-generating template</pre><pre>ERB<br>= HTML with embedded Ruby</pre><pre>Route helper<br>= Ruby method that generates a URL</pre><pre>Model / Active Record<br>= application layer that handles data and database persistence</pre><pre>Turbo Drive<br>= page-level navigation</pre><pre>Turbo Frame<br>= a defined region of the page</pre><pre>Turbo Stream<br>= an instruction for modifying the DOM</pre><p>And the most important Rails flow to remember is:</p><pre>HTTP request<br>    ↓<br>Route<br>    ↓<br>Controller#Action<br>    ↓<br>Model / Active Record (when data is needed)<br>    ↓<br>View<br>    ↓<br>HTML<br>    ↓<br>Browser</pre><p>with Rails conventions making the controller-to-view connection predictable:</p><pre>UsersController#index<br>        ↓<br>app/views/users/index.html.erb</pre><p>and route helpers providing a convenient way for those views to generate URLs:</p><pre>users_path<br>    ↓<br>/users<br>    ↓<br>&lt;a href=&quot;/users&quot;&gt;...&lt;/a&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69e4417365f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript: Connecting Related Types with a Type Map]]></title>
            <link>https://medium.com/@natsuko-dev-blog/typescript-connecting-related-types-with-a-type-map-c8076272ac4f?source=rss-0b5502fff6f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8076272ac4f</guid>
            <dc:creator><![CDATA[Natsuko]]></dc:creator>
            <pubDate>Sun, 20 Sep 2026 02:07:16 GMT</pubDate>
            <atom:updated>2026-09-20T02:07:16.468Z</atom:updated>
            <content:encoded><![CDATA[<h3>Table of Contents</h3><ol><li>The Problem: How Strict Should Types Be?</li><li>Design C: Connecting Related Types with a Type Map</li><li>Why Runtime Protection Is Still Necessary</li><li>Key Takeaways</li></ol><h3>1. The Problem: How Strict Should Types Be?</h3><p>Suppose an application has a function that receives:</p><ul><li>a category identifier</li><li>some common data</li><li>category-specific options</li></ul><p>The question is how strictly the category-specific options should be typed.</p><h3>Design A: Use a Loose Type</h3><p>One simple approach is:</p><pre>type CategoryOptions = Record&lt;string, unknown&gt;;</pre><p>This is flexible, but it does not strongly enforce which properties are allowed for each category.</p><h3>Design B: Use a Union of All Types</h3><p>Another approach is:</p><pre>type CategoryOptions =<br>  | CategoryAOptions<br>  | CategoryBOptions<br>  | CategoryCOptions;</pre><p>This is stricter, but it still represents the options as a collection of possible types rather than explicitly connecting the first argument to its corresponding options type.</p><p>I wanted the type system to express this relationship directly:</p><pre>category A → CategoryAOptions<br>category B → CategoryBOptions<br>category C → CategoryCOptions</pre><p>That led to Design C: a type map.</p><h3>2. Design C: Connecting Related Types with a Type Map</h3><p>The key idea is to define one mapping interface:</p><pre>interface CategoryOptionsMap {<br>  categoryA: CategoryAOptions;<br>  categoryB: CategoryBOptions;<br>  categoryC: CategoryCOptions;<br>}</pre><p>Each key represents a category, and each value represents the type of options associated with that category.</p><p>Then derive the category type from the keys:</p><pre>type Category = keyof CategoryOptionsMap;</pre><p>This produces:</p><pre>type Category<br>// &quot;categoryA&quot; | &quot;categoryB&quot; | &quot;categoryC&quot;</pre><p>Next, define a generic type that retrieves the options corresponding to a particular category:</p><pre>type CategoryOptions&lt;C extends Category&gt; =<br>  CategoryOptionsMap[C];</pre><p>The important part is:</p><pre>CategoryOptionsMap[C]</pre><p>This means:</p><blockquote><em>Given a category type </em><em>C, look up the corresponding options type in </em><em>CategoryOptionsMap.</em></blockquote><p>For example:</p><pre>CategoryOptions&lt;&quot;categoryA&quot;&gt;</pre><p>resolves to:</p><pre>CategoryAOptions</pre><p>and:</p><pre>CategoryOptions&lt;&quot;categoryB&quot;&gt;</pre><p>resolves to:</p><pre>CategoryBOptions</pre><h3>Connecting the Types with a Generic Function</h3><p>The function can now use the same generic type parameter for both arguments:</p><pre>function handleData&lt;C extends Category&gt;(<br>  category: C,<br>  options: CategoryOptions&lt;C&gt;<br>) {<br>  // ...<br>}</pre><p>When this is called:</p><pre>handleData(&quot;categoryA&quot;, categoryAOptions);</pre><p>TypeScript infers:</p><pre>C = &quot;categoryA&quot;</pre><p>Therefore:</p><pre>CategoryOptions&lt;C&gt;</pre><p>becomes:</p><pre>CategoryOptions&lt;&quot;categoryA&quot;&gt;</pre><p>which becomes:</p><pre>CategoryAOptions</pre><p>The relationship is:</p><pre>C = &quot;categoryA&quot;<br>       ↓<br>CategoryOptions&lt;C&gt;<br>       ↓<br>CategoryOptions&lt;&quot;categoryA&quot;&gt;<br>       ↓<br>CategoryAOptions</pre><p>The two arguments are therefore type-linked.</p><p>If the wrong options type is passed:</p><pre>handleData(&quot;categoryA&quot;, categoryBOptions);</pre><p>TypeScript can report an error because categoryBOptions does not match CategoryAOptions.</p><h3>Why This Is Different from a Union</h3><p>A union says:</p><pre>type CategoryOptions =<br>  | CategoryAOptions<br>  | CategoryBOptions<br>  | CategoryCOptions;</pre><p>In other words:</p><blockquote><em>The value can be one of these types.</em></blockquote><p>The generic type-map design says:</p><blockquote><em>The type of the second argument is determined by the type of the first argument.</em></blockquote><p>That relationship is the main advantage of this design.</p><h3>Is satisfies Still Necessary?</h3><p>With this design, it is generally unnecessary to separately write:</p><pre>const options = {<br>  // ...<br>} satisfies CategoryAOptions;</pre><p>if the object is immediately passed to:</p><pre>handleData(&quot;categoryA&quot;, options);</pre><p>The function parameter already requires:</p><pre>CategoryOptions&lt;&quot;categoryA&quot;&gt;</pre><p>which resolves to:</p><pre>CategoryAOptions</pre><p>Therefore, the function call itself provides the relevant type checking.</p><p>satisfies can still be useful when an object needs to be checked against a type independently of a function call, but it is not required simply to make this particular relationship type-safe.</p><h3>3. Why Runtime Protection Is Still Necessary</h3><p>The type map provides strong compile-time protection, but it does not make runtime validation unnecessary.</p><p>TypeScript types do not automatically validate JavaScript values at runtime.</p><h3>any</h3><p>Consider:</p><pre>function handleData&lt;C extends Category&gt;(<br>  category: C,<br>  options: CategoryOptions&lt;C&gt;<br>) {<br>  // ...<br>}<br><br>const options: any = getSomething();<br>handleData(&quot;categoryA&quot;, options);</pre><p>It may seem that the function’s parameter type should reject options.</p><p>For &quot;categoryA&quot;, the required type is:</p><pre>CategoryOptions&lt;&quot;categoryA&quot;&gt;</pre><p>which resolves to:</p><pre>CategoryAOptions</pre><p>However, any bypasses that check.</p><p>A simpler example shows the same behavior:</p><pre>function printValue(value: string) {}<br><br>const value: any = 123;<br>printValue(value); // No TypeScript error</pre><p>Without any:</p><pre>printValue(123); // Type error</pre><p>any effectively tells TypeScript:</p><blockquote><em>Do not type-check this value.</em></blockquote><p>Therefore, a runtime guard can still be useful when a value has passed through any.</p><h3>as Type Assertions</h3><p>A type assertion such as:</p><pre>const options = something as CategoryAOptions;</pre><p>does not validate the object at runtime.</p><p>For example:</p><pre>const options = {<br>  unexpectedProperty: &quot;some value&quot;,<br>} as CategoryAOptions;</pre><p>The actual runtime object still contains:</p><pre>{<br>  unexpectedProperty: &quot;some value&quot;<br>}</pre><p>The assertion only changes how TypeScript treats the value.</p><p>It does not:</p><ul><li>remove unexpected properties</li><li>check whether required properties exist</li><li>validate the value at runtime</li><li>transform the object</li></ul><p>This is also why a test can intentionally use a type assertion when testing a runtime guard. The assertion can simulate a value that has bypassed normal compile-time checks.</p><h3>External Libraries</h3><p>Consider:</p><pre>const options = someLibrary.getOptions();<br><br>handleData(&quot;categoryA&quot;, options);</pre><p>Suppose the library’s TypeScript declaration says:</p><pre>getOptions(): CategoryAOptions;</pre><p>TypeScript will trust that declaration.</p><p>However, the actual value is produced at runtime. It might ultimately come from an API response, configuration, environment data, or another runtime source.</p><p>The important distinction is:</p><pre>Declared type:<br>CategoryAOptions<br><br>Actual runtime value:<br>whatever the library actually returns</pre><p>A well-maintained library should normally keep these consistent. The point is that TypeScript itself does not independently inspect the runtime object and prove that the declaration matches the actual value.</p><h3>Deserialized JSON</h3><p>JSON is another example of runtime data:</p><pre>const json = await response.text();<br>const options = JSON.parse(json);</pre><pre>handleData(&quot;categoryA&quot;, options);</pre><p>JSON.parse() does not know anything about CategoryAOptions.</p><p>It simply converts JSON into a JavaScript value.</p><p>Even this:</p><pre>const options =<br>  JSON.parse(json) as CategoryAOptions;</pre><p>does not validate the JSON.</p><p>The as CategoryAOptions part only tells TypeScript how to treat the result.</p><p>The actual runtime data could still contain unexpected properties.</p><p>If runtime validation is required, the data must be explicitly validated rather than relying on the type assertion.</p><h3>Dynamically Constructed Objects</h3><p>Consider:</p><pre>const source = getData();<br><br>const options = {<br>  ...source,<br>  someSetting: value,<br>};<br>handleData(&quot;categoryA&quot;, options);</pre><p>The final object contains everything in source, not just the property explicitly written in this code.</p><p>If source contains an unexpected property at runtime, the spread operator copies it:</p><pre>source<br>  ↓<br>...source<br>  ↓<br>options</pre><p>For example, if the runtime value of source is:</p><pre>{<br>  unexpectedProperty: &quot;some value&quot;,<br>  anotherProperty: 123<br>}</pre><p>then the resulting object also contains those properties.</p><p>With correctly typed source data, TypeScript can catch many such problems. But when the source comes from runtime data, any, an external source, or a type assertion, unexpected properties can still make their way into the resulting object.</p><h3>Compile-Time Protection and Runtime Protection Have Different Jobs</h3><p>The distinction is:</p><pre>Compile time<br>    ↓<br>Type map + generic constraints<br>    ↓<br>Prevent invalid code from compiling<br><br><br>Runtime<br>    ↓<br>Actual JavaScript values<br>    ↓<br>Runtime validation / filtering<br>    ↓<br>Protect against unexpected data</pre><p>The goal is not to choose between type safety and runtime validation.</p><p>They protect against different things.</p><h3>4. Key Takeaways</h3><h3>1. A type map can express relationships between types</h3><pre>interface CategoryOptionsMap {<br>  categoryA: CategoryAOptions;<br>  categoryB: CategoryBOptions;<br>}<br><br>type Category = keyof CategoryOptionsMap;<br>type CategoryOptions&lt;C extends Category&gt; =<br>  CategoryOptionsMap[C];</pre><p>A generic function can then connect the two:</p><pre>function handleData&lt;C extends Category&gt;(<br>  category: C,<br>  options: CategoryOptions&lt;C&gt;<br>) {<br>  // ...<br>}</pre><p>This allows TypeScript to enforce:</p><pre>category A → options for category A<br>category B → options for category B</pre><h3>2. any can bypass the function&#39;s type constraint</h3><p>Even when a function requires a specific type, a value typed as any can be passed without a type error.</p><h3>3. as does not validate data</h3><pre>value as SomeType</pre><p>changes TypeScript’s static interpretation of the value. It does not validate or transform the runtime object.</p><h3>4. Runtime data is not automatically type-safe</h3><p>Data from external libraries, JSON, APIs, configuration, and dynamically constructed objects exists at runtime. TypeScript cannot automatically verify the actual contents of every such value.</p><h3>5. Strong typing and runtime guards are complementary</h3><pre>Strong compile-time types<br>+<br>Runtime validation where necessary<br>=<br>Defense in depth</pre><p>Use the type system to prevent invalid code during development, and use runtime checks to protect against values that reach the program without having been reliably validated by the type system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8076272ac4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Test React Components with react-i18next: Mocking useTranslation()]]></title>
            <link>https://medium.com/@natsuko-dev-blog/how-to-test-react-components-with-react-i18next-mocking-usetranslation-01b4e716fe64?source=rss-0b5502fff6f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/01b4e716fe64</guid>
            <dc:creator><![CDATA[Natsuko]]></dc:creator>
            <pubDate>Thu, 16 Jul 2026 06:54:46 GMT</pubDate>
            <atom:updated>2026-07-16T06:54:46.581Z</atom:updated>
            <content:encoded><![CDATA[<h3>Table of Contents</h3><ol><li><a href="https://chatgpt.com/c/6a587b56-bc08-83e8-b369-cbf72e38c673#1-what-react-i18next-does-in-an-application">What </a><a href="https://chatgpt.com/c/6a587b56-bc08-83e8-b369-cbf72e38c673#1-what-react-i18next-does-in-an-application">react-i18next Does in an Application</a></li><li><a href="https://chatgpt.com/c/6a587b56-bc08-83e8-b369-cbf72e38c673#2-why-a-unit-test-may-not-need-the-real-translation-system">Why a Unit Test May Not Need the Real Translation System</a></li><li><a href="https://chatgpt.com/c/6a587b56-bc08-83e8-b369-cbf72e38c673#3-mocking-usetranslation-with-vitest">Mocking </a><a href="https://chatgpt.com/c/6a587b56-bc08-83e8-b369-cbf72e38c673#3-mocking-usetranslation-with-vitest">useTranslation() with Vitest</a></li><li><a href="https://chatgpt.com/c/6a587b56-bc08-83e8-b369-cbf72e38c673#4-how-the-mocked-t-function-works">How the Mocked </a><a href="https://chatgpt.com/c/6a587b56-bc08-83e8-b369-cbf72e38c673#4-how-the-mocked-t-function-works">t() Function Works</a></li><li><a href="https://chatgpt.com/c/6a587b56-bc08-83e8-b369-cbf72e38c673#5-why-the-mock-handles-fallback-strings">Why the Mock Handles Fallback Strings</a></li><li><a href="https://chatgpt.com/c/6a587b56-bc08-83e8-b369-cbf72e38c673#6-using-translation-keys-as-predictable-test-text">Using Translation Keys as Predictable Test Text</a></li><li><a href="https://chatgpt.com/c/6a587b56-bc08-83e8-b369-cbf72e38c673#7-takeaway">Takeaway</a></li></ol><h3>1. What react-i18next Does in an Application</h3><p>In a multilingual React application, components often use useTranslation() to obtain a t() function:</p><pre>const { t } = useTranslation()</pre><p>The component can then pass a translation key to t():</p><pre>&lt;button&gt;{t(&#39;navigation.settings&#39;)}&lt;/button&gt;</pre><p>The key itself is not necessarily the text displayed to the user.</p><p>For example, translation files might contain:</p><pre>// en.json<br>{<br>  &quot;navigation&quot;: {<br>    &quot;settings&quot;: &quot;Settings&quot;<br>  }<br>}</pre><pre>// ja.json<br>{<br>  &quot;navigation&quot;: {<br>    &quot;settings&quot;: &quot;設定&quot;<br>  }<br>}</pre><p>The same code:</p><pre>t(&#39;navigation.settings&#39;)</pre><p>can therefore produce different text depending on the current language:</p><pre>English → &quot;Settings&quot;<br>Japanese → &quot;設定&quot;</pre><p>The translation key acts as a stable identifier in the source code, while the translation files provide the language-specific text displayed in the UI.</p><h3>2. Why a Unit Test May Not Need the Real Translation System</h3><p>A unit test does not always need to test every system that the component depends on.</p><p>For example, suppose a test needs to interact with a button rendered using:</p><pre>t(&#39;navigation.settings&#39;)</pre><p>The purpose of the test might be to verify what happens after the button is clicked.</p><p>In that case, the test may not be testing:</p><ul><li>whether the English translation is correct,</li><li>whether the Japanese translation is correct,</li><li>whether the current language is detected correctly,</li><li>whether the translation files are loaded correctly.</li></ul><p>Those are separate responsibilities.</p><p>The test only needs to interact with the relevant button.</p><p>In other words, the test may only need to perform an action such as:</p><pre>fireEvent.mouseDown(<br>  screen.getByText(&#39;navigation.settings&#39;)<br>)</pre><p>The exact text displayed by the button — such as &quot;Settings&quot; or &quot;設定&quot;—is not important to this particular test.</p><p>What matters is that the test can reliably identify the element it needs to interact with.</p><p>Instead of setting up the entire i18n system, the test can replace it with a small mock that produces predictable output.</p><h3>3. Mocking useTranslation() with Vitest</h3><p>A test can replace the react-i18next module with a mock:</p><pre>vi.mock(&#39;react-i18next&#39;, () =&gt; ({<br>  useTranslation: () =&gt; ({<br>    t: (<br>      key: string,<br>      fallbackOrOptions?: string | Record&lt;string, unknown&gt;<br>    ) =&gt; {<br>      if (typeof fallbackOrOptions === &#39;string&#39;) {<br>        return fallbackOrOptions<br>      }<br><br>return key<br>    },<br>  }),<br>}))</pre><p>This mock has three main parts.</p><h3>1. Replace the module</h3><pre>vi.mock(&#39;react-i18next&#39;, () =&gt; ({<br>  ...<br>}))</pre><p>This tells Vitest to use the provided fake implementation instead of the actual react-i18next module in the test.</p><h3>2. Provide a fake useTranslation()</h3><pre>useTranslation: () =&gt; ({<br>  t: ...<br>})</pre><p>The real useTranslation() provides a translation function and potentially other functionality.</p><p>However, if the component only uses t(), the mock only needs to provide t().</p><p>The mock does not need to reproduce the entire original library.</p><p>It only needs to provide the part of the API that the code under test actually uses.</p><h3>3. Provide a fake t() function</h3><pre>t: (<br>  key: string,<br>  fallbackOrOptions?: string | Record&lt;string, unknown&gt;<br>) =&gt; {<br>  ...<br>}</pre><p>The fake function accepts:</p><ol><li>a translation key, and</li><li>an optional second argument that can be either a fallback string or an options object.</li></ol><p>The mock then decides what to return based on the type of the second argument.</p><h3>4. How the Mocked t() Function Works</h3><p>The core logic is:</p><pre>if (typeof fallbackOrOptions === &#39;string&#39;) {<br>  return fallbackOrOptions<br>}<br><br>return key</pre><p>This creates two simple rules:</p><pre>A fallback string is provided<br>        ↓<br>Return the fallback string<br><br>No fallback string is provided<br>        ↓<br>Return the translation key itself</pre><h3>Example 1: A translation key without a fallback</h3><pre>t(&#39;navigation.settings&#39;)</pre><p>The second argument is undefined.</p><p>Therefore:</p><pre>typeof fallbackOrOptions === &#39;string&#39;</pre><p>is false.</p><p>The function returns:</p><pre>&quot;navigation.settings&quot;</pre><p>The key is returned unchanged.</p><p>No actual translation takes place.</p><h3>Example 2: A translation key with a fallback string</h3><pre>t(<br>  &#39;navigation.back&#39;,<br>  &#39;Back&#39;<br>)</pre><p>The second argument is a string.</p><p>Therefore:</p><pre>typeof fallbackOrOptions === &#39;string&#39;</pre><p>is true.</p><p>The function returns:</p><pre>&quot;Back&quot;</pre><p>The fallback string is used directly.</p><h3>Example 3: A translation key with an options object</h3><p>t() may also receive an object as its second argument.</p><p>For example:</p><pre>t(<br>  &#39;items.count&#39;,<br>  { count: 5 }<br>)</pre><p>In this case, the second argument is an object rather than a string.</p><p>Therefore, the condition is false:</p><pre>typeof fallbackOrOptions === &#39;string&#39;</pre><p>The mock returns the key:</p><pre>&quot;items.count&quot;</pre><p>This mock does not perform interpolation or real translation. It simply provides predictable output for the test.</p><h3>5. Why the Mock Handles Fallback Strings</h3><p>A simpler mock could always return the key:</p><pre>t: (key) =&gt; key</pre><p>However, this would ignore an important way that t() can be used.</p><p>Consider:</p><pre>t(<br>  &#39;navigation.back&#39;,<br>  &#39;Back&#39;<br>)</pre><p>The source code explicitly provides &quot;Back&quot; as a fallback string.</p><p>If the mock always returned the key, the rendered text would be:</p><pre>&quot;navigation.back&quot;</pre><p>The fallback would be lost.</p><p>Therefore, the mock preserves this simple behavior:</p><pre>If the second argument is a string:<br>    return the string<br><br>Otherwise:<br>    return the key</pre><p>This does not mean that the mock fully implements the real translation library.</p><p>It only supports the specific behavior needed by the test.</p><p>That distinction is important.</p><p>A mock does not need to be a complete replacement for the real dependency. It needs to provide the behavior that matters for the code being tested.</p><h3>6. Using Translation Keys as Predictable Test Text</h3><p>With this mock in place:</p><pre>t(&#39;navigation.settings&#39;)</pre><p>returns:</p><pre>&quot;navigation.settings&quot;</pre><p>The test can therefore locate the corresponding element using the key:</p><pre>fireEvent.mouseDown(<br>  screen.getByText(&#39;navigation.settings&#39;)<br>)</pre><p>This makes the test independent of the actual translated text.</p><p>For example, the translation might later change from:</p><pre>&quot;Settings&quot;</pre><p>to:</p><pre>&quot;Preferences&quot;</pre><p>The test does not need to change.</p><p>The same applies if the Japanese translation or another language’s translation changes.</p><p>The test is not testing the wording displayed to the user.</p><p>It is testing the behavior that occurs when the relevant UI element is interacted with.</p><p>Using the translation key as the mock output gives the test a stable and predictable value to query.</p><h3>7. Takeaway</h3><p>When a component depends on a larger subsystem, a unit test does not always need to initialize the entire subsystem.</p><p>For i18n, the test may not need:</p><ul><li>the real translation files,</li><li>language detection,</li><li>the current locale,</li><li>or the complete translation configuration.</li></ul><p>If the test only needs to interact with an element rendered through t(), a small mock may be enough.</p><p>For example:</p><pre>t: (<br>  key,<br>  fallbackOrOptions<br>) =&gt; {<br>  if (typeof fallbackOrOptions === &#39;string&#39;) {<br>    return fallbackOrOptions<br>  }<br><br>return key<br>}</pre><p>This mock follows a simple rule:</p><pre>Fallback string provided<br>    → return the fallback string<br><br>No fallback string provided<br>    → return the key itself</pre><p>The goal of a mock is not to reproduce the entire implementation of the real dependency.</p><p>The goal is to provide the smallest predictable behavior that allows the code under test to run and the test to focus on its actual purpose.</p><blockquote><strong><em>Mock the behavior the test needs — not the entire system behind the dependency.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01b4e716fe64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Implement Multilanguage Support in React: i18n, react-i18next, and useTranslation()]]></title>
            <link>https://medium.com/@natsuko-dev-blog/how-to-implement-multilanguage-support-in-react-i18n-react-i18next-and-usetranslation-6b9b512af862?source=rss-0b5502fff6f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b9b512af862</guid>
            <dc:creator><![CDATA[Natsuko]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 00:32:09 GMT</pubDate>
            <atom:updated>2026-07-15T00:32:09.034Z</atom:updated>
            <content:encoded><![CDATA[<h3>Table of Contents</h3><ol><li>What i18n Means and Why It Exists</li><li>The Relationship Between i18next, react-i18next, and Next.js</li><li>How useTranslation() Works in React</li><li>Translation Files and Translation Keys</li><li>What i18n Handles and What It Does Not Handle</li><li>Best Practices for Translating Static UI and Dynamic Content</li></ol><h3>1. What i18n Means and Why It Exists</h3><p>i18n is a common term used in software development for <strong>internationalization</strong>.</p><p>It is a numeronym, which means a word where numbers replace some of the letters.</p><p>The word:</p><pre>internationalization</pre><p>can be shortened as:</p><pre>i18n</pre><p>because:</p><pre>i + 18 letters + n</pre><p>The same naming pattern is used in:</p><pre>l10n = localization</pre><p>Internationalization means designing an application so that it can support multiple languages without changing the application logic.</p><p>Instead of writing language-specific text directly inside components:</p><pre>&lt;button&gt;Save&lt;/button&gt;</pre><p>developers separate the text from the UI logic:</p><pre>&lt;button&gt;{t(&#39;button.save&#39;)}&lt;/button&gt;</pre><p>The component only contains a translation key.</p><p>The actual displayed text is stored separately:</p><pre>{<br>  &quot;button&quot;: {<br>    &quot;save&quot;: &quot;Save&quot;<br>  }<br>}</pre><p>For another language:</p><pre>{<br>  &quot;button&quot;: {<br>    &quot;save&quot;: &quot;保存&quot;<br>  }<br>}</pre><p>The React component stays unchanged. Only the translation resource changes.</p><h3>2. The Relationship Between i18next, react-i18next, and Next.js</h3><h3>i18next</h3><p>i18next is the core internationalization library.</p><p>It provides:</p><ul><li>translation file management</li><li>language detection</li><li>key lookup</li><li>interpolation support</li></ul><p>For example:</p><pre>i18next.t(&#39;button.save&#39;)</pre><p>returns the correct string based on the active language.</p><h3>react-i18next</h3><p>react-i18next provides React-specific integration.</p><p>It adds:</p><ul><li>useTranslation() hook</li><li>&lt;Trans /&gt; component</li></ul><p>Example:</p><pre>import { useTranslation } from &#39;react-i18next&#39;<br><br>function SaveButton() {<br>  const { t } = useTranslation()<br>  return (<br>    &lt;button&gt;<br>      {t(&#39;button.save&#39;)}<br>    &lt;/button&gt;<br>  )<br>}</pre><p>The relationship:</p><pre>i18next<br>   ↓<br>react-i18next<br>   ↓<br>useTranslation()<br>   ↓<br>React components</pre><h3>Is i18next related to Next.js?</h3><p>No.</p><p>Despite the similar names, they are unrelated.</p><p>Next.js is a React framework that provides:</p><ul><li>routing</li><li>server-side rendering</li><li>static generation</li></ul><p>The “next” in i18next means “next generation.” It is not connected to Next.js.</p><h3>3. How useTranslation() Works in React</h3><p>useTranslation() provides the t() function.</p><p>Example:</p><pre>const { t } = useTranslation()<br><br>return (<br>  &lt;h1&gt;<br>    {t(&#39;profile.title&#39;)}<br>  &lt;/h1&gt;<br>)</pre><p>The important point:</p><pre>t() does not translate text.</pre><p>It performs a lookup.</p><p>The process:</p><pre>React Component<br>        |<br>        |<br>        v<br>t(&#39;profile.title&#39;)<br>        |<br>        |<br>        v<br>Translation Dictionary<br>        |<br>        |<br>        v<br>Displayed Text</pre><p>English:</p><pre>{<br>  &quot;profile&quot;: {<br>    &quot;title&quot;: &quot;Profile&quot;<br>  }<br>}</pre><p>Japanese:</p><pre>{<br>  &quot;profile&quot;: {<br>    &quot;title&quot;: &quot;プロフィール&quot;<br>  }<br>}</pre><p>The component does not know which language is being displayed.</p><h3>4. Translation Files and Translation Keys</h3><p>Translation files are often called <strong>JSON dictionaries</strong>.</p><p>This simply means JSON files that store key-value mappings.</p><p>Example:</p><pre>{<br>  &quot;common&quot;: {<br>    &quot;save&quot;: &quot;Save&quot;,<br>    &quot;cancel&quot;: &quot;Cancel&quot;<br>  }<br>}</pre><p>The key:</p><pre>common.save</pre><p>maps to:</p><pre>Save</pre><p>A typical React application might have:</p><pre>src/i18n/locales/<br> ├── en.json<br> └── ja.json</pre><p>Example structure:</p><pre>{<br>  &quot;navigation&quot;: {<br>    &quot;home&quot;: &quot;Home&quot;,<br>    &quot;settings&quot;: &quot;Settings&quot;<br>  },<br>  &quot;button&quot;: {<br>    &quot;submit&quot;: &quot;Submit&quot;<br>  },<br>  &quot;error&quot;: {<br>    &quot;network&quot;: &quot;Network error occurred&quot;<br>  }<br>}</pre><p>Translation keys are usually organized by feature or purpose.</p><p>This makes thousands of strings easier to maintain.</p><h3>5. What i18n Handles</h3><p>i18n is mainly designed for <strong>static application text</strong>.</p><p>Examples:</p><h3>Buttons</h3><pre>{t(&#39;button.submit&#39;)}</pre><h3>Navigation labels</h3><pre>{t(&#39;navigation.settings&#39;)}</pre><h3>Error messages</h3><pre>{t(&#39;error.network&#39;)}</pre><h3>Form labels</h3><pre>{t(&#39;form.email&#39;)}</pre><p>These are texts created by developers and shipped with the application.</p><h3>6. What i18n Does Not Handle</h3><p>i18n does not automatically translate dynamic content.</p><p>Dynamic content includes:</p><ul><li>user-generated posts</li><li>uploaded documents</li><li>customer-entered information</li><li>database records</li><li>AI-generated responses</li></ul><p>For example:</p><pre>&lt;p&gt;<br>  {userMessage}<br>&lt;/p&gt;</pre><p>The i18n system does not translate userMessage.</p><p>It simply displays the value.</p><p>This is because dynamic content is not known when developers create the translation files.</p><p>A translation dictionary cannot contain every possible user-generated sentence.</p><h3>7. How to Translate Dynamic Content When Needed</h3><p>Dynamic content requires a different solution.</p><h3>Option 1: Machine Translation API</h3><p>Applications can call translation services:</p><ul><li>Google Cloud Translation</li><li>DeepL API</li><li>AWS Translate</li></ul><p>Example flow:</p><pre>Original Content<br>        |<br>        v<br>Translation API<br>        |<br>        v<br>Translated Content</pre><p>Common practices:</p><ul><li>translate only when requested</li><li>cache translated results</li><li>allow users to view the original content</li></ul><p>Automatically translating everything is usually avoided because translation quality depends on context.</p><h3>Option 2: Store Multiple Language Versions</h3><p>For content written by humans, applications often store translations separately.</p><p>Example:</p><p>Database:</p><pre>Article<br><br>title_en:<br>&quot;Introduction to React&quot;<br>title_ja:<br>&quot;React入門&quot;</pre><p>This approach is common for:</p><ul><li>documentation</li><li>marketing pages</li><li>help centers</li></ul><p>because human-written translations usually provide better quality.</p><h3>8. Best Practice Architecture</h3><p>A production application usually separates two concerns.</p><h3>Application UI Translation</h3><p>Use:</p><pre>react-i18next + translation files</pre><p>For:</p><ul><li>buttons</li><li>menus</li><li>labels</li><li>messages</li></ul><h3>Dynamic Content Translation</h3><p>Use:</p><ul><li>translation APIs</li><li>multilingual database fields</li><li>human translation workflows</li></ul><p>when the product requirement requires it.</p><h3>Conclusion</h3><p>Multilanguage support is not one single translation system.</p><p>A well-designed React application separates:</p><h3>Static UI text</h3><p>Handled by:</p><pre>i18n<br>react-i18next<br>useTranslation()<br>JSON translation files</pre><h3>Dynamic content</h3><p>Handled separately through:</p><pre>translation APIs<br>or<br>stored multilingual conten</pre><p>useTranslation() exists to make React components language-independent. It allows developers to maintain one codebase while supporting multiple languages without mixing UI logic and language-specific text.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b9b512af862" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure URL Preview Generation: Preventing SSRF and Spoofed Preview Data]]></title>
            <link>https://medium.com/@natsuko-dev-blog/secure-url-preview-generation-preventing-ssrf-and-spoofed-preview-data-9697830c9cde?source=rss-0b5502fff6f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9697830c9cde</guid>
            <dc:creator><![CDATA[Natsuko]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 00:26:37 GMT</pubDate>
            <atom:updated>2026-07-10T00:26:37.651Z</atom:updated>
            <content:encoded><![CDATA[<h3>Table of Contents</h3><ol><li>Introduction: Why URL previews require security considerations</li><li>Why URL preview fetching must happen on the backend</li><li>Preventing SSRF when fetching URL metadata</li><li>Why the backend must not trust client-submitted preview data</li><li>Why the backend fetches the URL again when saving a post</li><li>SSRF vs. spoofed preview data: two different security risks</li><li>Summary: Secure architecture for URL previews</li></ol><h3>1. Introduction: Why URL previews require security considerations</h3><p>Many modern applications, such as social media platforms, chat applications, and community forums, provide URL preview functionality.</p><p>For example:</p><ol><li>When a user types a URL into a post composer, a preview card appears immediately while they are writing.</li></ol><pre>User types:<br><br>https://example.com/article<br><br>↓<br>Composer shows:<br>[Example Article]<br>[Thumbnail image]</pre><ol><li>After the user publishes the post, the same preview card appears permanently in the feed for other users.</li></ol><pre>User publishes post<br>↓<br>Other users open the feed<br>↓<br>The post displays:<br>[Example Article]<br>[Thumbnail image]</pre><p>Although these two features look similar from a user’s perspective, they have different security considerations.</p><p>The first case requires the application to safely fetch information from an external website while the user is composing a post.</p><p>The second case requires the application to safely store and display preview information that will later be shown to other users.</p><p>The main security risks are:</p><ul><li><strong>SSRF (Server-Side Request Forgery):</strong> An attacker tricks the backend server into fetching a URL that it should not access, such as internal/private resources.</li><li><strong>Spoofed preview data:</strong> An attacker submits fake preview information and tricks the application into displaying misleading data to other users.</li></ul><p>To implement URL previews securely, the backend must control how preview information is fetched, validated, and stored.</p><h3>2. Why URL preview fetching must happen on the backend</h3><p>A URL preview requires information from the target website:</p><ul><li>Page title (&lt;title&gt;)</li><li>Preview image (og:image)</li><li>Description (og:description)</li></ul><p>For example:</p><pre>https://example.com/article<br>↓<br>Title: &quot;Example Article&quot;<br>Image: &quot;thumbnail.jpg&quot;<br>Description: &quot;An article about...&quot;</pre><p>The application needs to visit the external URL and read its metadata.</p><p>However, this fetching should be performed by the backend server, not directly by the frontend browser.</p><h3>Reason 1: Browsers cannot freely fetch arbitrary websites</h3><p>Browsers enforce security restrictions such as CORS (Cross-Origin Resource Sharing).</p><p>A frontend application usually cannot request and read data from any random external website.</p><p>For example:</p><pre>fetch(&quot;https://external-site.com&quot;)</pre><p>may be blocked by the browser if the external website does not allow cross-origin requests.</p><p>A backend server does not have this browser restriction. Servers can communicate directly with other servers.</p><p>Therefore:</p><pre>Frontend browser<br>        |<br>        | Cannot reliably fetch arbitrary websites<br>        |<br>External website<br><br>Backend server<br>        |<br>        | Can fetch external websites<br>        |<br>External website</pre><h3>Reason 2: The backend can enforce security rules</h3><p>Although the backend can perform the fetch, it does not mean that every URL is safe.</p><p>A user-controlled URL is untrusted input.</p><p>If the backend fetches any URL without checking it first, an attacker may abuse the backend’s network access.</p><p>Therefore, the backend must:</p><ol><li>Validate the URL.</li><li>Confirm that the destination is allowed.</li><li>Fetch the website only after validation.</li></ol><p>The correct flow is:</p><pre>User provides URL<br>        ↓<br>Backend validates URL<br>        ↓<br>Backend fetches external website<br>        ↓<br>Backend extracts metadata<br>        ↓<br>Frontend displays preview</pre><h3>3. Preventing SSRF when fetching URL metadata</h3><h3>What is SSRF?</h3><p>SSRF (Server-Side Request Forgery) is an attack where an attacker tricks a server into making requests on the attacker’s behalf.</p><p>The important point is that the request is made <strong>from the backend server’s network environment</strong>, not from the attacker’s computer.</p><h3>Example: Accessing an internal admin system</h3><p>Imagine an application has:</p><pre>Public Internet<br>        |<br>        |<br>        v<br>Backend Server<br>        |<br>        |<br>        v<br>Internal Admin System</pre><p>The internal admin system is not publicly accessible.</p><p>A normal user cannot access:</p><pre>http://internal-admin</pre><p>However, the backend server may be able to access it because it exists inside the same private network.</p><p>A malicious user could submit:</p><pre>http://internal-admin/secret-page</pre><p>as a URL for preview generation.</p><p>If the backend blindly fetches it:</p><pre>Attacker<br>　 |<br>   | &quot;Generate preview for this URL&quot;<br>   |<br>   v<br>Backend Server<br>   |<br>   | fetches internal system<br>   |<br>   v<br>Internal Admin System</pre><p>The backend unintentionally becomes a bridge between the attacker and the internal resource.</p><p>The attacker may receive information that they were never supposed to access.</p><p>This is SSRF.</p><h3>What does “internal/private address” mean?</h3><p>It refers to resources that are reachable from the backend server’s own environment.</p><p>Examples:</p><ul><li>localhost / 127.0.0.1</li><li>The backend server communicating with itself.</li><li>Private network addresses such as:</li><li>10.x.x.x</li><li>192.168.x.x</li><li>Cloud metadata services such as:</li><li>169.254.169.254</li></ul><p>These are not other companies’ private systems.</p><p>The backend cannot access arbitrary internal networks around the world.</p><p>The concern is only:</p><blockquote><em>Can this backend server reach this destination from where it is running?</em></blockquote><h3>How to prevent SSRF</h3><p>Before fetching a URL, the backend should check:</p><ul><li>Is the URL using an allowed protocol?</li><li>Does the hostname resolve to a public IP address?</li><li>Is the destination a private/internal address?</li></ul><p>Only after validation should the backend fetch the website.</p><h3>4. Why the backend must not trust client-submitted preview data</h3><p>After a user publishes a post, the preview information becomes permanent application data.</p><p>This creates a different security problem.</p><p>A dangerous implementation would be:</p><pre>Frontend:<br>{<br>  url: &quot;https://example.com&quot;,<br>  title: &quot;Official Bank Login&quot;<br>}<br><br>        ↓<br><br>Backend:<br>Save everything received from the client<br>        ↓<br><br>Database</pre><p>The problem is that the client controls the data it sends.</p><p>A malicious user can bypass the normal UI and send a custom request:</p><pre>POST /posts<br><br>{<br>  url: &quot;https://fake-bank.com&quot;,<br>  preview:<br>  {<br>    title: &quot;Official Bank Login&quot;<br>  }<br>}</pre><p>The backend cannot know whether the title was:</p><ul><li>Actually fetched from the website</li><li>Created by the attacker</li></ul><p>Therefore:</p><blockquote><em>Data received from the client must never be trusted just because it looks like data generated by the server.</em></blockquote><h3>5. Why the backend fetches the URL again when saving a post</h3><p>A common question is:</p><p>“If the backend already fetched the preview while the user was composing the post, why fetch it again?”</p><p>Because the two situations have different trust requirements.</p><p>While composing:</p><pre>Backend<br>↓<br>Fetch metadata<br>↓<br>Send preview to frontend<br>↓<br>Display temporarily</pre><p>The preview is only used for the current user’s screen.</p><p>When saving permanently:</p><pre>User clicks Post<br>↓<br>Backend receives post<br>↓<br>Backend fetches URL again<br>↓<br>Backend saves verified preview data<br>↓<br>Other users see it later</pre><p>The backend does not reuse preview data that traveled through the client.</p><p>The reason is:</p><pre>Backend<br>   |<br>   | generated data<br>   |<br>Frontend<br>   |<br>   | user can modify anything<br>   |<br>Backend</pre><p>Once data passes through the client, the backend cannot prove that it has not been changed.</p><p>Therefore, when data will become permanent and visible to other users, the backend must generate it again by itself.</p><h3>6. SSRF vs. Spoofed Preview Data</h3><p>These are separate security problems.</p><p>SSRFSpoofed Preview DataMain problemBackend fetches a dangerous URLBackend saves fake preview informationRequires backend fetching?YesNoAttacker submitsInternal/private URLFake title/image dataAttacker’s goalAccess confidential internal informationDeceive other usersMain defenseValidate URL before fetchingNever trust client-submitted preview data</p><h3>7. Summary: Secure architecture for URL previews</h3><p>A secure URL preview system follows these rules:</p><h3>Rule 1: Fetch external website data on the backend</h3><pre>Frontend<br>   |<br>   v<br>Backend<br>   |<br>   v<br>External website</pre><p>The backend controls the request.</p><h3>Rule 2: Validate every URL before fetching</h3><pre>User URL<br>↓<br>URL validation<br>↓<br>Fetch only safe destinations</pre><p>This prevents SSRF.</p><h3>Rule 3: Never save preview information provided by the client</h3><p>Instead:</p><pre>Client sends post text<br>↓<br>Backend extracts URL<br>↓<br>Backend validates URL<br>↓<br>Backend fetches website<br>↓<br>Backend generates preview<br>↓<br>Database stores preview</pre><p>This prevents spoofed preview data.</p><p>A URL preview feature is not only a UI feature. It is also a server-side security feature because the application is making requests on behalf of users and storing information that other users will trust.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9697830c9cde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding target="_blank" and rel="noopener noreferrer" in HTML Links]]></title>
            <link>https://medium.com/@natsuko-dev-blog/understanding-target-blank-and-rel-noopener-noreferrer-in-html-links-ba806fb4fa25?source=rss-0b5502fff6f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba806fb4fa25</guid>
            <dc:creator><![CDATA[Natsuko]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 00:13:55 GMT</pubDate>
            <atom:updated>2026-07-09T00:13:55.475Z</atom:updated>
            <content:encoded><![CDATA[<h3>Table of Contents</h3><ol><li><a href="https://chatgpt.com/c/6a4ee335-23d0-83e8-8145-2da23d087084#target_blank-opening-links-in-a-new-tab">target=&quot;_blank&quot;: Opening Links in a New Tab</a></li><li><a href="https://chatgpt.com/c/6a4ee335-23d0-83e8-8145-2da23d087084#rel-attribute-meaning-and-purpose">rel Attribute: Meaning and Purpose</a></li><li><a href="https://chatgpt.com/c/6a4ee335-23d0-83e8-8145-2da23d087084#noopener-preventing-tab-nabbing-attacks">noopener: Preventing Tab-Nabbing Attacks</a></li><li><a href="https://chatgpt.com/c/6a4ee335-23d0-83e8-8145-2da23d087084#noreferrer-controlling-the-http-referer-header">noreferrer: Controlling the HTTP Referer Header</a></li><li>Why noopener noreferrer Are Commonly Used Together</li></ol><h3>target=&quot;_blank&quot;: Opening Links in a New Tab</h3><p>target=&quot;_blank&quot; is a standard HTML &lt;a&gt; element attribute. It is not specific to React.</p><pre>&lt;a href=&quot;https://example.com&quot; target=&quot;_blank&quot;&gt;<br>  Visit Example<br>&lt;/a&gt;</pre><p>target=&quot;_blank&quot; instructs the browser to open the linked page in a new browser tab (or window, depending on browser settings) instead of replacing the current page.</p><p>This is commonly used when users should keep their current page open, such as when linking to external websites from a feed, article, or application.</p><p>Example:</p><pre>&lt;a <br>  href=&quot;https://example.com&quot; <br>  target=&quot;_blank&quot; <br>  rel=&quot;noopener noreferrer&quot;<br>&gt;<br>  External Link<br>&lt;/a&gt;</pre><p>When this link is clicked:</p><ol><li>The external website opens in a new tab.</li><li>The original application tab remains open.</li><li>The rel attribute provides security and privacy protections.</li></ol><h3>rel Attribute: Meaning and Purpose</h3><p>rel stands for <strong>relationship</strong>.</p><p>It is a standard HTML attribute used to describe the relationship between the current document and the linked resource.</p><p>The rel attribute is used with both &lt;a&gt; and &lt;link&gt; elements.</p><p>Examples:</p><pre>&lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot;&gt;</pre><p>Here, rel=&quot;stylesheet&quot; tells the browser that the linked file is a stylesheet.</p><p>For anchor (&lt;a&gt;) elements, common values include:</p><p>ValuePurposenoopenerPrevents the opened page from accessing the original page through window.openernoreferrerPrevents sending the Referer HTTP header and also provides noopener behavior in modern browsersnofollowProvides search engine instructions not to treat the link as an endorsementauthorIndicates that the linked resource represents the author</p><p>For external links opened with target=&quot;_blank&quot;, the recommended pattern is:</p><pre>&lt;a href=&quot;https://example.com&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;<br>  External Site<br>&lt;/a&gt;</pre><h3>noopener: Preventing Tab-Nabbing Attacks</h3><h3>The window.opener Problem</h3><p>When a page opens another page using target=&quot;_blank&quot;, the newly opened page may receive a reference to the original page through a JavaScript object called:</p><pre>window.opener</pre><p>window.opener allows the new tab to communicate with and control the page that opened it.</p><p>For example, without protection:</p><pre>window.opener.location = &quot;https://fake-login-page.com&quot;;</pre><p>This code can change the URL of the original tab.</p><h3>How Tab-Nabbing Works</h3><p>A tab-nabbing attack happens when a malicious website uses this behavior to replace the original page with a phishing page.</p><p>The attack flow:</p><ol><li>A user visits an application:</li></ol><pre>https://yourapp.com</pre><ol><li>The application contains an external link:</li></ol><pre>&lt;a href=&quot;https://evil.com&quot; target=&quot;_blank&quot;&gt;<br>  Visit Website<br>&lt;/a&gt;</pre><ol><li>The user clicks the link.</li><li>evil.com opens in a new tab.</li><li>The new page runs:</li></ol><pre>window.opener.location = &quot;https://fake-login-page.com&quot;;</pre><ol><li>The original application tab is silently redirected to a fake login page.</li><li>When the user returns to the original tab, they see a login page that looks legitimate and may enter their credentials.</li></ol><p>This attack is called <strong>tab-nabbing</strong> because the new tab “nabs” control of the original tab.</p><h3>How rel=&quot;noopener&quot; Fixes the Problem</h3><p>Adding noopener prevents the browser from providing the new page with a reference to the original page.</p><p>Example:</p><pre>&lt;a <br>  href=&quot;https://example.com&quot; <br>  target=&quot;_blank&quot; <br>  rel=&quot;noopener&quot;<br>&gt;<br>  External Link<br>&lt;/a&gt;</pre><p>With noopener:</p><ul><li>window.opener is not available.</li><li>The opened page cannot access the original page.</li><li>The original tab cannot be redirected by the external page.</li></ul><p>The attack becomes impossible because the connection between the two tabs is removed.</p><h3>noreferrer: Controlling the HTTP Referer Header</h3><h3>What Is the Referer Header?</h3><p>When a browser requests a new page, it often sends an HTTP header called:</p><pre>Referer</pre><p>(Referer is intentionally misspelled in the HTTP standard.)</p><p>This header tells the destination server where the visitor came from.</p><p>Example:</p><p>A user is viewing:</p><pre>https://yourapp.com/post/12345</pre><p>The page contains:</p><pre>&lt;a href=&quot;https://example.com&quot; target=&quot;_blank&quot;&gt;<br>  External Link<br>&lt;/a&gt;</pre><p>After the user clicks the link, the request to example.com may include:</p><pre>Referer: https://yourapp.com/post/12345</pre><p>The external website can see the exact page that sent the visitor.</p><h3>Why the Referer Header Can Be a Privacy Concern</h3><p>Sending the Referer header can reveal information to external websites, such as:</p><ul><li>Internal URL structures</li><li>Specific pages viewed by users</li><li>Private or sensitive page paths</li><li>Which application page generated the traffic</li></ul><p>For example, an external site may learn that a visitor came from:</p><pre>https://yourapp.com/private-post/user123</pre><p>which exposes information that was not intended to leave the application.</p><h3>How rel=&quot;noreferrer&quot; Works</h3><p>noreferrer tells the browser not to send the Referer header when following the link.</p><p>Example:</p><pre>&lt;a <br>  href=&quot;https://example.com&quot; <br>  target=&quot;_blank&quot; <br>  rel=&quot;noreferrer&quot;<br>&gt;<br>  External Link<br>&lt;/a&gt;</pre><p>The destination server receives the request without information about the previous page.</p><p>Instead of:</p><pre>Referer: https://yourapp.com/post/12345</pre><p>the request contains no referrer information.</p><h3>Why noopener noreferrer Are Used Together</h3><p>The recommended pattern for external links opened in a new tab is:</p><pre>&lt;a <br>  href=&quot;https://example.com&quot; <br>  target=&quot;_blank&quot; <br>  rel=&quot;noopener noreferrer&quot;<br>&gt;<br>  External Link<br>&lt;/a&gt;</pre><p>Each attribute solves a different problem:</p><p>AttributeProtects Againsttarget=&quot;_blank&quot;Opens the link in a new tabnoopenerPrevents tab-nabbing by removing window.opener accessnoreferrerPrevents leaking the previous page URL through the Referer header</p><p>Modern browsers treat noreferrer as also providing noopener behavior, but including both explicitly is the standard practice because it clearly communicates intent and improves compatibility with older browsers.</p><p>Therefore, when using target=&quot;_blank&quot; for external links, the standard secure implementation is:</p><pre>&lt;a <br>  href=&quot;https://external-site.com&quot; <br>  target=&quot;_blank&quot; <br>  rel=&quot;noopener noreferrer&quot;<br>&gt;<br>  Open External Site<br>&lt;/a&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba806fb4fa25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why You Can’t Just Modify State Directly in React]]></title>
            <link>https://medium.com/@natsuko-dev-blog/why-you-cant-just-modify-state-directly-in-react-b92df8d8bfa0?source=rss-0b5502fff6f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b92df8d8bfa0</guid>
            <dc:creator><![CDATA[Natsuko]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 23:15:38 GMT</pubDate>
            <atom:updated>2026-06-08T23:15:38.459Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re new to React, one of the first rules you’ll hit is: <strong>never mutate state directly</strong>. This post explains the <em>why</em> behind the rule, not just the rule itself.</p><h3>The Problem: React Detects Changes by Reference</h3><p>React does not deep-scan your state on every render to look for changes inside objects or arrays. That would be expensive. Instead, it checks whether the <strong>reference</strong> changed — essentially the memory address pointing to the value.</p><p>Think of it like a label attached to a box. React looks at the label, not what’s inside the box.</p><pre>const a = { name: &quot;Alice&quot; };<br>const b = a;           // b points to the SAME box<br>b.name = &quot;Bob&quot;;        // modify the contents<br><br>console.log(a === b);  // true - same reference, same label</pre><p>React sees a === b and concludes: <em>&quot;nothing changed, no need to re-render.&quot;</em> Even though the name is now &quot;Bob&quot;.</p><h3>A Concrete React Example</h3><p>Say you have a list of users in state:</p><pre>const [users, setUsers] = useState([<br>  { id: 1, name: &quot;Alice&quot; },<br>  { id: 2, name: &quot;Bob&quot; },<br>]);</pre><h3>❌ Wrong — mutating in place</h3><pre>function handleRename() {<br>  users[0].name = &quot;Eve&quot;;  // mutate the existing array<br>  setUsers(users);        // pass the same array reference<br>}</pre><p>React compares the old reference with the new reference:</p><pre>old reference: 0x1a2b  →  [ {id:1, name:&quot;Alice&quot;}, ... ]<br>new reference: 0x1a2b  →  [ {id:1, name:&quot;Eve&quot;},   ... ]  ← same address!</pre><p>They’re identical in React’s eyes. <strong>No re-render. The UI stays stuck on “Alice.”</strong></p><h3>✅ Correct — replacing with a new array</h3><pre>function handleRename() {<br>  setUsers(prevUsers =&gt;<br>    prevUsers.map(user =&gt;<br>      user.id === 1<br>        ? { ...user, name: &quot;Eve&quot; }  // new object for the changed user<br>        : user                      // same reference for unchanged users<br>    )<br>  );<br>}</pre><p>Now React sees:</p><pre>old reference: 0x1a2b  →  [ {id:1, name:&quot;Alice&quot;}, ... ]<br>new reference: 0x3c4d  →  [ {id:1, name:&quot;Eve&quot;},   ... ]  ← different address!</pre><p>Different reference → React re-renders → UI updates to “Eve”.</p><h3>The Tools That Produce a New Reference</h3><p>These operations are your friends in React state updates — they always return something new:</p><p>OperationExampleResult.map()arr.map(x =&gt; ...)New array.filter()arr.filter(x =&gt; ...)New arrayArray spread[...arr, newItem]New arrayObject spread{ ...obj, key: value }New object</p><p>These are the operations that mutate in place — avoid them on state:</p><p>OperationExampleProblemIndex assignmentarr[0] = xSame array reference.push() / .pop()arr.push(x)Same array referenceProperty assignmentobj.key = valueSame object reference</p><h3>One More Gotcha: Nested Objects</h3><p>Spreading an object only creates a <strong>shallow</strong> copy. Nested objects still share a reference:</p><pre>const [form, setForm] = useState({<br>  user: { name: &quot;Alice&quot;, age: 25 },<br>  submitted: false,<br>});<br><br>// ❌ Wrong - the nested `user` object is still the same reference<br>setForm(prev =&gt; ({ ...prev, user: prev.user }));<br>prev.user.name = &quot;Eve&quot;;  // mutates the shared nested object<br>// ✅ Correct - spread both levels<br>setForm(prev =&gt; ({<br>  ...prev,<br>  user: { ...prev.user, name: &quot;Eve&quot; },<br>}));</pre><h3>Why Does React Work This Way?</h3><p>Because it makes React <strong>fast</strong>. Instead of recursively scanning every field of every object in your state tree on every render, React just compares references — an O(1) check. The trade-off is that <em>you</em>, the developer, are responsible for producing new references when data changes. Once you internalize this, .map(), .filter(), and spread become second nature.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b92df8d8bfa0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authentication in Web Applications: ①Sessions based vs ②JWT]]></title>
            <link>https://medium.com/@natsuko-dev-blog/authentication-in-web-applications-%E2%91%A0sessions-based-vs-%E2%91%A1jwt-49d1a87339da?source=rss-0b5502fff6f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/49d1a87339da</guid>
            <dc:creator><![CDATA[Natsuko]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 21:05:47 GMT</pubDate>
            <atom:updated>2026-06-06T21:05:47.536Z</atom:updated>
            <content:encoded><![CDATA[<h3>Table of Contents</h3><ol><li>Authentication vs Authorization</li><li>Signup and Login Fundamentals</li><li>Session-Based Authentication<br>Login Flow<br>Cookie Storage<br>Logout<br>Stateful Authentication</li><li>JWT-Based Authentication<br>Login Flow<br>JWT Structure<br>Signature Verification<br>Logout<br>Stateless Authentication</li><li>JWT Storage Options<br>JWT in localStorage<br>JWT in HttpOnly Cookies</li><li>Session Authentication vs JWT Authentication</li><li>Common Misconceptions</li><li>Other Authentication Types Worth Knowing</li></ol><h3>1. Authentication vs Authorization</h3><p>Authentication answers: <strong>Who are you?</strong><br>Authorization answers: <strong>What are you allowed to do?</strong></p><p>Authentication happens first. Authorization happens after authentication.</p><h3>2. Signup and Login Fundamentals</h3><h3>Signup (User Creation)</h3><p>Signup creates a user record in the database.</p><pre>POST /signup/<br><br>{<br>  &quot;email&quot;: &quot;alice@example.com&quot;,<br>  &quot;password&quot;: &quot;secret123&quot;<br>}</pre><p>Database:</p><pre>users table<br><br>id | email              | password_hash<br>-----------------------------------------<br>1  | alice@example.com  | x7k29...</pre><p>Important points:</p><ul><li>Password is never stored in plain text</li><li>Only a hashed password is stored</li><li>This happens at signup, not login</li></ul><h3>Login (Authentication)</h3><p>Login does NOT create a user.</p><pre>POST /login/<br><br><br>{<br>  &quot;email&quot;: &quot;alice@example.com&quot;,<br>  &quot;password&quot;: &quot;secret123&quot;<br>}</pre><p>Server does:</p><ul><li>Find user by email</li><li>Verify password</li><li>Issue authentication credential (session or JWT)</li></ul><h3>3. Session-Based Authentication</h3><h3>Login Flow</h3><p>After verifying credentials:</p><p>Server creates a session record:</p><pre>sessions table<br><br>session_id   | user_id<br>-----------------------<br>abc123       | 1</pre><p>Response:</p><pre>Set-Cookie: sessionid=abc123; HttpOnly; Secure</pre><h3>Cookie Storage (Important Clarification)</h3><p>When the browser receives:</p><pre>Set-Cookie: sessionid=abc123</pre><p>it stores it in the browser’s <strong>internal cookie storage</strong>, managed by the browser itself.</p><p>Conceptually:</p><pre>Domain: myapp.com<br>sessionid = abc123</pre><p>JavaScript does NOT manually store this.</p><h3>Automatic Cookie Sending</h3><p>On future requests:</p><pre>Cookie: sessionid=abc123</pre><p>The browser attaches this automatically.</p><p>No frontend code is needed.</p><h3>Logout</h3><p>Server invalidates session:</p><pre>DELETE session abc123</pre><p>After logout:</p><ul><li>The session is removed from server storage</li><li>The cookie may still exist in the browser</li><li>But it becomes useless</li></ul><h3>Stateful Authentication</h3><p>Session-based auth is <strong>stateful</strong> because:</p><ul><li>Server stores session state</li><li>Server must look up session_id every request</li></ul><p>Flow:</p><pre>session_id → database lookup → user_id</pre><h3>4. JWT-Based Authentication</h3><h3>Login Flow</h3><p>After verifying credentials:</p><p>Server generates JWT:</p><p>Payload:</p><pre>{<br>  &quot;user_id&quot;: 1,<br>  &quot;email&quot;: &quot;alice@example.com&quot;<br>}</pre><p>Then signs it:</p><pre>header.payload.signature</pre><p>Example token:</p><pre>eyJhbGciOiJIUzI1Ni...</pre><h3>JWT Structure</h3><p>A JWT has three parts:</p><pre>header.payload.signature</pre><ul><li>Header: algorithm metadata</li><li>Payload: user information</li><li>Signature: security proof</li></ul><h3>Signature Verification (Critical Concept)</h3><p>Server verifies JWT like this:</p><ol><li>Extract header + payload + signature</li><li>Recompute expected signature using secret key</li><li>Compare signatures</li></ol><p>Conceptually:</p><pre>if signature == HMAC(header + payload + secret):<br>    valid<br>else:<br>    invalid</pre><h3>Why signature matters</h3><p>If someone changes:</p><pre>user_id: 1 → user_id: 999</pre><p>the signature no longer matches.</p><p>This prevents tampering.</p><p>Important:</p><ul><li>JWT payload is NOT encrypted</li><li>It is only encoded and readable</li><li>Security comes from the signature</li></ul><h3>Logout</h3><p>JWT systems usually do NOT store sessions on the server.</p><p>So logout is typically:</p><ul><li>Delete token on client side</li><li>Or expire cookie/token</li></ul><p>There is often no server-side record to delete.</p><h3>Stateless Authentication</h3><p>JWT auth is <strong>stateless</strong> because:</p><ul><li>Server does not store session data</li><li>Each request contains everything needed</li></ul><p>Flow:</p><pre>JWT → verify signature → extract user info</pre><p>No database session lookup is required.</p><h3>5. JWT Storage Options</h3><h3>5.1 JWT in localStorage</h3><p>Flow:</p><ol><li>Server returns token</li><li>Frontend stores token</li><li>Frontend attaches token manually</li></ol><p>Example:</p><pre>localStorage.setItem(&quot;token&quot;, jwt);<br><br>fetch(&quot;/api/data&quot;, {<br>  headers: {<br>    Authorization: `Bearer ${jwt}`<br>  }<br>});</pre><p>Key points:</p><ul><li>Browser does NOT attach token automatically</li><li>Developer must implement request logic</li><li>Common in older SPA patterns</li></ul><h3>5.2 JWT in HttpOnly Cookies</h3><p>Flow:</p><ol><li>Server sets cookie</li><li>Browser stores cookie automatically</li><li>Browser sends cookie automatically</li></ol><p>Response:</p><pre>Set-Cookie: access_token=eyJhbG...; HttpOnly; Secure</pre><p>On future requests:</p><pre>Cookie: access_token=eyJhbG...</pre><p>Important:</p><ul><li>JavaScript cannot read HttpOnly cookies</li><li>More resistant to XSS token theft</li></ul><h3>Critical Clarification</h3><p>The browser treats:</p><pre>sessionid=abc123</pre><p>and</p><pre>access_token=eyJhbG...</pre><p>exactly the same way.</p><p>The browser does not know or care what is inside the cookie.</p><h3>6. Session Authentication vs JWT Authentication</h3><p>FeatureSessionJWTStored where?ServerClient (token)Server stateYesNoValidationDB lookupSignature verificationScalabilityRequires session storageStateless</p><p>Core idea:</p><ul><li>Session = “Look up my identity on the server”</li><li>JWT = “Trust this signed token”</li></ul><h3>7. Common Misconceptions</h3><h3>Misconception 1: POST creates database records</h3><p>False.</p><p>POST means:</p><blockquote><em>Perform an action on the server</em></blockquote><p>Login is an action, not a creation event.</p><h3>Misconception 2: JWT must be stored in localStorage</h3><p>False.</p><p>JWT can be stored in:</p><ul><li>localStorage</li><li>memory</li><li>cookies (including HttpOnly cookies)</li></ul><h3>Misconception 3: JWT contains sensitive data</h3><p>False.</p><p>JWT should NOT contain:</p><ul><li>passwords</li><li>password hashes</li></ul><p>It is readable by anyone holding the token.</p><h3>Misconception 4: Frontend always attaches authentication data</h3><p>Only true for:</p><ul><li>localStorage + Authorization header</li></ul><p>Not true for:</p><ul><li>HttpOnly cookie systems</li><li>session cookies</li></ul><h3>8. Other Authentication Types Worth Knowing</h3><p>TypeHow it worksCommon use caseBasic AuthAuthorization: Basic base64(email:password) on every requestSimple internal APIsAPI KeyStatic key in header or query paramThird-party APIs (Cloudinary, SendGrid)OAuth 2.0Login via external provider (Google, GitHub)Social loginmTLSMutual certificate authenticationBanking / enterprise systems</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49d1a87339da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Implement Multi-Image Upload in Python Django]]></title>
            <link>https://medium.com/@natsuko-dev-blog/how-to-implement-multi-image-upload-in-python-django-adff6d1bc2a6?source=rss-0b5502fff6f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/adff6d1bc2a6</guid>
            <dc:creator><![CDATA[Natsuko]]></dc:creator>
            <pubDate>Fri, 05 Jun 2026 00:45:48 GMT</pubDate>
            <atom:updated>2026-06-05T00:45:48.296Z</atom:updated>
            <content:encoded><![CDATA[<h3>Table of Contents</h3><ol><li>Why This Is Not Trivial</li><li>Database Design: The PostImage Table</li><li>ForeignKey Anatomy: related_name, null=True, blank=True</li><li>HTTP Fundamentals: multipart/form-data vs JSON vs Base64</li><li>Django QueryDict: .get() vs .getlist()</li><li>Two Serializers: Write vs Read</li><li>The DTO Pattern</li><li>Python Type Hints for File Uploads</li><li>The N+1 Problem and prefetch_related</li><li>Image Validation: Where and How</li><li>Complete Workflow: Frontend to Response</li><li>API Design: Update vs Delete for Images</li></ol><h3>1. Why This Is Not Trivial</h3><p>At first glance, supporting multiple images per post seems simple — just allow more than one file upload. In practice, it requires deliberate decisions at every layer of the stack:</p><ul><li>The <strong>database schema</strong> must be normalized (one image per row, not multiple values in one cell)</li><li>The <strong>HTTP request format</strong> must be multipart/form-data, not JSON</li><li>The <strong>view</strong> must extract files separately from text fields</li><li>The <strong>serializer</strong> only handles text — file validation is manual</li><li>The <strong>DAO</strong> must loop over files and create one database row per image</li><li>The <strong>read serializer</strong> must join data from two tables into one API response</li></ul><p>Miss any of these and you end up with a subtle bug — for example, only the last uploaded image being saved because Django’s QueryDict.get() discards all but the last value when a key appears multiple times.</p><p>This post covers every layer from scratch.</p><h3>2. Database Design: The PostImage Table</h3><h3>The wrong approach: one column, multiple values</h3><p>The naive approach is to store all image URLs in a single column, either as one URL or as a comma-separated string:</p><pre>class Post(models.Model):<br>    content = models.TextField()<br>    image = models.CharField(max_length=500, blank=True, null=True)<br>    # for multiple: &quot;url1.jpg,url2.jpg,url3.jpg&quot;  ← antipattern</pre><p>This violates <strong>First Normal Form (1NF)</strong>: every cell in a database table must hold exactly one atomic value. Storing multiple values in one cell causes real problems:</p><ul><li>You cannot filter or query on individual images</li><li>You cannot delete one image without string manipulation</li><li>You cannot attach metadata (display order, caption) to each image</li><li>Every ORM and admin tool assumes one value per cell</li></ul><h3>The correct approach: a related table</h3><p>Create a separate PostImage table where each row represents one image:</p><pre>class Post(models.Model):<br>    content = models.TextField()<br>    # no image field here<br><br><br>class PostImage(models.Model):<br>    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name=&quot;images&quot;)<br>    image = models.CharField(max_length=500)</pre><pre>posts:           id | content<br>                  1 | &quot;Good morning&quot;<br><br>posts_postimage:  id | post_id | image<br>                   1 |    1    | &quot;cdn.example.com/a.jpg&quot;<br>                   2 |    1    | &quot;cdn.example.com/b.jpg&quot;<br>                   3 |    1    | &quot;cdn.example.com/c.jpg&quot;</pre><p>One Post row. Three PostImage rows. Each cell holds exactly one value. You can add, remove, or reorder images independently without touching the Post row at all.</p><p>In production, the image field is typically a CloudinaryField (if using Cloudinary) or an S3FileField / ImageField with S3 storage backend (if using AWS S3). The choice of cloud storage does not change the schema design — PostImage remains a separate table regardless.</p><h3>3. ForeignKey Anatomy</h3><pre>class PostImage(models.Model):<br>    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name=&quot;images&quot;)<br>    image = models.CharField(max_length=500)</pre><h3>ForeignKey(Post, ...)</h3><p>Creates a many-to-one relationship: many PostImage rows can point to one Post. In the database this becomes a post_id integer column in the postimage table.</p><h3>on_delete=models.CASCADE</h3><p>Defines what happens when the parent Post is deleted. CASCADE means: automatically delete all related PostImage rows. Other common options:</p><p>OptionBehaviorCASCADEDelete all related rowsSET_NULLSet the FK column to NULL (requires null=True)PROTECTPrevent deletion if related rows exist</p><h3>related_name=&quot;images&quot;</h3><p>Without this, accessing a post’s images from the Post side uses Django&#39;s ugly auto-generated name:</p><pre>post.postimage_set.all()   # auto-generated default</pre><p>With related_name=&quot;images&quot;:</p><pre>post.images.all()          # clean and readable</pre><h3>null=True vs blank=True — they are completely different</h3><p>This is one of the most common Django confusions. They operate at two different layers:</p><p>null=Trueblank=True<strong>Layer</strong>DatabasePython / validation<strong>Effect</strong>Column allows SQL NULLSerializer / form accepts empty value</p><pre># A completely optional text field<br>bio = models.TextField(null=True, blank=True)<br># null=True  → the database column can store NULL<br># blank=True → the serializer will not complain if the field is omitted</pre><p>In PostImage, neither is needed on image — a PostImage row should only ever exist when there is an image. A PostImage with no image is meaningless. If you try to create one without an image, it should fail loudly.</p><p>The ForeignKey also does not need null=True — every PostImage must belong to a Post.</p><h3>4. HTTP Fundamentals: multipart/form-data vs JSON vs Base64</h3><h3>The fundamental rule</h3><p>HTTP requests that include files <strong>must</strong> use multipart/form-data. JSON cannot carry binary data. This applies to the entire request body — if any file is present, even the text fields travel as form fields, not JSON.</p><pre>multipart/form-data request body:<br>  --boundary<br>  Content-Disposition: form-data; name=&quot;content&quot;<br><br>Good morning<br>  --boundary<br>  Content-Disposition: form-data; name=&quot;tags&quot;<br>  life<br>  --boundary<br>  Content-Disposition: form-data; name=&quot;images&quot;; filename=&quot;sunrise.jpg&quot;<br>  Content-Type: image/jpeg<br>  &lt;binary bytes&gt;<br>  --boundary--</pre><p>The text fields (content, tags) travel as form fields, not JSON. Django parses them into request.data just like any other text fields — so nothing about the backend handling changes for text.</p><h3>What about requests with no files?</h3><p>Even when the user posts without images, the endpoint must still receive multipart/form-data — because the backend uses request.data.getlist(&quot;tags&quot;) which only works on a QueryDict (see Section 5). The frontend must always use FormData for this endpoint:</p><pre>const formData = new FormData();<br>formData.append(&quot;content&quot;, &quot;Good morning&quot;);<br>formData.append(&quot;tags&quot;, &quot;life&quot;);<br>formData.append(&quot;tags&quot;, &quot;travel&quot;);<br>// Only append images if the user selected any<br>selectedFiles.forEach(file =&gt; formData.append(&quot;images&quot;, file));<br><br><br>fetch(&quot;/posts/&quot;, {<br>    method: &quot;POST&quot;,<br>    body: formData,<br>    // DO NOT set Content-Type manually - the browser sets it with the boundary string<br>});</pre><p>Using FormData makes the request multipart/form-data automatically, whether or not files are included.</p><h3>The response is always JSON</h3><p>When the server responds, images have already been uploaded to Cloudinary / S3 and are stored as URL strings. Everything in the response is text, so standard JSON works:</p><pre>{<br>  &quot;id&quot;: 42,<br>  &quot;content&quot;: &quot;Good morning&quot;,<br>  &quot;images&quot;: [<br>    &quot;https://cdn.example.com/sunrise.jpg&quot;,<br>    &quot;https://cdn.example.com/coffee.jpg&quot;<br>  ]<br>}</pre><h3>Why not use Base64 to embed images in JSON?</h3><p>Base64 is an encoding scheme that converts binary data into ASCII text using 64 safe characters (A–Z, a–z, 0–9, +, /). It was invented so binary data could be transmitted over text-only protocols (originally email).</p><p>The conversion takes every <strong>3 bytes</strong> of binary and converts them into <strong>4 characters</strong>:</p><pre>Binary (3 bytes, 24 bits):   01001101  01100001  01101110<br><br>Split into 4 × 6-bit groups: 010011  010110  000101  101110<br><br>Map to Base64 alphabet:         T       W       F       u<br><br>Result:                       &quot;TWFu&quot;</pre><p>3 bytes in, 4 characters out — always a <strong>33% size increase</strong>.</p><pre>1 MB image  → 1.33 MB base64 string<br>5 MB image  → 6.67 MB base64 string</pre><p>Using base64 to embed images inside JSON means:</p><ol><li><strong>Browser encodes</strong> binary → base64 string before sending</li><li><strong>33% more data</strong> travels over the network</li><li><strong>Server must decode</strong> base64 string → binary before uploading to Cloudinary / S3</li><li>The entire string must live in RAM while being processed</li></ol><p>With multipart/form-data, the binary file is sent as-is. No encoding, no decoding, no size inflation. The server streams the binary directly to cloud storage. Base64 is only justified in narrow cases where multipart is impossible (some WebSocket APIs, embedding tiny images in CSS).</p><h3>5. Django QueryDict</h3><h3>Why a regular Python dict is not enough for HTTP</h3><p>A regular Python dict maps each key to exactly one value. But HTTP form submissions allow the same key to appear multiple times:</p><pre>content=Hello&amp;tags=news&amp;tags=local&amp;tags=sports</pre><p>A regular dict cannot represent this — the second tags would overwrite the first. Django&#39;s QueryDict solves this by storing all values for a key internally as a list, while offering two access methods:</p><pre>request.data.get(&quot;tags&quot;)        # → &quot;sports&quot;                       (last value only)<br>request.data.getlist(&quot;tags&quot;)    # → [&quot;news&quot;, &quot;local&quot;, &quot;sports&quot;]    (all values)</pre><p>This is why .getlist() exists, and why using .get() for a repeated field silently discards all but the last value — exactly the bug that caused only one image to be saved.</p><h3>When JSON is sent</h3><p>When the frontend sends application/json, request.data becomes a regular Python dict, not a QueryDict:</p><pre>request.data.getlist(&quot;tags&quot;)   # → AttributeError: &#39;dict&#39; object has no attribute &#39;getlist&#39;</pre><p>With JSON, multiple values are sent as a JSON array inside the value, so a regular .get() already returns the full list:</p><pre>{&quot;content&quot;: &quot;Hello&quot;, &quot;tags&quot;: [&quot;news&quot;, &quot;local&quot;, &quot;sports&quot;]}</pre><pre>request.data.get(&quot;tags&quot;)   # → [&quot;news&quot;, &quot;local&quot;, &quot;sports&quot;]</pre><p>Summary:</p><p>multipart/form-dataapplication/jsonrequest.data typeQueryDictdictMultiple valuesRepeated keys: tags=a&amp;tags=bJSON array: &quot;tags&quot;: [&quot;a&quot;,&quot;b&quot;].get(&quot;tags&quot;)Last value onlyFull array.getlist(&quot;tags&quot;)Full listCrashes (AttributeError)</p><h3>6. Two Serializers: Write vs Read</h3><p>A standard DRF pattern is to use separate serializers for writing (input validation) and reading (output shaping).</p><h3>Write serializer — input validation only</h3><pre>class PostCreateUpdateSerializer(serializers.ModelSerializer):<br>    content = serializers.CharField(max_length=1000)<br>    tags = serializers.ListField(child=serializers.CharField(), required=False)<br><br>class Meta:<br>        model = Post<br>        fields = [&quot;content&quot;, &quot;tags&quot;, &quot;pinned&quot;, &quot;anonymous&quot;]</pre><p>Used when the client sends data (POST, PATCH). It validates incoming text fields only. It never sees image files — those are handled separately in the view (see Section 11). It does not include id, likes, created_at, or comments — the client is not allowed to set those.</p><h3>Read serializer — output shaping</h3><pre>class PostSerializer(serializers.ModelSerializer):<br>    images = serializers.SerializerMethodField()<br>    comments = CommentSerializer(many=True, read_only=True)<br><br>class Meta:<br>        model = Post<br>        fields = [&quot;id&quot;, &quot;content&quot;, &quot;images&quot;, &quot;likes&quot;, &quot;comments&quot;, &quot;created_at&quot;, ...]<br>    def get_images(self, obj):<br>        return [img.image for img in obj.images.all()]</pre><p>Used when the server returns data (GET). It shapes the full response. Note that images = SerializerMethodField() is <strong>not a database column</strong> — it is a computed field. The Post table has no images column. The serializer reaches into the related PostImage table via obj.images.all() and injects the results into the response. The client receives one merged JSON object even though the data came from two separate tables.</p><h3>7. The DTO Pattern</h3><h3>What is a DTO?</h3><p>DTO stands for <strong>Data Transfer Object</strong>. It is a plain Python object (typically a dataclass) whose only job is to carry data from one part of a system to another. It contains no business logic.</p><pre>from dataclasses import dataclass, field<br>from typing import Optional, List<br>from django.core.files.uploadedfile import InMemoryUploadedFile<br><br>@dataclass<br>class CreatePostData:<br>    user_id: int<br>    content: str<br>    images: List[InMemoryUploadedFile] = field(default_factory=list)<br>    tags: Optional[List[str]] = None<br>    pinned: bool = False</pre><h3>The “T” stands for Transfer, not Network Transfer</h3><p>A common misconception is that DTOs only travel between frontend and backend. In reality, a DTO is used anywhere structured data needs to be handed from one part of a system to another:</p><pre># Within a backend — DTO never leaves the server<br>View layer<br>  ↓  CreatePostData(...)<br>Service layer<br>  ↓  CreatePostData(...)<br>DAO layer<br>  ↓  writes to database<br><br><br># Within a frontend - DTO never leaves the browser<br>API response (JSON)<br>  ↓  converted into UserDTO { id, name }<br>UI component<br>  ↓  UserDTO passed to child component</pre><p>DTOs are used:</p><ul><li>Frontend ↔ Backend (across the network)</li><li>View → Service → DAO (within the backend)</li><li>One microservice → another microservice</li><li>One frontend module → another frontend module</li></ul><p>The key idea: <strong>a DTO exists whenever one part of a system needs to hand structured data to another part of the system</strong>, regardless of whether that transfer crosses the internet, crosses processes, or is entirely within one codebase.</p><h3>Why not just pass request everywhere?</h3><pre># BAD — passing request deep into the stack<br>class PostDao:<br>    def create_post(self, request):          # DAO now knows about HTTP<br>        content = request.data[&quot;content&quot;]    # tightly coupled</pre><p>If you pass the raw HTTP request object from the view all the way down to the DAO:</p><ul><li>The DAO and Service must know about HTTP — they shouldn’t</li><li>You cannot call create_post from a test, CLI command, or background task without constructing a fake HTTP request</li><li>Each layer loses its clear responsibility</li></ul><p>With a DTO, only the <strong>View</strong> knows about HTTP. Every layer below receives a plain Python object with clearly named fields.</p><h3>The DTO is not the database schema</h3><p>CreatePostData has an images field containing file objects — even though there is no images column on the Post table. The DTO carries everything needed for the operation. It is the <strong>DAO&#39;s responsibility</strong> to look at the DTO and decide which tables to write to:</p><pre>def create_post(post_data: CreatePostData) -&gt; Post:<br>    post = Post.objects.create(          # writes to Post table<br>        user_id=post_data.user_id,<br>        content=post_data.content,<br>    )<br>    for image_file in post_data.images:  # writes to PostImage table<br>        PostImage.objects.create(post=post, image=image_file)<br>    return post</pre><p>One DTO → two database tables. Only the DAO knows about this split. The View and Service are unaware of how the data is persisted.</p><h3>8. Python Type Hints</h3><p>Python is dynamically typed — variables have no declared type. Since Python 3.5, <strong>type hints</strong> can be added as documentation and for static analysis. They do not change runtime behavior.</p><h3>Core type hint vocabulary</h3><pre># str — exactly one string, always required<br>content: str<br><br># Optional[str] - one string or None<br># Shorthand for Union[str, None]<br>from typing import Optional<br>bio: Optional[str] = None<br># List[str] - a list of strings (zero or more)<br>from typing import List<br>tags: List[str]<br># Optional[List[str]] - a list or None<br>tags: Optional[List[str]] = None</pre><h3>Any — avoid it</h3><pre>from typing import Any<br>data: Any   # type checker ignores this entirely</pre><p>Any turns off type checking for that field. Use the actual type whenever known. For Django uploaded files, the correct type is:</p><pre>from django.core.files.uploadedfile import InMemoryUploadedFile<br>images: List[InMemoryUploadedFile]</pre><p>This tells the IDE exactly what the objects are and enables accurate autocompletion and error detection.</p><h3>Why List[InMemoryUploadedFile] and not List[str]</h3><p>At the time CreatePostData is constructed (inside the View), the images field holds <strong>file objects in memory</strong> — not strings. They become Cloudinary / S3 URL strings only after the DAO uploads them. Using List[str] would be factually wrong and mislead anyone reading the code.</p><h3>9. The N+1 Problem and prefetch_related</h3><h3>The N+1 problem</h3><p>Imagine fetching 10 posts for a newsfeed. For each post the serializer calls post.images.all(). Without any optimization, Django runs one SQL query per post:</p><pre>-- 1 query to get posts<br>SELECT * FROM posts ORDER BY created_at DESC LIMIT 10;<br><br>-- 10 separate queries, one per post&#39;s images<br>SELECT * FROM postimage WHERE post_id = 1;<br>SELECT * FROM postimage WHERE post_id = 2;<br>...<br>SELECT * FROM postimage WHERE post_id = 10;</pre><p>That is <strong>11 queries</strong> for one page. With 100 posts it becomes 101 queries. This is the <strong>N+1 problem</strong>: 1 query for the list + N queries for the related data.</p><h3>prefetch_related — the fix</h3><pre>Post.objects.prefetch_related(&quot;images&quot;).order_by(&quot;-created_at&quot;)[:10]</pre><p>Django now runs exactly <strong>2 queries</strong> regardless of how many posts are fetched:</p><pre>-- Query 1: get posts<br>SELECT * FROM posts ORDER BY created_at DESC LIMIT 10;<br><br>-- Query 2: get ALL images for those 10 posts at once<br>SELECT * FROM postimage WHERE post_id IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);</pre><p>Django distributes the results from query 2 into each Post object in memory. When the serializer later calls post.images.all(), it reads from that in-memory cache — zero additional database queries.</p><h3>Why “prefetch” and “related”</h3><ul><li><strong>prefetch</strong> — the data is loaded <em>in advance</em>, before anything asks for it</li><li><strong>related</strong> — it targets objects connected via ForeignKey, reverse FK, or ManyToMany</li></ul><h3>Does it fetch all posts’ images when you only want one post?</h3><p>No. prefetch_related on a single-post query only fetches images for that one post:</p><pre>SELECT * FROM postimage WHERE post_id IN (42);</pre><p>The benefit still applies — instead of lazy query execution at serialization time, it runs one clean query upfront.</p><h3>10. Image Validation</h3><h3>Two layers — defense in depth</h3><p>Best practice is to validate at both your server and at the cloud storage provider.</p><p><strong>Layer 1 — your view, before uploading to Cloudinary / S3:</strong></p><pre># TODO: confirm these limits with the team before shipping<br>_ALLOWED_IMAGE_TYPES = {&quot;image/jpeg&quot;, &quot;image/png&quot;, &quot;image/webp&quot;}<br>_MAX_IMAGE_SIZE_BYTES = 10 * 1024 * 1024   # needs team decision — placeholder: 10 MB<br>_MAX_IMAGES_PER_POST = 10                  # needs team decision — placeholder: 10<br><br>def _validate_images(images: list) -&gt; str | None:<br>    &quot;&quot;&quot;Return an error message if validation fails, else None.&quot;&quot;&quot;<br>    if len(images) &gt; _MAX_IMAGES_PER_POST:<br>        return f&quot;A post can have at most {_MAX_IMAGES_PER_POST} images.&quot;<br>    for f in images:<br>        if f.content_type not in _ALLOWED_IMAGE_TYPES:<br>            return f&quot;&#39;{f.name}&#39; is not a supported type (JPEG, PNG, WebP only).&quot;<br>        if f.size &gt; _MAX_IMAGE_SIZE_BYTES:<br>            return f&quot;&#39;{f.name}&#39; exceeds the size limit.&quot;<br>    return None</pre><p><strong>Layer 2 — Cloudinary / S3:</strong> rejects malformed files, corrupted headers, and unsupported formats.</p><h3>Why not use a serializer for file validation?</h3><p>DRF serializers work well for text fields but do not handle repeated file keys in multipart/form-data cleanly. The serializer and file validation are intentionally separate:</p><ul><li><strong>Serializer</strong> → validates text fields only (content, tags, pinned, anonymous)</li><li><strong>View</strong> → manually validates image files after extracting them from request.FILES</li></ul><p>File validation belongs in the view, as a manual step before the DTO is constructed.</p><h3>Why not rely on Cloudinary / S3 alone?</h3><ul><li>You waste an API call uploading a 100 MB file that should have been rejected instantly</li><li>Cloud error messages are technical and hard to surface to users cleanly</li><li>You have no control over what is and is not accepted</li></ul><h3>11. Complete Workflow: Frontend to Response</h3><h3>Forward: creating a post with images</h3><pre>FRONTEND<br>  User fills in the form, selects 2 photos, clicks &quot;Post&quot;<br><br>Sends: POST /posts/<br>  Content-Type: multipart/form-data<br>  content = &quot;Good morning&quot;<br>  tags    = &quot;life&quot;<br>  tags    = &quot;travel&quot;<br>  images  = sunrise.jpg  (binary)<br>  images  = coffee.jpg   (binary)<br>  Note: this is NOT JSON. Files cannot be sent as JSON.<br>  Even the text fields travel as multipart form fields, not JSON.<br><br>        ↓<br><br>VIEW<br>  Step 1 - Validate text fields via the write serializer:<br>    serializer = PostCreateUpdateSerializer(data=request.data)<br>    serializer.is_valid()<br>    request.data is a QueryDict (Django parsed the multipart body into this)<br>    After is_valid(), serializer.validated_data is a regular Python dict:<br>      {&quot;content&quot;: &quot;Good morning&quot;, &quot;pinned&quot;: False, ...}<br>  Step 2 - Extract files separately (serializer never touches files):<br>    images = request.FILES.getlist(&quot;images&quot;)<br>    → [&lt;InMemoryUploadedFile: sunrise.jpg&gt;, &lt;InMemoryUploadedFile: coffee.jpg&gt;]<br>    .getlist() is essential here - .get() would return only coffee.jpg<br>  Step 3 - Validate files manually:<br>    _validate_images(images)  → checks type, size, count<br>  Step 4 - Build ONE DTO combining ① validated text dict + ② file list:<br>    CreatePostData(<br>        user_id=7,<br>        content=&quot;Good morning&quot;,        ← from serializer.validated_data<br>        images=[sunrise.jpg, coffee.jpg], ← from request.FILES<br>        tags=[&quot;life&quot;, &quot;travel&quot;],<br>        pinned=False,<br>    )<br>    This is one plain Python object. Post data and image files live together.<br>    The DTO does not care about database schema - that is the DAO&#39;s concern.<br><br>        ↓<br><br>SERVICE<br>  Receives the same DTO - passes it through after business logic checks:<br>    - Is user allowed to pin?<br>    - Are tags valid? (length, profanity, count)<br>  Calls DAO with the unchanged DTO.<br><br>        ↓<br><br>DAO  ← the only layer that knows about database tables<br>  Splits the one DTO into two tables:<br>  ① INSERT into posts table:<br>      Post.objects.create(user_id=7, content=&quot;Good morning&quot;, ...)<br>      → post.id = 42<br>  ② Loop over images, INSERT into postimage table:<br>      PostImage.objects.create(post_id=42, image=sunrise.jpg)<br>        → uploads sunrise.jpg to Cloudinary/S3<br>        → saves URL in postimage row<br>      PostImage.objects.create(post_id=42, image=coffee.jpg)<br>        → uploads coffee.jpg to Cloudinary/S3<br>        → saves URL in postimage row<br>  Returns Post object (id=42)<br><br>        ↓<br><br>VIEW (back)<br>  PostSerializer(post).data<br>  → get_images(post) calls post.images.all()<br>  → returns [&quot;cdn.example.com/sunrise.jpg&quot;, &quot;cdn.example.com/coffee.jpg&quot;]<br>  Returns HTTP 201:<br>  {<br>    &quot;id&quot;: 42,<br>    &quot;content&quot;: &quot;Good morning&quot;,<br>    &quot;images&quot;: [&quot;cdn.example.com/sunrise.jpg&quot;, &quot;cdn.example.com/coffee.jpg&quot;],<br>    &quot;tags&quot;: [&quot;life&quot;, &quot;travel&quot;],<br>    &quot;likes&quot;: 0,<br>    &quot;comments&quot;: []<br>  }<br>  Note: the response IS JSON - images are now just URL strings,<br>  so everything can be serialized as JSON.<br><br>        ↓<br><br>FRONTEND<br>  Renders the post with both images.</pre><h3>Reverse: fetching posts (GET)</h3><pre>FRONTEND<br>  GET /posts/?page=1&amp;limit=10<br><br>↓<br>VIEW → SERVICE → DAO<br>  DAO runs 2 SQL queries via prefetch_related:<br>    Query 1: SELECT * FROM posts LIMIT 10<br>    Query 2: SELECT * FROM postimage WHERE post_id IN (42, 38, 35, ...)<br>  Django attaches image results to each Post object in memory.<br>  Returns a list of 10 Post objects.<br>        ↓<br>VIEW<br>  PostSerializer(posts, many=True)<br>  For each post, get_images() calls post.images.all() → reads from memory<br>  → zero additional database queries<br>  There is no &quot;merge step&quot; with a DTO here.<br>  The Post model object returned by the DAO already has .images<br>  loaded in memory via prefetch_related. The serializer reads both<br>  the Post fields and .images from that single object and produces<br>  one merged JSON per post.<br>  Returns HTTP 200:<br>  {<br>    &quot;posts&quot;: [<br>      {<br>        &quot;id&quot;: 42,<br>        &quot;content&quot;: &quot;Good morning&quot;,<br>        &quot;images&quot;: [&quot;cdn.example.com/sunrise.jpg&quot;, &quot;cdn.example.com/coffee.jpg&quot;]<br>      },<br>      {<br>        &quot;id&quot;: 38,<br>        &quot;content&quot;: &quot;Evening walk&quot;,<br>        &quot;images&quot;: []<br>      }<br>    ],<br>    &quot;page&quot;: 1,<br>    &quot;total_pages&quot;: 4<br>  }</pre><h3>12. API Design: Update vs Delete for Images</h3><p>When thinking about image operations, look at <strong>one image at a time</strong> — not the post’s image set as a whole. Each image is an independent resource.</p><p>What the user doesHTTP methodWhat it meansAttach a new photo to a postPOSTCreate a new PostImage rowRemove a specific photoDELETEDelete that one PostImage row&quot;Replace&quot; a photo—Does not exist — delete the old one, upload a new one</p><p>There is no meaningful “update a single image” operation. You never modify an existing image in-place — you remove it and upload a new one. This means <strong>no PATCH endpoint for images is needed</strong>.</p><p>The two endpoints that cover everything:</p><pre>POST   /posts/{post_id}/images/           → add new image(s)<br>DELETE /posts/{post_id}/images/{image_id}/ → remove one specific image</pre><p>This approach — looking at images one by one — is best practice because:</p><ul><li>Each endpoint does exactly one thing</li><li>Adding a new image never touches or risks deleting existing images</li><li>HTTP semantics are correct: POST creates, DELETE destroys</li><li>The user has full, granular control</li></ul><p>The alternative — treating the image set as a group and sending PATCH to replace all images at once — is simpler to implement but dangerous: a PATCH call with new images silently wipes all existing ones.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adff6d1bc2a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>