<?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 Abhishek Chaudhuri on Medium]]></title>
        <description><![CDATA[Stories by Abhishek Chaudhuri on Medium]]></description>
        <link>https://medium.com/@Abhiek187?source=rss-38566b972440------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*K6ha_Sv8KHzoukHT5nDzwA.png</url>
            <title>Stories by Abhishek Chaudhuri on Medium</title>
            <link>https://medium.com/@Abhiek187?source=rss-38566b972440------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 03:36:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Abhiek187/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[What Really Happens When You Use an MCP Server? (2026–07–28 Edition)]]></title>
            <link>https://medium.com/@Abhiek187/what-really-happens-when-you-use-an-mcp-server-2026-07-28-edition-b9d8b6b6356a?source=rss-38566b972440------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9d8b6b6356a</guid>
            <category><![CDATA[json-rpc]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[2026]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Abhishek Chaudhuri]]></dc:creator>
            <pubDate>Sun, 15 Nov 2026 03:12:31 GMT</pubDate>
            <atom:updated>2026-11-15T03:12:31.390Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Fred from Scooby Doo unmasking a ghost labeled “MCP Server”, revealing himself to be “POST Requests”" src="https://cdn-images-1.medium.com/max/359/0*a2P9vXcrKmj5AP3G.png" /><figcaption>I think this meme is truer than ever</figcaption></figure><blockquote>But even then, there’s still plenty to learn about [MCP servers]. And since this protocol is relatively new as of this writing, I’m sure plenty will change even a year later.</blockquote><p>Well, it’s only been 5 months, and things have changed a bit about how MCP servers work. The 2026–07–28 protocol was released, and with it, V2 of the TypeScript SDK.</p><p>I recommend checking out my <a href="https://medium.com/@Abhiek187/what-really-happens-when-you-use-an-mcp-server-d254073de48b">last article</a> on MCP servers to get a baseline understanding of how they work. Much of that information is still relevant, but the 2026 protocol changes quite a bit about how we set up and test MCP servers, so it warranted a follow-up article.</p><h3>Code Changes</h3><p>If you have an existing MCP server on the V1 TypeScript SDK, a codemod is available to handle some of the migrations. But supporting the 2026 protocol still requires manual changes.</p><pre>npx @modelcontextprotocol/codemod@latest v1-to-v2 .</pre><p>First, we need to install a couple of MCP dependencies. For my Express server, these were the dependencies I installed:</p><pre>npm i @modelcontextprotocol/express @modelcontextprotocol/node @modelcontextprotocol/server</pre><h4>MCP Tools</h4><p>The code for defining the MCP tools hasn’t changed too much. For example, here’s the code for my recipe details tool (notice that I bumped the version number):</p><pre>import { McpServer } from &quot;@modelcontextprotocol/server&quot;;<br>import z from &quot;zod&quot;;<br><br>import { CUISINES, MEAL_TYPES, SPICE_LEVELS } from &quot;../types/client/Recipe&quot;;<br><br>const MCP_NAME = &quot;ez-recipes&quot;;<br>const MCP_VERSION = &quot;1.1.0&quot;;<br><br>const createMcpServer = () =&gt; {<br>  const server = new McpServer(<br>    {<br>      name: MCP_NAME,<br>      version: MCP_VERSION,<br>    },<br>    {<br>      capabilities: {<br>        logging: {},<br>      },<br>    }<br>  );<br><br>  server.registerTool(<br>    `${MCP_NAME}_get_recipe_details`,<br>    {<br>      description: &quot;Get detailed information about a recipe by its ID&quot;,<br>      inputSchema: z.object({<br>        id: z<br>          .number()<br>          .int()<br>          .positive()<br>          .describe(&quot;A unique recipe ID that maps to spoonacular&#39;s recipe ID&quot;),<br>      }),<br>      outputSchema: z.object({<br>        // Only return fields useful to an LLM to save on context &amp; reduce hallucinations<br>        id: z.number(),<br>        name: z.string(),<br>        url: z.string().url().optional(),<br>        healthScore: z.number(),<br>        time: z.number(),<br>        servings: z.number(),<br>        summary: z.string(),<br>        types: z.array(z.enum(MEAL_TYPES)),<br>        spiceLevel: z.enum(SPICE_LEVELS),<br>        isVegetarian: z.boolean(),<br>        isVegan: z.boolean(),<br>        isGlutenFree: z.boolean(),<br>        isHealthy: z.boolean(),<br>        isCheap: z.boolean(),<br>        isSustainable: z.boolean(),<br>        culture: z.array(z.enum(CUISINES)),<br>        nutrients: z.array(<br>          z.object({<br>            name: z.string(),<br>            amount: z.number(),<br>            unit: z.string(),<br>          })<br>        ),<br>        ingredients: z.array(<br>          z.object({<br>            name: z.string(),<br>            amount: z.number(),<br>            unit: z.string(),<br>          })<br>        ),<br>        instructions: z.array(<br>          z.object({<br>            name: z.string(),<br>            steps: z.array(<br>              z.object({<br>                number: z.number(),<br>                step: z.string(),<br>                ingredients: z.array(z.string()),<br>                equipment: z.array(z.string()),<br>              })<br>            ),<br>          })<br>        ),<br>        averageRating: z.number().nullable().optional(),<br>        totalRatings: z.number().optional(),<br>        views: z.number().optional(),<br>      }),<br>      annotations: {<br>        readOnlyHint: true,<br>        destructiveHint: false,<br>        idempotentHint: true,<br>        openWorldHint: false,<br>      },<br>    },<br>    async ({ id }) =&gt; {<br>      // ...<br>    }<br>  );<br><br>  return server;<br>};</pre><p>This version of the SDK supports Zod V4, so we no longer need to import from “zod/v3”. In general, the imports have been fixed so they no longer require adding “.js” at the end.</p><p>server.sendLoggingMessage is now deprecated. While the recommended approach is to send logs to services like OpenTelemetry, we can also log to stderr by calling console.warn or console.error :</p><pre>console.warn(`Getting recipe by ID: ${id}`);</pre><p>The search recipes tool also contains these small changes. The only other change worth mentioning is that the inputSchema is wrapped around a Zod object. This change was done automatically as part of the codemod above.</p><h4>STDIO Transport</h4><p>Most of the code changes come into play when initializing each MCP transport. First, the STDIO transport:</p><pre>import &quot;dotenv/config&quot;;<br>import { serveStdio } from &quot;@modelcontextprotocol/server/stdio&quot;;<br>import { connection, ConnectionStates } from &quot;mongoose&quot;;<br><br>import { connectToMongoDB } from &quot;../utils/db&quot;;<br><br>const main = async () =&gt; {<br>  try {<br>    // A single session runs in STDIO mode<br>    serveStdio(createMcpServer);<br>    console.warn(&quot;EZ Recipes MCP Server running on stdio&quot;);<br><br>    if (connection.readyState !== ConnectionStates.connected) {<br>      await connectToMongoDB();<br>    }<br>  } catch (error) {<br>    console.error(&quot;Error running MCP from stdio:&quot;, error);<br>  }<br>};<br><br>if (require.main === module) {<br>  main();<br>}</pre><p>In V2, we no longer need to initialize the transport. Calling <strong>serveStdio</strong> and passing the MCP server instance is enough to start the MCP server in STDIO mode.</p><h4>HTTP Transport</h4><p>The HTTP transport has been simplified greatly in V2. This is the whole code, including the authorization piece:</p><pre>import {<br>  OAuthTokenVerifier,<br>  requireBearerAuth,<br>} from &quot;@modelcontextprotocol/express&quot;;<br>import { toNodeHandler } from &quot;@modelcontextprotocol/node&quot;;<br>import {<br>  OAuthError,<br>  OAuthErrorCode,<br>  createMcpHandler,<br>} from &quot;@modelcontextprotocol/server&quot;;<br>import express from &quot;express&quot;;<br><br>import FirebaseAdmin from &quot;../utils/auth/admin&quot;;<br><br>const router = express.Router();<br><br>const tokenVerifier: OAuthTokenVerifier = {<br>  verifyAccessToken: async (token) =&gt; {<br>    try {<br>      const decodedToken = await FirebaseAdmin.instance.validateToken(token);<br><br>      return {<br>        token,<br>        clientId: decodedToken.uid,<br>        scopes: [], // Firebase doesn&#39;t use OAuth scopes by default<br>        expiresAt: decodedToken.exp,<br>      };<br>    } catch (error) {<br>      console.error(&quot;[MCP] Failed to validate token:&quot;, error);<br>      throw new OAuthError(<br>        OAuthErrorCode.InvalidToken,<br>        &quot;Invalid Firebase token provided&quot;<br>      );<br>    }<br>  },<br>};<br><br>const mcpAuth = requireBearerAuth({<br>  verifier: tokenVerifier,<br>});<br>const handler = createMcpHandler(createMcpServer);<br>const nodeHandler = toNodeHandler(handler);<br><br>router.all(&quot;/&quot;, mcpAuth, (req, res) =&gt; nodeHandler(req, res, req.body));<br><br>export default router;</pre><p>In V1, we had to manage all the HTTP transport sessions in memory, each associated with a session ID. This included manually checking if the user initialized or terminated the connection using various HTTP methods. Now, like with STDIO, it’s as simple as calling <strong>createMcpHandler</strong> with the MCP server instance. Ok, well, it’s a couple more steps than that! We still need to integrate this into the Express architecture. But we can utilize some helper methods to convert the MCP handler into a Node handler that can be used in all the /mcp routes. With the 2026 protocol, POST is mainly used. But the other methods are kept for backwards compatibility. This will be explained further when we get into the actual payloads. The authorization part is mostly similar, except we throw an OAuthError to comply with the 2026 protocol.</p><h4>Initializing the Express Server</h4><p>One part I failed to mention in my last article was how to initialize the Express app with the MCP SDK.</p><pre>import { createMcpExpressApp } from &quot;@modelcontextprotocol/express&quot;;<br>import {<br>  localhostAllowedHostnames,<br>  localhostAllowedOrigins,<br>} from &quot;@modelcontextprotocol/server&quot;;<br><br>import mcp from &quot;./routes/mcp&quot;;<br><br>const app = createMcpExpressApp({<br>  allowedHosts: [<br>    ...localhostAllowedHostnames(),<br>    &quot;10.0.2.2&quot;, // Android localhost<br>    &quot;ez-recipes-server.onrender.com&quot;,<br>  ],<br>  allowedOrigins: [<br>    ...localhostAllowedOrigins(),<br>    &quot;10.0.2.2&quot;,<br>    &quot;ez-recipes-web.onrender.com&quot;,<br>  ],<br>});<br><br>// All other Express configurations/middleware here<br><br>app.use(&quot;/mcp&quot;, mcp);<br><br>// parseInt() requires a string, not undefined<br>const port = parseInt(`${process.env.PORT}`) || 5000;<br><br>app.listen(port, () =&gt; console.log(`Server listening on port ${port}...`));</pre><p>Instead of calling express(), we call <strong>createMcpExpressApp()</strong>. The extra parameters are there to protect against DNS rebinding, where a malicious webpage could rebind its domain to make API calls appear same-origin. This only impacts browsers since non-browser environments don’t pass an Origin header. (It is the same reason why CORS only applies to browsers.) The Host header specifies who the server is, while the Origin header specifies who the client is. In V1, we only needed to include <strong>allowedHosts</strong>. But in V2, we also need to include <strong>allowedOrigins</strong>. By default, the SDK allows localhost connections. But to work in prod, we need to specify the prod web &amp; server hostnames. I also included the Android localhost address to test locally from an Android emulator. If these aren’t specified, either the server won’t start, or cross-origin requests will return a 403. Don’t forget to include these! It’s not like I learned it the hard way after breaking my recipe apps in prod or anything…😅</p><h3>Testing</h3><h4>MCP Inspector</h4><p>The MCP Inspector got a new look. The NPM command has been simplified, so we no longer need to include the STDIO command:</p><pre>npx @modelcontextprotocol/inspector</pre><p>The new UI makes it easier to save and seamlessly switch between STDIO and HTTP connections. Most MCP clients, including the inspector, default to the legacy 2025 protocol. Switching to <strong>auto</strong> under the Protocol Era settings allows the client to probe whether the server supports the modern protocol or fall back to the legacy protocol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KfTS9w7HLJX3eAGk" /><figcaption>Saved MCP connections for both STDIO and HTTP</figcaption></figure><p>Under Connection Info, you can confirm if the MCP connection is using the latest protocol version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*AMwL5sGa-VfPI0b_1AStRQ.png" /><figcaption>Connection info for the HTTP transport</figcaption></figure><p>From there, you can call tools and inspect the output/logs like before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Idfw8NMCrgPXZP16" /><figcaption>New inspector UI for calling tools and viewing their responses</figcaption></figure><h4>Postman</h4><p>Since our code is backwards compatible, we can still call the MCP server using the same 2025-era payloads from the last part. But for the client to be compliant with the 2026 protocol, the requests need to be structured differently. Here is a sample request:</p><pre>POST /mcp<br><br>// Headers<br>Authorization: Bearer ...<br>Accept: application/json; text/event-stream<br>MCP-Protocol-Version: 2026-07-28<br>MCP-Method: server/discover<br><br>// Body<br>{<br>  &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>  &quot;id&quot;: &quot;server-discover-probe-1&quot;,<br>  &quot;method&quot;: &quot;server/discover&quot;,<br>  &quot;params&quot;: {<br>    &quot;_meta&quot;: {<br>      &quot;io.modelcontextprotocol/protocolVersion&quot;: &quot;2026-07-28&quot;,<br>      &quot;io.modelcontextprotocol/clientInfo&quot;: {<br>        &quot;name&quot;: &quot;Postman Client&quot;,<br>        &quot;version&quot;: &quot;12.31.1&quot;<br>      },<br>      &quot;io.modelcontextprotocol/clientCapabilities&quot;: {<br>        &quot;elicitation&quot;: { &quot;form&quot;: {}, &quot;url&quot;: {} },<br>        &quot;sampling&quot;: {}<br>      }<br>    }<br>  }<br>}</pre><p>The Authorization and Accept headers are still there. But instead of an mcp-session-id, we need to pass the <strong>MCP-Protocol-Version</strong> and <strong>MCP-Method</strong> headers. Some requests also require an <strong>MCP-Name</strong> header, such as tool calls. The request body is still JSON-RPC and contains similar data to before. But now it includes a <strong>params._meta</strong> object that describes who the client is, what capabilities they support, and the protocol version. The header and body values must match to be compliant with the 2026 protocol. Why the redundancy? API gateways can more easily parse HTTP headers than request bodies to route requests accordingly. But since headers can be spoofed more easily, the body must be validated as well to ensure they relay the same request.</p><p>The key difference with the 2026 protocol is that it’s designed to be stateless. So, we no longer need to tie each exchange to a session ID. Most POST requests return a response immediately instead of keeping the stream alive. This makes it easier to test each request individually in Postman. As such, there’s no initialize method anymore. Instead, the <strong>server/discover</strong> method is called to determine if the server supports the specified protocol. The server can also include meta information in the response, such as its name and version.</p><p>The rest of the tool methods are similar to the 2025 protocol. <strong>tools/list</strong> lists all the supported tools, and <strong>tools/call</strong> invokes a tool. When calling a tool, both <strong>params.name</strong> and the<strong> MCP-Name</strong> header need to match the tool name. Errors still follow the JSON-RPC schema, but with a 4xx status code to mirror traditional REST API errors.</p><h3>Conclusion</h3><p>The 2026 protocol simplifies the process of creating an MCP server, especially for HTTP transports. Knowing how the requests and responses differ helps with determining if both the client and server support the newest MCP protocol. Hopefully, these changes will allow future protocol versions to be more seamless and build upon these additional requirements.</p><p>As usual, the full source code for my MCP server can be found here: <a href="https://github.com/Abhiek187/ez-recipes-server/blob/main/routes/mcp.ts">https://github.com/Abhiek187/ez-recipes-server/blob/main/routes/mcp.ts</a></p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9d8b6b6356a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Really Happens When You Use an MCP Server?]]></title>
            <link>https://medium.com/@Abhiek187/what-really-happens-when-you-use-an-mcp-server-d254073de48b?source=rss-38566b972440------2</link>
            <guid isPermaLink="false">https://medium.com/p/d254073de48b</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[json-rpc]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Abhishek Chaudhuri]]></dc:creator>
            <pubDate>Fri, 05 Jun 2026 03:13:31 GMT</pubDate>
            <atom:updated>2026-11-15T03:17:56.851Z</atom:updated>
            <content:encoded><![CDATA[<p>MCP (or Model Context Provider) is a powerful standard for allowing LLMs to access your server. I won’t use the cliché USB-C analogy, but it’s best to think of MCP servers as the equivalent of REST APIs designed for AI systems. The idea is that you can have your chatbot connect with many existing tools you already use, and it’ll understand how to retrieve that particular information without you needing to feed it context yourself.</p><p>When I first heard about MCP servers, I thought it was a protocol where two agents communicated with each other. But that’s not the case. Once the agent understands what APIs (or tools if we’re using MCP terminology) work best for the input given, most of the logic is deterministic. The agent essentially calls an API with some input, and the server runs its code to respond. Then it’s up to the LLM how to present that response to the user. From the MCP server’s perspective, the only probabilistic part is the input given to the tool. As long as that input is sanitized and validated (much like traditional REST APIs), anyone with an existing backend service can add MCP support today.</p><p>I tried out building an MCP server for my existing recipe app and learned a lot of interesting things about how MCP servers work under the hood and how to properly test them. For disclosure, I mainly stuck with tools and basic authentication. I won’t go in-depth about things like resources, prompts, or OAuth for MCP servers. But even then, there’s still plenty to learn about them. And since this protocol is relatively new as of this writing, I’m sure plenty will change even a year later.</p><p>In fact, since writing this article, a new MCP protocol has been released and changed the way MCP servers are built and tested. <a href="https://medium.com/@Abhiek187/what-really-happens-when-you-use-an-mcp-server-2026-07-28-edition-b9d8b6b6356a?sharedUserId=Abhiek187">Check out my latest article</a> going over the changes, but stick around if you want to learn the basics.</p><h3>Tools</h3><p>I created two tools for my recipe app: one to search for recipes and one to fetch recipe details. MCP servers don’t need to map one-to-one with all the REST APIs. Instead, we only expose the high-impact use cases LLMs can benefit from. We also start with read-only tools, so LLMs can’t accidentally modify or delete data due to vague prompts or hallucinations. And the fewer tools, the less context gets fed into LLMs, which can save on costs.</p><h4>Recipe Details</h4><p>Let’s start with the recipe details tool. I used the MCP TypeScript SDK to create my MCP server.</p><pre>import { McpServer } from &quot;@modelcontextprotocol/sdk/server/mcp.js&quot;;<br>import z from &quot;zod/v3&quot;;<br><br>import { CUISINES, MEAL_TYPES, SPICE_LEVELS } from &quot;../types/client/Recipe&quot;;<br><br>const MCP_NAME = &quot;ez-recipes&quot;;<br><br>const server = new McpServer(<br>  {<br>    name: MCP_NAME,<br>    version: &quot;1.0.0&quot;,<br>  },<br>  {<br>    capabilities: {<br>      logging: {},<br>    },<br>  }<br>);<br><br>server.registerTool(<br>  `${MCP_NAME}_get_recipe_details`,<br>  {<br>    description: &quot;Get detailed information about a recipe by its ID&quot;,<br>    inputSchema: {<br>      id: z<br>        .number()<br>        .int()<br>        .positive()<br>        .describe(&quot;A unique recipe ID that maps to spoonacular&#39;s recipe ID&quot;),<br>    },<br>    outputSchema: z.object({<br>      // Only return fields useful to an LLM to save on context &amp; reduce hallucinations<br>      id: z.number(),<br>      name: z.string(),<br>      url: z.string().url().optional(),<br>      healthScore: z.number(),<br>      time: z.number(),<br>      servings: z.number(),<br>      summary: z.string(),<br>      types: z.array(z.enum(MEAL_TYPES)),<br>      spiceLevel: z.enum(SPICE_LEVELS),<br>      isVegetarian: z.boolean(),<br>      isVegan: z.boolean(),<br>      isGlutenFree: z.boolean(),<br>      isHealthy: z.boolean(),<br>      isCheap: z.boolean(),<br>      isSustainable: z.boolean(),<br>      culture: z.array(z.enum(CUISINES)),<br>      nutrients: z.array(<br>        z.object({<br>          name: z.string(),<br>          amount: z.number(),<br>          unit: z.string(),<br>        })<br>      ),<br>      ingredients: z.array(<br>        z.object({<br>          name: z.string(),<br>          amount: z.number(),<br>          unit: z.string(),<br>        })<br>      ),<br>      instructions: z.array(<br>        z.object({<br>          name: z.string(),<br>          steps: z.array(<br>            z.object({<br>              number: z.number(),<br>              step: z.string(),<br>              ingredients: z.array(z.string()),<br>              equipment: z.array(z.string()),<br>            })<br>          ),<br>        })<br>      ),<br>      averageRating: z.number().nullable().optional(),<br>      totalRatings: z.number().optional(),<br>      views: z.number().optional(),<br>    }),<br>    annotations: {<br>      readOnlyHint: true,<br>      destructiveHint: false,<br>      idempotentHint: true,<br>      openWorldHint: false,<br>    },<br>  },<br>  async ({ id }) =&gt; {<br>    // ...<br>  }<br>);</pre><p>With TS, we use Zod to define our input and output schema. Zod has validation checks built in, so we can make sure the input and output match our expectations. It’s important to define this correctly since this is the part LLMs must interpret when deciding if using this MCP tool would be appropriate. As with any AI tool, we need to use natural language to explain each part of the tool. This is done through the describe method in Zod. Other SDKs use docstrings from comments to explain each tool. Even the tool name can help LLMs understand them better. Since MCP namespaces need to be unique, I prepended our app name to each tool to reduce the chances of naming conflicts.</p><p>The output schema covers a lot of recipe data, but I omitted certain details that weren’t relevant for LLMs. For example, we don’t need to include images since most LLMs work best with text. We also don’t need to share the IDs of every ingredient or piece of equipment. The names of these items are what matter. The annotations can provide metadata so LLMs understand if a tool is read-only and doesn’t have any side effects, but keep in mind that not all clients will respect them.</p><pre>import { getRecipeById } from &quot;../utils/db&quot;;<br>import { filterObject } from &quot;../utils/object&quot;;<br><br>server.registerTool(<br>  `${MCP_NAME}_get_recipe_details`,<br>  // ...<br>  async ({ id }) =&gt; {<br>    await server.sendLoggingMessage({<br>      level: &quot;debug&quot;,<br>      data: `Getting recipe by ID: ${id}`,<br>    });<br><br>    const recipe = await getRecipeById(id);<br><br>    if (recipe === null) {<br>      return {<br>        content: [<br>          {<br>            type: &quot;text&quot;,<br>            text: `A recipe with ID ${id} does not exist.`,<br>          },<br>        ],<br>        isError: true,<br>      };<br>    }<br><br>    return {<br>      structuredContent: {<br>        ...filterObject(recipe, [<br>          &quot;id&quot;,<br>          &quot;name&quot;,<br>          &quot;url&quot;,<br>          &quot;healthScore&quot;,<br>          &quot;time&quot;,<br>          &quot;servings&quot;,<br>          &quot;summary&quot;,<br>          &quot;types&quot;,<br>          &quot;spiceLevel&quot;,<br>          &quot;isVegetarian&quot;,<br>          &quot;isVegan&quot;,<br>          &quot;isGlutenFree&quot;,<br>          &quot;isHealthy&quot;,<br>          &quot;isCheap&quot;,<br>          &quot;isSustainable&quot;,<br>          &quot;culture&quot;,<br>          &quot;averageRating&quot;,<br>          &quot;totalRatings&quot;,<br>          &quot;views&quot;,<br>        ]),<br>        nutrients: recipe.nutrients.map((nutrient) =&gt;<br>          filterObject(nutrient, [&quot;name&quot;, &quot;amount&quot;, &quot;unit&quot;])<br>        ),<br>        ingredients: recipe.ingredients.map((ingredient) =&gt;<br>          filterObject(ingredient, [&quot;name&quot;, &quot;amount&quot;, &quot;unit&quot;])<br>        ),<br>        instructions: recipe.instructions.map((instruction) =&gt; ({<br>          name: instruction.name,<br>          steps: instruction.steps.map((step) =&gt; ({<br>            number: step.number,<br>            step: step.step,<br>            ingredients: step.ingredients.map(<br>              (ingredient) =&gt; ingredient.name<br>            ),<br>            equipment: step.equipment.map((equip) =&gt; equip.name),<br>          })),<br>        })),<br>      },<br>      // For backwards compatibility<br>      content: [<br>        {<br>          type: &quot;text&quot;,<br>          text: `Recipe name: ${recipe.name}\nSummary: ${recipe.summary}\nInstructions: ${recipe.instructions<br>            .flatMap((instruction) =&gt;<br>              instruction.steps.map((step) =&gt; `${step.number}. ${step.step}`)<br>            )<br>            .join(&quot;\n&quot;)}`,<br>        },<br>      ],<br>    };<br>  }<br>);</pre><p>The callback function is where our deterministic logic takes place. We get the recipe details from MongoDB using the provided ID. If the ID is invalid or doesn’t point to any recipe, we return an error.</p><p>On success, we make sure the structuredContent matches the output schema. If the client doesn’t support structured content, we fall back to a plaintext response summarizing the key data points from our database.</p><h4>Search Recipes</h4><p>For the search recipe tool, we can accept many more input combinations for various filters. This is more error-prone and should be tested thoroughly with various AI tools. The output schema is simpler since we only need to show high-level information about each recipe. In a typical workflow, the user asks an LLM to search for specific recipes; the LLM provides some options; the user selects a recipe; and the LLM fetches the data using the recipe’s ID.</p><pre>import z from &quot;zod/v3&quot;;<br><br>import { filterRecipes } from &quot;../utils/db&quot;;<br>import { CUISINES, MEAL_TYPES, SPICE_LEVELS } from &quot;../types/client/Recipe&quot;;<br>import { filterObject, isEmptyObject } from &quot;../utils/object&quot;;<br><br>server.registerTool(<br>  `${MCP_NAME}_search_recipes`,<br>  {<br>    description: &quot;Search recipes using a variety of filters&quot;,<br>    inputSchema: {<br>      query: z<br>        .string()<br>        .min(1)<br>        .optional()<br>        .describe(<br>          &quot;An full-text query to search recipes by name or description&quot;<br>        ),<br>      minCals: z<br>        .number()<br>        .int()<br>        .min(0)<br>        .max(2000)<br>        .optional()<br>        .describe(&quot;The minimum number of calories for a recipe&quot;),<br>      maxCals: z<br>        .number()<br>        .int()<br>        .min(0)<br>        .max(2000)<br>        .optional()<br>        .describe(&quot;The maximum number of calories for a recipe&quot;),<br>      vegetarian: z<br>        .boolean()<br>        .optional()<br>        .describe(&quot;Whether the recipes must be vegetarian&quot;),<br>      vegan: z<br>        .boolean()<br>        .optional()<br>        .describe(&quot;Whether the recipes must be vegan&quot;),<br>      glutenFree: z<br>        .boolean()<br>        .optional()<br>        .describe(&quot;Whether the recipes must be gluten-free&quot;),<br>      healthy: z<br>        .boolean()<br>        .optional()<br>        .describe(&quot;Whether the recipes must be healthy&quot;),<br>      cheap: z<br>        .boolean()<br>        .optional()<br>        .describe(&quot;Whether the recipes must be cheap&quot;),<br>      sustainable: z<br>        .boolean()<br>        .optional()<br>        .describe(&quot;Whether the recipes must be sustainable&quot;),<br>      rating: z<br>        .number()<br>        .int()<br>        .min(1)<br>        .max(5)<br>        .optional()<br>        .describe(&quot;The minimum number of stars a recipe is rated, from 1-5&quot;),<br>      spiceLevels: z<br>        .array(z.enum(SPICE_LEVELS).exclude([&quot;unknown&quot;]))<br>        .optional()<br>        .describe(&quot;The spice levels for a recipe: none, mild, or spicy&quot;),<br>      types: z<br>        .array(z.enum(MEAL_TYPES))<br>        .optional()<br>        .describe(<br>          &quot;The meal types a recipe is appropriate for, such as breakfast, lunch, or dinner&quot;<br>        ),<br>      cultures: z<br>        .array(z.enum(CUISINES))<br>        .optional()<br>        .describe(<br>          &quot;The cuisine types associated with a recipe, such as American, Italian, or Latin American&quot;<br>        ),<br>    },<br>    outputSchema: z.object({<br>      results: z.array(<br>        z.object({<br>          // Return limited recipe information since get_recipe_details will add more detail<br>          // (Similar to viewing recipe cards at a glance)<br>          id: z.number(),<br>          name: z.string(),<br>          time: z.number(),<br>          summary: z.string(),<br>          nutrients: z.array(<br>            z.object({<br>              name: z.string(),<br>              amount: z.number(),<br>              unit: z.string(),<br>            })<br>          ),<br>          averageRating: z.number().nullable().optional(),<br>          totalRatings: z.number().optional(),<br>        })<br>      ),<br>    }),<br>    annotations: {<br>      readOnlyHint: true, // only reads data<br>      destructiveHint: false, // no write actions, so reversible<br>      idempotentHint: true, // can be called multiple times with consistent results<br>      openWorldHint: false, // doesn&#39;t interact with the open internet (constrained to MongoDB database)<br>    },<br>  },<br>  async (filter) =&gt; {<br>    await server.sendLoggingMessage({<br>      level: &quot;debug&quot;,<br>      data: `Searching recipes using the following filter: ${JSON.stringify(filter)}`,<br>    });<br><br>    if (isEmptyObject(filter)) {<br>      return {<br>        content: [<br>          {<br>            type: &quot;text&quot;,<br>            text: &quot;At least one filter must be provided to search for recipes&quot;,<br>          },<br>        ],<br>        isError: true,<br>      };<br>    }<br><br>    const recipes = await filterRecipes(filter);<br><br>    if (typeof recipes === &quot;string&quot;) {<br>      return {<br>        content: [<br>          {<br>            type: &quot;text&quot;,<br>            text: `Failed to filter recipes. Error: ${recipes}`,<br>          },<br>        ],<br>        isError: true,<br>      };<br>    } else if (recipes === null) {<br>      return {<br>        content: [<br>          {<br>            type: &quot;text&quot;,<br>            text: `Failed to filter recipes. Please try again later.`,<br>          },<br>        ],<br>        isError: true,<br>      };<br>    }<br><br>    return {<br>      // structuredContent must be an object, not an array<br>      structuredContent: {<br>        results: recipes.map((recipe) =&gt; ({<br>          ...filterObject(recipe, [<br>            &quot;id&quot;,<br>            &quot;name&quot;,<br>            &quot;time&quot;,<br>            &quot;summary&quot;,<br>            &quot;averageRating&quot;,<br>            &quot;totalRatings&quot;,<br>          ]),<br>          nutrients: recipe.nutrients.map((nutrient) =&gt;<br>            filterObject(nutrient, [&quot;name&quot;, &quot;amount&quot;, &quot;unit&quot;])<br>          ),<br>        })),<br>      },<br>      content: [<br>        {<br>          type: &quot;text&quot;,<br>          text: `${recipes.length} result(s)\n${recipes<br>            .map(<br>              (recipe) =&gt;<br>                `Recipe ID: ${recipe.id}\nName: ${recipe.name}\nSummary: ${recipe.summary}`<br>            )<br>            .join(&quot;\n&quot;)}`,<br>        },<br>      ],<br>    };<br>  }<br>);</pre><p>Once again, we use MongoDB to search for the recipes using the provided filters. (That logic is out of scope of this article, but you can view the full source code linked at the bottom.) If we get no results or an error occurs, we return an error. Otherwise, we return all the results (or up to the first 100, since I didn’t incorporate pagination in this tool).</p><h3>Transports</h3><p>There are two ways to connect to an MCP server: STDIO or HTTP. It’s best to support both transport options to give users a choice for how they want to connect.</p><h4>STDIO</h4><p>STDIO is a way to connect to MCP servers locally with a 1:1 relationship between the client and the server. The client sends a request through STDIN, and the server outputs the response through STDOUT. To set this up, you would run the MCP server as a standalone script and have the client connect to it via localhost or a proxy. The connection closes as soon as the client disconnects. This is advantageous for privacy since the server doesn’t need to connect to the open internet and can leverage local resources like files to respond to client requests. As such, authentication isn’t necessary with this transport.</p><pre>import &quot;dotenv/config&quot;;<br>import { StdioServerTransport } from &quot;@modelcontextprotocol/sdk/server/stdio.js&quot;;<br>import { connection, ConnectionStates } from &quot;mongoose&quot;;<br><br>import {<br>  connectToMongoDB,<br>  disconnectFromMongoDB,<br>} from &quot;../utils/db&quot;;<br><br>const main = async () =&gt; {<br>  try {<br>    // A single session runs in STDIO mode<br>    const transport = new StdioServerTransport();<br>    const server = createMcpServer(); // the code shown earlier<br>    await server.connect(transport);<br>    await server.sendLoggingMessage({<br>      level: &quot;info&quot;,<br>      data: &quot;EZ Recipes MCP Server running on stdio&quot;,<br>    });<br><br>    if (connection.readyState !== ConnectionStates.connected) {<br>      await connectToMongoDB();<br>    }<br><br>    transport.onclose = () =&gt; {<br>      disconnectFromMongoDB();<br>    };<br>  } catch (error) {<br>    console.error(&quot;Error running MCP from stdio:&quot;, error);<br>  }<br>};<br><br>if (require.main === module) {<br>  main();<br>}</pre><p>Logging is interesting with this method. Since STDOUT is reserved for client responses, we don’t want the MCP server to output logs directly to the console. We can either output to STDERR or use the built-in logger from the SDK. I found the logger to be more ideal not only to better support HTTP, but also to make the logs more uniform and traceable. To support the logger, we need to add the logging capability when initializing the server.</p><pre>const server = new McpServer(<br>  {<br>    name: MCP_NAME,<br>    version: &quot;1.0.0&quot;,<br>  },<br>  {<br>    capabilities: {<br>      logging: {},<br>    },<br>  }<br>);</pre><h4>HTTP</h4><p>HTTP requires more setup to get working. We need to define routes that will stream the MCP responses to the client. (So yes, some MCP servers <em>are</em> REST APIs in disguise!)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*cNaPiJzs9gGYE0fHDBWN3g.png" /></figure><p>But the keyword is stream. Unlike traditional REST APIs that return one-and-done responses, the client and server keep the session alive to send data in real-time, kind of like WebSockets. The client can choose to disconnect once the user’s session has ended or if they no longer need to connect to that MCP server.</p><p>We’ll use Express to define 3 routes: a GET, POST, and DELETE /mcp endpoint. POST will establish the connection, GET will ping for updates, and DELETE will terminate the connection.</p><pre>import { StreamableHTTPServerTransport } from &quot;@modelcontextprotocol/sdk/server/streamableHttp.js&quot;;<br>import { isInitializeRequest } from &quot;@modelcontextprotocol/sdk/types.js&quot;;<br>import express, { Request, Response } from &quot;express&quot;;<br>import { randomUUID } from &quot;node:crypto&quot;;<br><br>// Multiple sessions can run in parallel in HTTP mode<br>const transports: Record&lt;string, StreamableHTTPServerTransport&gt; = {};<br><br>const router = express.Router();<br><br>router.post(&quot;/&quot;, mcpAuth, async (req, res) =&gt; {<br>  const sessionId = req.headers[&quot;mcp-session-id&quot;];<br>  let transport: StreamableHTTPServerTransport;<br><br>  if (typeof sessionId === &quot;string&quot; &amp;&amp; Object.hasOwn(transports, sessionId)) {<br>    // Reuse an existing connection<br>    transport = transports[sessionId];<br>    console.log(`[MCP] [${sessionId}] Reusing existing MCP connection`);<br>  } else if (sessionId === undefined &amp;&amp; isInitializeRequest(req.body)) {<br>    // Create a new HTTP session<br>    transport = new StreamableHTTPServerTransport({<br>      sessionIdGenerator: () =&gt; randomUUID(),<br>      onsessioninitialized: (sessionId) =&gt; {<br>        transports[sessionId] = transport;<br>        console.log(`[MCP] [${sessionId}] MCP HTTP server initialized`);<br>      },<br>    });<br><br>    transport.onclose = () =&gt; {<br>      if (transport.sessionId !== undefined) {<br>        delete transports[transport.sessionId];<br>        console.log(<br>          `[MCP] [${transport.sessionId}] MCP HTTP connection closed`<br>        );<br>      }<br>    };<br><br>    const server = createMcpServer();<br>    await server.connect(transport);<br>    await server.sendLoggingMessage({<br>      level: &quot;info&quot;,<br>      data: &quot;EZ Recipes MCP Server running on streamable HTTP&quot;,<br>    });<br>  } else {<br>    res.status(400).json({<br>      jsonrpc: &quot;2.0&quot;,<br>      error: {<br>        code: -32000,<br>        message: &quot;Bad Request: No valid session ID provided&quot;,<br>      },<br>      id: null,<br>    });<br>    return;<br>  }<br><br>  await transport.handleRequest(req, res, req.body);<br>});<br><br>const handleDefaultMcpRequest = async (req: Request, res: Response) =&gt; {<br>  const sessionId = req.headers[&quot;mcp-session-id&quot;];<br>  if (typeof sessionId !== &quot;string&quot; || !Object.hasOwn(transports, sessionId)) {<br>    res.status(400).json({ error: &quot;Invalid or missing session ID&quot; });<br>    return;<br>  }<br><br>  const transport = transports[sessionId];<br>  await transport.handleRequest(req, res);<br>};<br><br>router.get(&quot;/&quot;, mcpAuth, handleDefaultMcpRequest);<br>router.delete(&quot;/&quot;, mcpAuth, handleDefaultMcpRequest);<br><br>export default router;</pre><p>Now that we’re exposing endpoints for the HTTP transport, we should protect these using bearer auth. The MCP protocol has standards for OAuth, but in my app, I was using Firebase to handle user authentication. And Firebase is unfortunately not fully OAuth-compliant. The next best thing we could do was require passing a valid Firebase token to each endpoint, which a user would normally have after signing in to our app. This pattern doesn’t support refresh tokens, so if the token has expired, the user would need to manually pass a new token to the MCP server.</p><pre>import { requireBearerAuth } from &quot;@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js&quot;;<br>import { OAuthTokenVerifier } from &quot;@modelcontextprotocol/sdk/server/auth/provider.js&quot;;<br><br>import FirebaseAdmin from &quot;../utils/auth/admin&quot;;<br><br>const tokenVerifier: OAuthTokenVerifier = {<br>  verifyAccessToken: async (token) =&gt; {<br>    try {<br>      const decodedToken = await FirebaseAdmin.instance.validateToken(token);<br><br>      return {<br>        token,<br>        clientId: decodedToken.uid,<br>        scopes: [], // Firebase doesn&#39;t use OAuth scopes by default<br>        expiresAt: decodedToken.exp,<br>      };<br>    } catch (error) {<br>      console.error(&quot;[MCP] Failed to validate token:&quot;, error);<br>      throw new Error(&quot;Invalid Firebase token provided&quot;, { cause: error });<br>    }<br>  },<br>};<br><br>const mcpAuth = requireBearerAuth({<br>  verifier: tokenVerifier,<br>});</pre><p>Now back to the routes. Since HTTP supports multiple client connections in parallel, we need to keep track of each session so we can keep the connections alive and not cause any memory leaks. The MCP protocol uses the <strong>mcp-session-id</strong> header to pass a unique session ID for each connection. We will save these in memory and check if the session ID already exists. If so, we can leverage that existing connection. If the user connects for the first time and they pass a valid initialization request (more on this later), we create a new connection. Once the client disconnects, we remove this session ID from memory. The final part is to call handleRequest so the MCP SDK can automatically send the appropriate response to the client based on the message they pass, while keeping the stream intact. We utilize this same method for the GET and DELETE endpoints. But we still check if the session ID is present and valid. If not, we assume a faulty connection and return an error.</p><h3>Testing</h3><p>There are several ways we can test MCP servers, and each way provides a unique insight into how they work behind the scenes.</p><h4>MCP Inspector</h4><p>A good place to start is the MCP Inspector. Run <strong>npx @modelcontextprotocol/inspector</strong> followed by the command to run the MCP server. For example:</p><pre>npx @modelcontextprotocol/inspector node dist/routes/mcp.js</pre><p>This will open a webpage that lets you test the MCP server through STDIO/HTTP, list all the available tools, and validate the inputs and outputs (both the structured &amp; unstructured content). If any of the schemas don’t match, the inspector will show a warning. There are even boxes at the top for each of the different annotations. The bottom shows all the requests sent by the inspector and the server logs from the logger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VtTVqPS7aE0SYdjaoYeMMQ.png" /><figcaption>Running the recipe details tool in the MCP inspector</figcaption></figure><h4>Postman</h4><p>Like with REST APIs, Postman can be used to test MCP servers. Though I only got this to work with the HTTP transport. STDIO didn’t work since my server was running in WSL, but Postman was installed on Windows, so it couldn’t find the right command to run my server. With a Postman account, we can create a new MCP server request. This gives us an interface to connect to the server, list tools, and run them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QWypT3SXiyt5gYEBmOvFcw.png" /><figcaption>Running the search recipe tool using Postman</figcaption></figure><p>One weird quirk with Postman is that they separate traditional REST collections and multi-protocol collections. REST collections can only contain REST APIs, but are fully compatible with older versions of Postman and let you import/export the collection. But you’re not able to add non-REST APIs to an existing REST collection. So, I had to create a separate collection just to add the MCP request. Not a big deal in hindsight, but a little annoying since it wasn’t clear why certain features weren’t available with certain collections.</p><p>If your Postman version doesn’t support non-REST APIs, such as if you’re using it locally using the Scratch Pad, you can still call the MCP server using a POST request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oxcrUzp6OLBQXKN74cDk7A.png" /><figcaption>Calling the MCP server in Postman using a POST request</figcaption></figure><p>Now let’s discuss how MCP servers work under the hood. First, we need to add some required headers: the Authorization header with our Firebase token, the Accept header needs to be <strong>application/json; text/event-stream</strong>, and the mcp-session-id should be a unique UUID for a given session.</p><p>For the body, the client and server communicate using JSON-RPC. It’s JSON with some extra properties. Each request must have <strong>“jsonrpc”: “2.0”</strong> and a unique <strong>id</strong>. The method determines what type of MCP request we make. For example, “initialize” will officially start the connection, and the server returns all the supported capabilities. “tools/list” will list all the available tools. And “tools/call” will call the specified tool. Under params, we provide the tool name and all the arguments. The output contains both the structured and unstructured content. As long as the session ID is consistent, we can continue sending messages to the MCP server. If any of the messages aren’t structured correctly or if the input isn’t valid, a standard <a href="https://www.jsonrpc.org/specification#error_object">JSON-RPC error code</a> is returned, separate from REST response codes like 4xx or 5xx.</p><h4>Command Line (STDIO)</h4><p>To test the STDIO transport, we can run the MCP server directly on the command line. We paste the JSON-RPC messages, and the server immediately outputs its response along with the logs. It can be tricky to test this way since the JSON must be formatted correctly and fit on one line. All the other testing methods provide a convenient UI to send and receive messages like these.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cm15iufecHZdrO_IGk2rwA.png" /><figcaption>Running the MCP server from the command line using STDIO</figcaption></figure><h4>VSCode Copilot Chat</h4><p>Finally, we can test the MCP server using an actual chatbot. I used VSCode’s Copilot chat so I could test within the IDE, and the results were interesting. First, we need to add an <strong>mcp.json</strong> file under the .vscode directory to specify how we call an MCP server using either HTTP or STDIO.</p><pre>// STDIO<br>{<br>  &quot;servers&quot;: {<br>    &quot;ez-recipes&quot;: {<br>      &quot;type&quot;: &quot;stdio&quot;,<br>      &quot;command&quot;: &quot;/ABSOLUTE/PATH/TO/node&quot;,<br>      &quot;args&quot;: [&quot;/ABSOLUTE/PATH/TO/MCP_SCRIPT.js&quot;]<br>    }<br>  },<br>  &quot;inputs&quot;: []<br>}<br><br>// HTTP<br>{<br>  &quot;servers&quot;: {<br>    &quot;ez-recipes&quot;: {<br>      &quot;type&quot;: &quot;http&quot;,<br>      // Replace with your prod URL in a real deployment<br>      &quot;url&quot;: &quot;http://localhost:5000/mcp&quot;,<br>      &quot;headers&quot;: {<br>        &quot;Authorization&quot;: &quot;Bearer YOUR_AUTH_TOKEN&quot;<br>      }<br>    }<br>  },<br>  &quot;inputs&quot;: []<br>}</pre><p>Many MCP clients use a file similar to this, but the exact schema isn’t always consistent. If this file contains secrets to authenticate with the MCP server, it shouldn’t be included in version control. Then there should be a button above the server name to run it within VSCode. You can see the logs from the Output tab and see all the available tools from the chat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fWQU5tdJ1PeAPPEvMthqHQ.png" /><figcaption>Asking GitHub Copilot to search for recipes with specific criteria</figcaption></figure><p>Ideally, if your prompt is clear enough, the LLM should understand which MCP tool(s) to call, but to ensure we test each tool thoroughly, I specify the exact tool for each prompt. First, I ask it to search for healthy chicken &amp; broccoli recipes within the provided calorie range. This should map to the appropriate filters in my search tool. We can see within the chat which MCP tool the LLM called and what parameters they passed. We can also see this from the server logs. If this is the first time the LLM is calling an MCP tool, it can ask for permission before running it to ensure it’s within its permission boundary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0KaoAtCWTeJtZG8nuSPzcg.png" /><figcaption>Copilot calling the same tool multiple times</figcaption></figure><p>Once the server returns its output, the LLM uses it to construct an appropriate response for the user. However, while testing, I noticed that it tried calling the same tool multiple times. It could be a glitch, or it might have thought it could paginate the results if there were more than 100 of them. The parameters also didn’t quite line up with what I was expecting from my prompt. It missed the calorie range, but assumed I didn’t want vegetarian or vegan results since I asked for chicken. It eventually came back with a result, but with some fine-tuning or a better model, we can optimize the LLM’s token usage with our MCP server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gPWs91orStc-CVfrHhkRGQ.png" /><figcaption>Asking a follow-up question to learn more about a particular recipe</figcaption></figure><p>Now I have given a follow-up prompt to give more info about the herb chicken recipe it shared. This one worked better thanks to the limited input. I didn’t need to specify the recipe ID; the LLM was able to determine which recipe I was referring to and used its ID from the last message. It responded with a neat summary outlining the steps to make that recipe. And it even provided a URL to the original recipe source from spoonacular.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZhZadKCpMwQZxYSV86Mfkg.png" /><figcaption>Copilot’s recipe details response</figcaption></figure><h3>Conclusion</h3><p>MCP servers can be a powerful way to give AI tools access to your application, while staying mostly deterministic. It doesn’t take too much extra code to create an MCP server for an existing application. But it’s important to structure your tools effectively so LLMs understand how to call them and how to interpret the results, while accounting for any input errors. The more complex the input, the more ways it can fail. It’s also important to secure these MCP tools, so LLMs don’t perform unexpected actions due to malicious prompts or random hallucinations. But by understanding that MCP servers can be called like REST APIs, it should help with testing them using various clients and input combinations.</p><p>As promised, here is the full source code for my MCP server as well as the rest of my recipe backend: <a href="https://github.com/Abhiek187/ez-recipes-server/blob/main/routes/mcp.ts">https://github.com/Abhiek187/ez-recipes-server/blob/main/routes/mcp.ts</a></p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d254073de48b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Really Happens When You Use Passkeys?]]></title>
            <link>https://medium.com/@Abhiek187/how-passkeys-work-behind-the-scenes-f3daa6dd78b9?source=rss-38566b972440------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3daa6dd78b9</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[passkey]]></category>
            <category><![CDATA[webauthn]]></category>
            <dc:creator><![CDATA[Abhishek Chaudhuri]]></dc:creator>
            <pubDate>Sun, 26 Apr 2026 19:35:23 GMT</pubDate>
            <atom:updated>2026-05-03T22:45:49.458Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*gcvn1WNSuU5iEMmeQ5kRcQ.png" /><figcaption>A sequence diagram for signing in with a passkey</figcaption></figure><p>I wrote a <a href="https://medium.com/@Abhiek187/cognito-passwordless-auth-using-passkeys-ccfa4a6175e5">Medium article</a> that went over how to add passkey support to Cognito: AWS’s authentication service. That has since become my most viewed article, and passkey adoption has only grown from there. So, I want to go over how I integrated passkeys into an <a href="https://medium.com/@Abhiek187/i-wrote-the-same-app-on-ios-android-and-the-web-here-were-the-results-a67d1ef4c5e0">existing recipe app</a> that I created for iOS, Android, and the web. I’ll go more in-depth about what happens on the backend as users create and authenticate using passkeys.</p><h3>What are Passkeys Again?</h3><p>First, though, I want to briefly review what passkeys are and how they differ from passwords. A password is hashed and stored on the server-side. The server allows access if the hashed password matches. With passkeys, on the other hand, the user just needs to enter their username and sign in through their authenticator, usually either a password manager or a security key. They don’t need to remember a password and can use something they already have, such as biometrics. This is done through public-key cryptography, where the public key is stored on the server, and the private key is stored on the client. Users can (and are encouraged to) create multiple passkeys for each device they own. Passkeys are also tied to a specific domain, so they can’t be phished by tricking users into signing in through a fake website.</p><p>Both authentication methods can work simultaneously to give the user more choice, as well as a fallback in case they lose their password or their device. While passkeys appear to be seamless on the frontend, more work is done on the backend to handle and validate this transaction.</p><h3>Server Architecture</h3><p>You can use any WebAuthn-compliant library to implement passkeys, but for my project, I went with <a href="https://simplewebauthn.dev/docs/packages/server">@simplewebauthn/server</a> for my Node.js server. We’ll be building 5 APIs to manage passkeys:</p><ol><li>Create a new passkey</li><li>Log in with an existing passkey</li><li>Validate a passkey (both new and existing)</li><li>View all passkeys</li><li>Delete a passkey</li></ol><p>At a high level, the client and the server need to do the following when working with passkeys:</p><ol><li>The server generates a random challenge</li><li>The client responds to the challenge using an authenticator</li><li>The server validates the client’s response</li><li>The server saves the passkey information and returns success</li></ol><p>For context, the recipe app I built uses Firebase Authentication and stores data in MongoDB. Firebase doesn’t natively support passkeys, so once we validate them, we’ll need to create a Firebase token to authenticate the user. As such, to create a passkey, the user must be signed in first. That way, we can utilize an existing user record to save the passkey data. While there is a trend for password-less auth, the user will still need a backup method to verify their identity, such as email verification. Since I added passkey support after the fact, I still require users to have a password to sign in.</p><h3>Creating a New Passkey</h3><p>With a valid token, we can populate all the required fields to generate a new passkey challenge.</p><pre>const RelyingParty = {<br>  NAME: &quot;EZ Recipes Web&quot;,<br>  ID: &quot;ez-recipes-web.onrender.com&quot;, // should be part of the web origin<br>  ID_LOCAL: &quot;localhost&quot;, // required to test passkeys on localhost<br>  // All the clients that support passkeys (prevents phishing)<br>  ORIGINS: [<br>    &quot;http://localhost:4200&quot;,<br>    &quot;https://ez-recipes-web.onrender.com&quot;,<br>    &quot;ios:bundle-id:com.abhiek.EZ-Recipes&quot;,<br>    &quot;android:apk-key-hash:8Znu2G7b5SsIboIQ0fVbK8Zofk9F6_W8NXhKqHZ83uk&quot;, // debug fingerprint<br>    &quot;android:apk-key-hash:ZuHdlL_PLiSrXs3LMCp4tCmImpkYuQOJXcX-sMsa3og&quot;, // release fingerprint<br>  ],<br>};<br><br>router.get(&quot;/passkey/create&quot;, auth, async (req, res) =&gt; {<br>  // Get all the options needed to create a new passkey<br>  const { uid } = res.locals;<br>  let email: string;<br><br>  // Passkeys are identified by email, not by UID<br>  try {<br>    const userRecord = await FirebaseAdmin.instance.getUserByUID(uid);<br><br>    if (userRecord.email === undefined) {<br>      res.status(404).json({ error: &quot;No email associated with this account&quot; });<br>      return;<br>    } else {<br>      email = userRecord.email;<br>    }<br>  } catch (err) {<br>    const error = err as FirebaseAuthError;<br>    console.error(`Error getting the user&#39;s email for UID ${uid}:`, error);<br>    res.status(500).json({ error: error.message });<br>    return;<br>  }<br><br>  const chef = await getChef(uid);<br>  const isLocal = req.headers.origin?.includes(&quot;localhost&quot;) === true;<br><br>  try {<br>    // Used in navigator.credentials.create:<br>    // https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions<br>    const createOptions = await generateRegistrationOptions({<br>      // RP = Relying Party (the web app)<br>      rpName: RelyingParty.NAME,<br>      rpID: isLocal ? RelyingParty.ID_LOCAL : RelyingParty.ID,<br>      userName: email,<br>      userID: Buffer.from(uid),<br>      // No need to get specific information about the authenticator (protects users&#39; privacy)<br>      attestationType: &quot;none&quot;,<br>      // Prevent users from re-registering existing authenticators<br>      excludeCredentials: chef?.passkeys?.map((passkey) =&gt; ({<br>        id: passkey.id,<br>        transports: passkey.transports,<br>      })),<br>      authenticatorSelection: {<br>        // Android requires the passkey to be discoverable<br>        requireResidentKey: true,<br>        residentKey: &quot;required&quot;,<br>        userVerification: &quot;required&quot;, // the user must authenticate with their passkey<br>      },<br>    });<br><br>    // Save the challenge and user ID for verification<br>    await savePasskeyChallenge(uid, createOptions.challenge);<br>    res.json(createOptions);<br>  } catch (err) {<br>    const error = err as Error;<br>    console.error(&quot;Failed to generate a new passkey challenge:&quot;, error);<br>    res.status(500).json({<br>      error: `Failed to generate a new passkey challenge: ${error.message}`,<br>    });<br>  }<br>});</pre><p>Let’s go over each parameter.</p><ul><li>The relying party (RP) is the web hostname associated with an app’s passkeys. Even if you’re building a mobile app, you must own a web domain that password managers can use to save passkeys. The RP name can be anything you want to identify the app. But the ID must be either the full domain (minus the protocol and path) or a higher-level domain containing the website. When testing passkeys locally, the RP ID can be set to <strong>localhost</strong> so the domain matches and can be saved separately by authenticators.</li><li>The username should match what the user must enter to uniquely identify themselves. In my case, I use the user’s email since we require it to be verified before the user can create an account.</li><li>The user ID is another unique identifier to associate each passkey with the user’s account. This is kept hidden by authenticators, but it will be important to help sync passkeys between the client-side authenticators and the database. Firebase creates a unique identifier called a UID for each user. The WebAuthn standard requires this ID to be a binary value, so we set it as a base64 binary string.</li><li>Authenticators can choose to share attestation data, which contains information about the authenticator itself. This is useful, for instance, to automatically name a passkey after the authenticator used so the user has an easier time distinguishing multiple passkeys. But to respect the user’s privacy, I set this value to “none” so authenticators aren’t required to share this data. This isn’t a hard enforcement, though. I found that many password managers still share attestations, while security keys hide this information.</li><li>excludeCredentials prevents users from registering an existing passkey. We can get all the passkeys by looking up the user’s account by their UID.</li><li>Finally, the authenticator selection controls specific behavior with certain passkeys. Setting user verification to “required” means that I require users to authenticate in some way in addition to using their passkey. Most passkeys automatically do this by requiring either biometrics or a screen lock to access the required private key. But for security keys, the user must enter a PIN in addition to tapping on the device. This adds a layer of security in case the device gets stolen. On Android, I had to add some resident key fields to get passkeys working. A resident key is also known as a discoverable credential, meaning that the app can “discover” a passkey saved in an authenticator and allow the user to sign in, without them needing to enter their username. You might’ve seen this via a pop-up that asks the user if they want to sign in with a passkey.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*3HUvi_o7dd6pZn1O_LcZUw.png" /><figcaption>Example sign-in page that displays a discoverable passkey</figcaption></figure><p>Once the challenge is generated, before sending it to the client, it’s saved temporarily in the database. After the passkey is used, the client will send another request to validate the passkey. The server can refer to the stored challenge based on the UID to validate the signature and then delete the challenge. I utilized MongoDB’s TTL (time to live) feature to automatically delete a document after 1 minute, but you can adjust this timeout based on your requirements.</p><pre>const TempSchema = new Schema&lt;Temp&gt;({<br>  _id: { type: String, required: true },<br>  createdAt: { type: Date, expires: 60, default: Date.now },<br>  challenge: { type: String },<br>});</pre><p>Now the client can pass this JSON data to its respective native passkey methods. On iOS, this is done through <a href="https://developer.apple.com/documentation/authenticationservices/supporting-passkeys">Authentication Services</a>. On Android, it’s <a href="https://developer.android.com/identity/passkeys">Credential Manager</a>. And on the web, it’s the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Navigator/credentials">navigator credentials</a>. Below is an example workflow in the web app:</p><pre>let passkeyCredential: Credential | null = null;<br>let options: PublicKeyCredentialCreationOptionsJSON | null = null;<br><br>// Request a challenge from the server<br>options = await firstValueFrom(this.chefService.getNewPasskeyChallenge());<br><br>// Answer the challenge<br>const passkeyOptions =<br>  PublicKeyCredential.parseCreationOptionsFromJSON(options);<br><br>passkeyCredential = await navigator.credentials.create({<br>  publicKey: passkeyOptions,<br>});<br>if (passkeyCredential === null) {<br>  throw new Error(&#39;Unable to create a passkey&#39;);<br>}<br><br>// Verify the response<br>const chef = await firstValueFrom(<br>  this.chefService.validatePasskey(passkeyCredential),<br>);<br>this.success.emit(chef);</pre><p>On success, the authenticator automatically saves the passkey. Then the client passes the authenticator’s response to the server for validation. This can be an issue since passkey information is getting stored in multiple places. To keep things synced, we can utilize the <a href="https://w3c.github.io/webauthn/#sctn-signal-methods">Signal API</a> to tell authenticators to delete the passkey if it cannot be validated.</p><pre>// Signal all authenticators to delete the passkey<br>if (<br>  passkeyCredential !== null &amp;&amp;<br>  options !== null &amp;&amp;<br>  Object.hasOwn(PublicKeyCredential, &#39;signalUnknownCredential&#39;)<br>) {<br>  try {<br>    // eslint-disable-next-line @typescript-eslint/no-explicit-any<br>    await (PublicKeyCredential as any).signalUnknownCredential({<br>      rpId: options.rp.id,<br>      credentialId: passkeyCredential.id,<br>    });<br>  } catch {<br>    // Swallow cleanup error<br>  }<br><br>  this.snackBar.open(`${error.message}. Please try again.`, &#39;Dismiss&#39;);<br>} else {<br>  this.snackBar.open(<br>    `${error.message}. Please delete the passkey from your device and try again.`,<br>    &#39;Dismiss&#39;,<br>  );<br>}</pre><p>This is a relatively new API, so not all authenticators will respect it. But from my testing, Google Password Manager and Apple Passwords show notifications if a passkey was deleted using the Signal API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/0*7_71OIsnXGtBL4ul" /><figcaption>An example passkey from Google Password Manager that was deleted using the Signal API</figcaption></figure><p>The authenticator response contains a lot of data, mainly in binary, but the key elements include:</p><ul><li>The passkey ID</li><li>The user ID</li><li>Authenticator metadata</li><li>Client metadata</li><li>(If creating a passkey) The public key to be stored server-side</li><li>(If signing in with a passkey) The signature generated using the device’s private key</li></ul><pre>const { registrationInfo, verified } = await verifyRegistrationResponse(<br>  {<br>    /**<br>     * req.body:<br>     * {<br>     *   id: Base64URLString;<br>     *   rawId: Base64URLString;<br>     *   response: AuthenticatorAttestationResponseJSON;<br>     *   authenticatorAttachment?: AuthenticatorAttachment;<br>     *   clientExtensionResults: AuthenticationExtensionsClientOutputs;<br>     *   type: PublicKeyCredentialType;<br>     * }<br>     */<br>    response: req.body,<br>    expectedChallenge: challengeData.challenge,<br>    expectedOrigin: RelyingParty.ORIGINS,<br>    expectedRPID: [RelyingParty.ID, RelyingParty.ID_LOCAL],<br>  }<br>);<br><br>if (!verified) {<br>  res.status(401).json({ error: &quot;Unable to verify the new passkey&quot; });<br>  return;<br>}<br><br>// Copied again as a refresher<br>const RelyingParty = {<br>  NAME: &quot;EZ Recipes Web&quot;,<br>  ID: &quot;ez-recipes-web.onrender.com&quot;, // should be part of the web origin<br>  ID_LOCAL: &quot;localhost&quot;, // required to test passkeys on localhost<br>  // All the clients that support passkeys (prevents phishing)<br>  ORIGINS: [<br>    &quot;http://localhost:4200&quot;,<br>    &quot;https://ez-recipes-web.onrender.com&quot;,<br>    &quot;ios:bundle-id:com.abhiek.EZ-Recipes&quot;,<br>    &quot;android:apk-key-hash:8Znu2G7b5SsIboIQ0fVbK8Zofk9F6_W8NXhKqHZ83uk&quot;, // debug fingerprint<br>    &quot;android:apk-key-hash:ZuHdlL_PLiSrXs3LMCp4tCmImpkYuQOJXcX-sMsa3og&quot;, // release fingerprint<br>  ],<br>};</pre><p>In SimpleWebAuth’s verify method, we pass the raw authenticator response, the original challenge, the expected origin, and the RP ID. The origin and RP ID checks are important to prevent phishing. We allow a list of all possible origins for each platform. These are also known as FacetIDs. On the web, this is the full origin (the domain + the protocol, unlike the RP ID). On iOS, this is <strong>ios:bundle-id:YOUR_BUNDLE_ID</strong>. And on Android, this is <strong>android:apk-key-hash:ENCODED_SHA256_FINGERPRINT</strong>. We must pass both the debug fingerprint for testing locally and the release fingerprint used by Google in Play App Signing (not the upload key). The encoded fingerprint is a base64 URL-encoded string of the SHA-256 fingerprint, minus the colons. For the debug fingerprint, you can use the following script to calculate the hash:</p><pre># Run from the directory containing debug.keystore<br># Note: none of this is sensitive since it uses the default alias and password<br>keytool -exportcert \<br>  -alias androiddebugkey \<br>  -keystore debug.keystore \<br>  -storepass android \<br>  -keypass android 2&gt;/dev/null | \<br>openssl sha256 -binary | \<br>openssl base64 | \<br>tr &#39;+/&#39; &#39;-_&#39; | \<br>tr -d &#39;=&#39;</pre><p>And for the release fingerprint, copy the SHA-256 hash from the Google Play console and run the following command:</p><pre>echo &quot;YOUR_SHA256_HASH&quot; | \<br>tr -d &#39;:\n&#39; | \<br>xxd -r -p | \<br>openssl base64 | \<br>tr &#39;+/&#39; &#39;-_&#39; | \<br>tr -d &#39;=&#39;</pre><p>Once verified, we can extract information about the passkey to save in our database.</p><pre>const {<br>  aaguid,<br>  credential,<br>  credentialDeviceType,<br>  credentialBackedUp,<br>  origin,<br>} = registrationInfo;<br>const passkeyInfo = await getPasskeyInfo(aaguid, origin);<br>const newPasskey: Passkey = {<br>  id: credential.id,<br>  publicKey: credential.publicKey,<br>  counter: credential.counter,<br>  transports: credential.transports,<br>  deviceType: credentialDeviceType,<br>  backedUp: credentialBackedUp,<br>  name: passkeyInfo?.name ?? &quot;Unknown&quot;,<br>  lastUsed: new Date(),<br>  iconLight: passkeyInfo?.iconLight,<br>  iconDark: passkeyInfo?.iconDark,<br>};<br>await savePasskey(uid, newPasskey);<br><br>res.json({ token });</pre><p>The AAGUID (Authenticator Attestation Globally Unique Identifier) is a unique identifier for each authenticator. This is the attestation info described earlier to help users identify each passkey. We utilize a <a href="https://github.com/passkeydeveloper/passkey-authenticator-aaguids">GitHub repo</a> to get the full list of authenticators, but acknowledge that it’s not an official, permanent solution.</p><pre>// Community-driven AAGUID list, may be removed at any point:<br>// https://github.com/passkeydeveloper/passkey-authenticator-aaguids/tree/main<br>const aaguidApi = createAxios({<br>  baseURL:<br>    &quot;https://raw.githubusercontent.com/passkeydeveloper/passkey-authenticator-aaguids/refs/heads/main/combined_aaguid.json&quot;,<br>  signal: new AbortController().signal,<br>});<br><br>// Simple cache that resets when the server spins down<br>let aaguidCache: PasskeyAAGUIDResponse = {};<br><br>/**<br> * Fetch user-friendly information about a passkey based on its AAGUID<br> * (Authenticator Attestation Global Unique Identifier)<br> * @param aaguid the AAGUID of the passkey<br> * @param origin the client that used the passkey<br> * @returns user-friendly data about the passkey, or `undefined` if no info could be found<br> */<br>export const getPasskeyInfo = async (<br>  aaguid: string,<br>  origin: string<br>): Promise&lt;<br>  | {<br>      name: string;<br>      iconLight?: string;<br>      iconDark?: string;<br>    }<br>  | undefined<br>&gt; =&gt; {<br>  try {<br>    let passkeyInfo = aaguidCache[aaguid];<br>    if (passkeyInfo === undefined) {<br>      // Cache miss: call the real API (downloads MBs of data)<br>      const allPasskeys = await aaguidApi.get&lt;PasskeyAAGUIDResponse&gt;(&quot;&quot;);<br>      aaguidCache = allPasskeys.data ?? {};<br>      passkeyInfo = allPasskeys.data?.[aaguid];<br><br>      /* If the AAGUID is all 0&#39;s, the authenticator may have intentionally hid the device info.<br>       * As a fallback, create a default name based on the origin.<br>       */<br>      if (passkeyInfo === undefined) {<br>        if (origin.startsWith(&quot;https&quot;)) {<br>          return {<br>            name: &quot;Web Browser&quot;,<br>          };<br>        } else if (origin.startsWith(&quot;ios&quot;)) {<br>          return {<br>            name: &quot;iOS Device&quot;,<br>          };<br>        } else if (origin.startsWith(&quot;android&quot;)) {<br>          return {<br>            name: &quot;Android Device&quot;,<br>          };<br>        } else {<br>          return undefined;<br>        }<br>      }<br>    }<br><br>    // Normalize the response<br>    return {<br>      name: passkeyInfo.name,<br>      iconLight: passkeyInfo.icon_light ?? undefined,<br>      iconDark: passkeyInfo.icon_dark ?? undefined,<br>    };<br>  } catch (error) {<br>    console.warn(`Failed to get passkey info with AAGUID ${aaguid}:`, error);<br>    return undefined;<br>  }<br>};</pre><p>Then we store all the passkey information in MongoDB under the user’s existing document. (+1 for NoSQL’s flexible schema!) One important piece of information we store is when the passkey was last used. This, alongside the passkey name, can help users identify passkeys that haven’t been used in a while.</p><h3>Logging in with a Passkey</h3><p>Authenticating with passkeys follows a similar sequence of events, but with different arguments.</p><pre>router.get(<br>  &quot;/passkey/auth&quot;,<br>  query(&quot;email&quot;).isEmail().withMessage(&quot;Invalid email&quot;),<br>  async (req, res) =&gt; {<br>    // Get all the options needed to sign in using an existing passkey<br>    checkValidations(req, res);<br>    if (res.writableEnded) return;<br><br>    const email = req.query?.email as string;<br>    let uid: string;<br>    // Don&#39;t give attackers hints if an account exists or has a passkey<br>    const genericPasskeyError = `No passkeys are associated with chef ${email}`;<br><br>    try {<br>      ({ uid } = await FirebaseAdmin.instance.getUserByEmail(email));<br>    } catch (err) {<br>      const error = err as FirebaseAuthError;<br>      console.error(`Error getting the user&#39;s UID:`, error);<br>      res.status(400).json({ error: genericPasskeyError });<br>      return;<br>    }<br><br>    const chef = await getChef(uid);<br>    if (<br>      chef === null ||<br>      chef.passkeys === undefined ||<br>      chef.passkeys.length === 0<br>    ) {<br>      res.status(400).json({ error: genericPasskeyError });<br>      return;<br>    }<br><br>    const isLocal = req.headers.origin?.includes(&quot;localhost&quot;) === true;<br><br>    try {<br>      // Used in navigator.credentials.get:<br>      // https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions<br>      const requestOptions = await generateAuthenticationOptions({<br>        rpID: isLocal ? RelyingParty.ID_LOCAL : RelyingParty.ID,<br>        // Require users to use a previously-registered authenticator<br>        allowCredentials: chef.passkeys.map((passkey) =&gt; ({<br>          id: passkey.id,<br>          transports: passkey.transports,<br>        })),<br>        userVerification: &quot;required&quot;,<br>      });<br><br>      await savePasskeyChallenge(uid, requestOptions.challenge);<br>      res.json(requestOptions);<br>    } catch (err) {<br>      const error = err as Error;<br>      console.error(&quot;Failed to generate an existing passkey challenge:&quot;, error);<br>      res.status(500).json({<br>        error: `Failed to generate an existing passkey challenge: ${error.message}`,<br>      });<br>    }<br>  }<br>);</pre><p>Since the user isn’t signed in, we can use their email to look up their existing passkeys. This gets passed as allowCredentials, acting as the inverse of excludeCredentials, to prevent the user from signing in with an unknown passkey.</p><pre>// If the passkey exists, verify the authentication signature<br>const inputPasskeyId = req.body.id;<br>const passkeys = await getPasskeys(uid);<br>const passkey = passkeys.find((pk) =&gt; pk.id === inputPasskeyId);<br><br>if (passkey === undefined) {<br>  res.status(401).json({<br>    error: `The passkey provided isn&#39;t associated with chef ${email}`,<br>  });<br>  return;<br>}<br><br>const { authenticationInfo, verified } =<br>  await verifyAuthenticationResponse({<br>    /**<br>     * req.body:<br>     * {<br>     *   id: Base64URLString;<br>     *   rawId: Base64URLString;<br>     *   response: AuthenticatorAssertionResponseJSON; // main difference<br>     *   authenticatorAttachment?: AuthenticatorAttachment;<br>     *   clientExtensionResults: AuthenticationExtensionsClientOutputs;<br>     *   type: PublicKeyCredentialType;<br>     * }<br>     */<br>    response: req.body,<br>    expectedChallenge: challengeData.challenge,<br>    expectedOrigin: RelyingParty.ORIGINS,<br>    expectedRPID: [RelyingParty.ID, RelyingParty.ID_LOCAL],<br>    credential: {<br>      id: passkey.id,<br>      publicKey: passkey.publicKey,<br>      counter: passkey.counter,<br>      transports: passkey.transports,<br>    },<br>  });<br><br>if (!verified) {<br>  res<br>    .status(401)<br>    .json({ error: &quot;Unable to verify the existing passkey&quot; });<br>  return;<br>}<br><br>const { credentialID, newCounter } = authenticationInfo;<br>await updatePasskeyCounter(uid, credentialID, newCounter);<br><br>// Create a custom token that can be exchanged for a Firebase token<br>const idToken = await FirebaseAdmin.instance.getIdToken(uid);<br>res.cookie(COOKIES.ID_TOKEN, idToken, COOKIE_2_WEEKS);<br>res.json({ token: idToken });</pre><p>When it comes time to validate the passkey, we need to make sure it matches one of the saved passkeys for our user. When the passkey was first registered, the authenticator created a key pair, where the private key is stored client-side, and the public key is stored server-side. When signing in, the authenticator signs the challenge sent by the server. The server must verify the signature using the associated public key. Then, to authenticate the user, we need to mint a new Firebase token. This involves 2 steps: creating a custom token using the admin SDK and exchanging it for an ID token using the Firebase REST API.</p><pre>/**<br> * Get an ID token for a given user &amp; store the refresh token<br> * @param uid the unique ID of the user<br> * @throws `FirebaseAuthError` if an error occurred<br> * @returns an ID token<br> */<br>async getIdToken(uid: string): Promise&lt;string&gt; {<br>  const auth = getAuth();<br>  const customToken = await auth.createCustomToken(uid);<br>  const { idToken, refreshToken } =<br>    await FirebaseApi.instance.exchangeCustomToken(customToken);<br>  await saveRefreshToken(uid, refreshToken);<br>  return idToken;<br>}<br><br>this.idApi = createAxios({<br>  baseURL: &quot;https://identitytoolkit.googleapis.com/v1&quot;,<br>  params: {<br>    key: process.env.WEB_API_KEY,<br>  },<br>  signal: new AbortController().signal,<br>});<br><br>/**<br> * Exchange a custom token for an ID &amp; refresh token<br> * @param customToken a custom token created by the Firebase Admin SDK<br> * @throws `FirebaseRestError` if an error occurred<br> * @returns an ID &amp; refresh token<br> */<br>async exchangeCustomToken(<br>  customToken: string<br>): Promise&lt;FirebaseTokenExchangeResponse&gt; {<br>  const response = await this.idApi.post&lt;FirebaseTokenExchangeResponse&gt;(<br>    &quot;/accounts:signInWithCustomToken&quot;,<br>    {<br>      token: customToken,<br>      returnSecureToken: true,<br>    }<br>  );<br>  return response.data;<br>}</pre><h3>Getting All Passkeys</h3><p>I created an API to fetch the user’s profile after they sign in. The same API can be used to list all their passkeys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*TUi3x1txG9pKqc-bwQVxqQ.png" /><figcaption>A list of passkeys from the user’s profile</figcaption></figure><p>The most important things to show the user are the passkey name and when they were last used. The AAGUID API also provides icons for each authenticator as a nice visual touch. If an authenticator couldn’t be identified, such as with a security key, we default to a generic name based on where the user created the passkey. For example, I used my YubiKey on my website, so the passkey is called “Web Browser”. You can give the user the option to rename a passkey as they see fit.</p><h3>Deleting a Passkey</h3><p>Much like other credentials, a user must be given an option to delete a passkey from their account. This can be done by simply deleting the credential from the database.</p><pre>router.delete(<br>  &quot;/passkey&quot;,<br>  query(&quot;id&quot;)<br>    .isString()<br>    .withMessage(&quot;Passkey ID is not a string&quot;)<br>    .notEmpty()<br>    .withMessage(&quot;Passkey ID is required&quot;),<br>  auth,<br>  async (req, res) =&gt; {<br>    checkValidations(req, res);<br>    if (res.writableEnded) return;<br><br>    const passkeyId = req.query?.id as string;<br>    const { token, uid } = res.locals;<br><br>    try {<br>      const isSuccess = await deletePasskey(uid, passkeyId);<br><br>      if (isSuccess) {<br>        res.json({ token });<br>      } else {<br>        res.status(404).json({ error: &quot;Passkey not found&quot; });<br>      }<br>    } catch (err) {<br>      const error = err as Error;<br>      console.error(&quot;Error deleting passkey:&quot;, error);<br>      res<br>        .status(500)<br>        .json({ error: `Error deleting passkey: ${error.message}` });<br>    }<br>  }<br>);</pre><p>No WebAuthn methods are required, but we can leverage the Signal API to automatically delete the passkey from the authenticator. If the device or authenticator doesn’t support this feature, we can ask the user to manually delete the passkey from their device. Otherwise, they may try to sign in with that passkey and get an error since the server can’t validate the passkey anymore.</p><p>Another way to remediate this is to let all the authenticators know which passkeys are tied to a user after they sign in.</p><pre>async syncPasskeys(chef: Chef) {<br>  // Sync passkeys and the username with all authenticators<br>  try {<br>    if (Object.hasOwn(PublicKeyCredential, &#39;signalAllAcceptedCredentials&#39;)) {<br>      // eslint-disable-next-line @typescript-eslint/no-explicit-any<br>      await (PublicKeyCredential as any).signalAllAcceptedCredentials({<br>        rpId: location.hostname,<br>        userId: base64URLEncode(chef.uid),<br>        allAcceptedCredentialIds: chef.passkeys.map(<br>          (passkey) =&gt; passkey.id, // the passkey IDs are already base64 URL-encoded<br>        ),<br>      });<br>      console.log(<br>        `Signaled all authenticators to sync ${chef.passkeys.length} ${<br>          chef.passkeys.length === 1 ? &#39;passkey&#39; : &#39;passkeys&#39;<br>        } for user ${chef.uid} and RP ID ${location.hostname}: [${chef.passkeys<br>          .map((passkey) =&gt; passkey.id)<br>          .join(&#39;, &#39;)}]`,<br>      );<br>    }<br>    if (Object.hasOwn(PublicKeyCredential, &#39;signalCurrentUserDetails&#39;)) {<br>      // eslint-disable-next-line @typescript-eslint/no-explicit-any<br>      await (PublicKeyCredential as any).signalCurrentUserDetails({<br>        rpId: location.hostname,<br>        userId: base64URLEncode(chef.uid),<br>        name: chef.email,<br>        displayName: &#39;&#39;,<br>      });<br>      console.log(<br>        `Signaled all authenticators to set the username for user ID ${chef.uid} and RP ID ${<br>          location.hostname<br>        } to ${chef.email}`,<br>      );<br>    }<br>  } catch (error: unknown) {<br>    console.warn(&#39;Passkey signal error:&#39;, error);<br>  }<br>}</pre><p>This is where saving the UID is important when registering a passkey. If an authenticator has a passkey that isn’t in this list, it will automatically delete it and send the user a notification. But again, this requires that the authenticator support the Signal API in the first place.</p><p>Here’s a full demo of what we built:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JrGXXq44qT1-_Pp4" /><figcaption>Creating a passkey, logging in with it, and deleting it from Google Password Manager</figcaption></figure><p>Hopefully, this was a good deep dive into how passkeys are managed end-to-end. We balance having a frictionless UX with several server-side validation checks.</p><p>You can find my recipe app as well as the source code for the server using the links below. Thanks for reading!</p><ul><li>Server code: <a href="https://github.com/Abhiek187/ez-recipes-server">https://github.com/Abhiek187/ez-recipes-server</a></li><li>Website: <a href="https://ez-recipes-web.onrender.com/">https://ez-recipes-web.onrender.com/</a></li><li>Android app: <a href="https://play.google.com/store/apps/details?id=com.abhiek.ezrecipes">https://play.google.com/store/apps/details?id=com.abhiek.ezrecipes</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3daa6dd78b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Wrote the Same App Part 6: Web Exclusive Features]]></title>
            <link>https://medium.com/@Abhiek187/i-wrote-the-same-app-part-6-web-exclusive-features-c9c9c134b882?source=rss-38566b972440------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9c9c134b882</guid>
            <category><![CDATA[web]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Abhishek Chaudhuri]]></dc:creator>
            <pubDate>Sun, 20 Jul 2025 21:37:37 GMT</pubDate>
            <atom:updated>2025-07-20T21:37:37.963Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="EZ Recipes logo" src="https://cdn-images-1.medium.com/max/300/1*UdcU28noobFcm3N2lLyn_w.png" /><figcaption>EZ Recipes logo</figcaption></figure><p>Let’s explore what made developing the EZ Recipes Web app special. For more context on how the app was built, please check out the previous parts in this series:</p><ul><li><a href="https://medium.com/@Abhiek187/a67d1ef4c5e0">Part 1 — MVP</a></li><li><a href="https://medium.com/@Abhiek187/034f504bf5b4">Part 2 — Post MVP</a></li></ul><p>For all other platforms, feel free to check out these articles:</p><ul><li><a href="https://medium.com/@Abhiek187/i-wrote-the-same-app-part-4-ios-exclusive-features-952a99745012">iOS</a></li><li><a href="https://medium.com/@Abhiek187/i-wrote-the-same-app-part-5-android-exclusive-features-da301053c933">Android</a></li></ul><h3>Web</h3><p>Web apps, on the surface, seem to have the most flexible developer experience due to the abundance of tools, frameworks, and IDEs, in addition to being a lower barrier to entry compared to mobile development. But all that flexibility comes with more responsibilities to ensure you’re delivering a great user experience without compromising security.</p><p>Navigation is freer on the web than on mobile apps. Users can navigate to any page under a domain. There’s no restriction like on mobile to hide certain screens by button presses. As such, it’s important to have a 404 page ready in case the user navigates to a path the website can’t serve.</p><figure><img alt="The 404 page for EZ Recipes" src="https://cdn-images-1.medium.com/max/1024/1*rASN6LJsYJLvqA6qPBv0pA.png" /><figcaption>The 404 page for EZ Recipes</figcaption></figure><p>Following agile principles, I deployed my code every time it got merged into the main branch. So, unlike mobile apps, the website would regularly update, and users can’t roll back to an earlier version. (This is assuming service workers aren’t used.) This is where feature flags come into play. We can quickly toggle certain features on or off depending on what we want to deliver to the end users. You can introduce more advanced strategies like A/B testing, but in my case, I wanted to create simple flags to hide features that were in development until they were prod-ready. In Angular, routes can be protected using guards. I created a dev guard to prevent navigation to incomplete pages.</p><pre>import { CanActivateFn } from &#39;@angular/router&#39;;<br><br>import { environment } from &#39;src/environments/environment&#39;;<br><br>// Block access to routes until they&#39;re ready for production<br>export const devGuard: CanActivateFn = () =&gt; {<br>  return !environment.production;<br>};</pre><p>I also created an auth guard to check if a user is authorized to access a certain page. If they’re not, the guard will redirect the user to the login page. After they log in, they will be redirected back to the page they originally wanted to navigate. I used these guards extensively when I developed the login feature, since it would be confusing for users to see a profile tab without being able to create an account or get access to exclusive perks.</p><figure><img alt="The generated static assets for the EZ Recipes website" src="https://cdn-images-1.medium.com/max/820/1*HKP9w_re7jLWT2iv1Z9zMg.png" /><figcaption>The generated static assets for the EZ Recipes website</figcaption></figure><p>Web apps are packaged differently from mobile apps. While there is technically a build step to convert TypeScript code into JavaScript, the final build is the minified source code that’s interpreted by browsers instead of a binary file. This makes reverse engineering websites easier than mobile apps, but it’s important to emphasize that nothing on the front end is hidden. All sensitive data must be kept secure on the server side.</p><figure><img alt="Docker logo" src="https://cdn-images-1.medium.com/max/300/1*xiQD14CF8kLiejvgfDEm_A.png" /><figcaption>Docker logo</figcaption></figure><p>Docker is used to containerize both the web app and the server in a way that’s portable for any web hosting service. It contains a list of instructions that allow any Linux machine to install and run your code. There’s an art to creating the optimal Docker container that secures the Linux environment and minimizes the final image size. Many companies have dedicated teams whose job is to help deploy the code that the developers built. While I don’t claim to be a Docker expert, I learned a good number of tips throughout my career and even while building this project.</p><pre># The first stage builds the Angular application for production<br>FROM node:24-alpine AS builder<br>WORKDIR /usr/src/app<br><br>COPY package*.json ./<br># The Angular CLI is a dev dependency that needs to be installed<br>RUN npm ci --omit=dev &amp;&amp; npm ci @angular/cli &amp;&amp; npm cache clean --force<br><br>COPY . .<br># The build will be located in dist/project-name<br>RUN npm run build<br><br># The second stage hosts the app using nginx<br>FROM nginx:1.29.0-alpine<br>COPY nginx.conf /etc/nginx/nginx.conf<br>COPY --from=builder /usr/src/app/dist/ez-recipes/browser /usr/share/nginx/html</pre><p>I typically start with an Alpine Node image since it gives us the bare minimum to run Linux and Node.js and install additional dependencies for only a few MB. Then I copy the package.json files to install all the non-dev dependencies. These are the only dependencies that are required to bundle the web app and run the server. To minimize the final image size, I do 2 things. First, I combine as many RUN commands as I can to reduce the number of layers or instructions needed to build the image. Second, I delete any cache that was created from installing dependencies. For NPM, it’s as simple as running <strong>npm cache clean — force</strong>. Now I copy the rest of the code over to the container. But there’s an additional step that’s done here to make sure we’re not copying any unnecessary files. Like Git, Docker can ignore files listed in <strong>.dockerignore</strong> when using the COPY command.</p><pre>.angular/cache<br>.git<br>coverage<br>dist<br>node_modules<br>npm-debug.log</pre><p>Most files from the gitignore can be added to the dockerignore. This includes .env files that contain secrets. These should be injected separately, either through a dedicated secrets manager or through the web hosting tool. Additionally, I added the .git directory since version control isn’t needed in a container that’s only meant to run production code. You can also add other files like READMEs that don’t contribute to the final app build.</p><p>After the code is built, the web app and server diverge. The server simply runs the startup script to listen for requests. But for the web app, we don’t need the full source code anymore. Instead, we can create a separate stage to host all the static assets. I use an nginx alpine image to serve the web content under <strong>/usr/share/nginx/html</strong>. Finally, I run a Docker Compose file to build both the web and server images at the same time and expose the appropriate ports. I can reference the GitHub repo to fetch the corresponding Dockerfile.</p><pre>services:<br>  web:<br>    build:<br>      context: https://github.com/Abhiek187/ez-recipes-web.git#main<br>      dockerfile: Dockerfile.prod<br>    image: ez-recipes-web-prod<br>    ports:<br>      - 4200:80<br><br>  server:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile.prod<br>    image: ez-recipes-server-prod<br>    ports:<br>      - 5000:5000<br>    environment:<br>      - PORT=5000<br>      - API_KEY=$API_KEY<br>      - MONGO_URI=$MONGO_URI</pre><p>The final image size for the web app is 66 MB and 329 MB for the server, which is reasonable for a side project. I like creating 2 separate Dockerfiles for testing and production. The production file should follow all the best practices listed above, but the testing one can simply follow the same instructions used to run your app locally.</p><p>Unlike mobile apps, websites don’t have an “App Store”. Deploying websites doesn’t require any approval aside from your team, but you need to manage the metrics yourself. App Store consoles display the total number of users using your app and separate them by region, device type, and OS version. They also show how often an app crashes, along with the stack trace for debugging. Users can rate the app and write reviews. If you’re showing off your portfolio to employers, this is a good way to show how real users respond to your apps. For web apps, you would need to integrate a tool like Adobe or Google Analytics to collect these metrics. To comply with privacy laws, you should show a consent banner to allow the website to store cookies for tracking. You could link to a survey to collect feedback, but you should follow the same best practices for when you’d want to prompt them on mobile to mitigate negative reviews. Websites don’t <em>crash</em> per se, but are susceptible to runtime errors that could prevent certain web content from loading. A logging tool would need to be integrated to monitor these errors from the front end, since console logs stay within the browser.</p><p>App stores also provide a way to show off your marketing skills since you need to create a title, description, and screenshots that users will search for and be enticed to download your app. If you’re building a PWA, you can add these things when users are prompted to install the web app. Otherwise, the equivalent for websites would be SEO or search engine optimization. There are techniques website owners can perform to increase their chances of discoverability in search engines. Adding the right meta tags can improve search results and allow sites to be more easily shared across platforms. Another way to improve SEO is to optimize the content for web crawlers, such as with server-side rendering, sitemaps, or a robots.txt file. I can see in the logs when a bot is crawling my website (and likely training their AI models 😏):</p><blockquote>[Incoming Request] Thu Jul 10 2025 17:48:51 GMT+0000 (Coordinated Universal Time) | Method: GET | URL: /api/terms | Headers: {“user-agent”:”Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Safari/605.1.15 (Applebot/0.1; +http://www.apple.com/go/applebot)&quot;,&quot;accept-language&quot;:&quot;en-US&quot;,&quot;origin&quot;:&quot;https://ez-recipes-web.onrender.com&quot;}</blockquote><blockquote>[Incoming Request] Thu Jul 10 2025 18:04:24 GMT+0000 (Coordinated Universal Time) | Method: GET | URL: /api/terms | Headers: {“user-agent”:”AdsBot-Google (+http://www.google.com/adsbot.html)&quot;,&quot;accept-language&quot;:&quot;en-US&quot;,&quot;origin&quot;:&quot;https://ez-recipes-web.onrender.com&quot;}</blockquote><blockquote>[Incoming Request] Fri Jul 11 2025 18:01:40 GMT+0000 (Coordinated Universal Time) | Method: GET | URL: /robots.txt | Headers: {“user-agent”:”Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)&quot;}</blockquote><blockquote>[Incoming Request] Sat Jul 12 2025 12:23:51 GMT+0000 (Coordinated Universal Time) | Method: GET | URL: /robots.txt | Headers: {“user-agent”:”Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)”}</blockquote><p>Other legal and user-friendly features aren’t as emphasized for web apps due to the lack of a formal approval process. In a way, this is a good thing for teams that want high velocity and a continuous feedback loop. There’s no bottleneck from a 3rd party company that puts an app’s deployment status outside of the team’s control. On the other hand, it makes it easy for companies to release unfinished products that can have negative financial or reputational costs. Even for a junior engineer, having a formal review process helps them receive more holistic feedback on how to improve a side project outside of just developing it. When you first submit your app to these app stores, you need to fill out several forms to declare what kind of app you’re trying to publish, what data you need to collect, your target demographic, ads, etc. One of these requirements is a privacy policy. For simple projects, you may be inclined to just state that you don’t collect any data and truly care about the user’s privacy. But if your app does collect data for things like logging or database storage, it’s better to be honest so you don’t deceive your users or face legal repercussions. I created a <a href="https://github.com/Abhiek187/ez-recipes-web/blob/main/PRIVACY_POLICY.md">privacy policy</a> that can be shared across all platforms and is updated whenever I add significant features like accounts.</p><figure><img alt="Some of the forms that were required to submit the Android app" src="https://cdn-images-1.medium.com/max/310/1*tPSR2Kqp2kjwZ30mlH2s3w.png" /><figcaption>Some of the forms that were required to submit the Android app</figcaption></figure><p>Another feature that was required for iOS and Android that isn’t as emphasized for web apps is the ability for users to delete their accounts. This gives them full control over how apps manage their data. It’s generally good practice to delete any unused accounts in case there’s a data breach in the future. In all my apps that include a sign-in page, I always include an option to delete the user’s account. To make sure they confirm their decision, I require them to enter their full username before deleting their account. This is a clever technique many apps use to ensure their users are consciously aware of the consequences.</p><figure><img alt="The delete account form requiring users to enter their username" src="https://cdn-images-1.medium.com/max/649/1*haSB2g893i9R5pggwPJpRA.png" /><figcaption>The delete account form requiring users to enter their username</figcaption></figure><p>In EZ Recipes, once the account is deleted in Firebase, I also delete the user’s document in MongoDB. Firebase sends an email confirming that their account has been deleted. If users uninstall the mobile app, their account info won’t be deleted, only the data saved on the device (except the Keychain as discussed in the iOS article). If they change their mind, they can still sign in using the same credentials. This is why mobile apps are required to provide an alternative way to request the deletion of users’ information.</p><p>Some apps provide a form that users can enter, and the deletion process can be automated. On the server, I created a cron job that deletes unverified accounts after 1 week. If users still remember their credentials, they can open the web app and select the Delete Account option. Otherwise, if the user has no way of signing in, the deletion process is more manual. In the privacy policy, I give users an option to email me if they want to delete the account under their email. Then I would go to Firebase and MongoDB and delete the appropriate records. I assume the email the user is using is the same one I should delete to avoid deleting someone else’s account. If Firebase provided an API to verify the user’s email before deleting their account, I would’ve used that, but no such endpoint currently exists aside from building a custom workflow.</p><h3>Staying Up to Date</h3><p>For continuous learning, Apple and Google host yearly developer conferences to give updates on their platforms. For iOS, it’s <a href="https://developer.apple.com/wwdc/">WWDC</a>. For Android, it’s <a href="https://io.google/">Google I/O</a>. Angular also gets included in Google I/O. Other web frameworks have their yearly conferences, too. I find videos easier to follow than reading through the official docs. Since they’re on YouTube, it’s easy to search for the videos you want. I noticed that Apple’s prerecorded WWDC videos are more direct and to the point, whereas Google’s live demos tend to be livelier and more playful, at the risk of the AI not working as expected. But besides these, there are other resources I’ve found useful when I wanted to learn something new about each platform. A personal favorite of mine is <a href="https://www.hackingwithswift.com/">Hacking with Swift</a>, which provides easy-to-follow tutorials for Swift and SwiftUI, as well as accompanying videos for each subject.</p><p>Thanks again for reading all these articles! I hope you learned something new about developing on each platform. As usual, you can view the recipe app in these repos:</p><ul><li>iOS: <a href="https://github.com/Abhiek187/ez-recipes-ios">https://github.com/Abhiek187/ez-recipes-ios</a></li><li>Android: <a href="https://github.com/Abhiek187/ez-recipes-android">https://github.com/Abhiek187/ez-recipes-android</a></li><li>Web: <a href="https://github.com/Abhiek187/ez-recipes-web">https://github.com/Abhiek187/ez-recipes-web</a></li><li>Server: <a href="https://github.com/Abhiek187/ez-recipes-server">https://github.com/Abhiek187/ez-recipes-server</a></li></ul><p>And check out the published apps:</p><ul><li>Android: <a href="https://play.google.com/store/apps/details?id=com.abhiek.ezrecipes">https://play.google.com/store/apps/details?id=com.abhiek.ezrecipes</a></li><li>Web: <a href="https://ez-recipes-web.onrender.com/">https://ez-recipes-web.onrender.com/</a></li><li>Server: <a href="https://ez-recipes-server.onrender.com/">https://ez-recipes-server.onrender.com/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9c9c134b882" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Wrote the Same App Part 5: Android Exclusive Features]]></title>
            <link>https://medium.com/@Abhiek187/i-wrote-the-same-app-part-5-android-exclusive-features-da301053c933?source=rss-38566b972440------2</link>
            <guid isPermaLink="false">https://medium.com/p/da301053c933</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[keystore]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[proguard]]></category>
            <dc:creator><![CDATA[Abhishek Chaudhuri]]></dc:creator>
            <pubDate>Sun, 20 Jul 2025 21:35:58 GMT</pubDate>
            <atom:updated>2025-07-20T21:38:14.091Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="EZ Recipes logo" src="https://cdn-images-1.medium.com/max/300/1*UdcU28noobFcm3N2lLyn_w.png" /><figcaption>EZ Recipes logo</figcaption></figure><p>Let’s explore what made developing the EZ Recipes Android app special. For more context on how the app was built, please check out the previous parts in this series:</p><ul><li><a href="https://medium.com/@Abhiek187/a67d1ef4c5e0">Part 1 — MVP</a></li><li><a href="https://medium.com/@Abhiek187/034f504bf5b4">Part 2 — Post MVP</a></li></ul><p>For all other platforms, feel free to check out these articles:</p><ul><li><a href="https://medium.com/@Abhiek187/i-wrote-the-same-app-part-4-ios-exclusive-features-952a99745012">iOS</a></li><li><a href="https://medium.com/@Abhiek187/i-wrote-the-same-app-part-6-web-exclusive-features-c9c9c134b882">Web</a></li></ul><h3>Android</h3><p>When comparing my experience building all the apps, I found the Android version the most complex to develop. It seemed like for every feature I’d implement on iOS and the web, it would take 5 extra steps to implement the same thing on Android. Kotlin is built on top of the JVM, and Java requires classes with unique namespaces (aka packages) so they can be imported from other files. When you create a new Android project, you’ll have the following file structure for some of the critical files:</p><ul><li>PROJECT_NAME/app/src/main/AndroidManifest.xml (the app’s metadata)</li><li>PROJECT_NAME/app/src/main/res/values/strings.xml (localized string resources)</li><li>PROJECT_NAME/app/src/main/java/YOUR/REVERSE/DOMAIN_NAME/MainActivity.kt (where the code starts)</li></ul><p>We had to traverse 8 levels deep just to get to our main source code! And that’s before adding additional folders to better organize the code. Now, Android Studio and GitHub do collapse directories if they don’t contain any additional files, but when traversing the project through a file explorer or the command line, it becomes more of a pain to get from point A to point B (unless you’re familiar with clever Linux tricks).</p><p>Setting up the base UI for the Android app took several steps. Unlike Android apps built with XML views, Jetpack Compose apps are built as single-activity apps (kind of like single-page apps, or SPAs). The activity dynamically changes content depending on the state of each composable. Creating a Hello World app from here will display the text on the top left of the screen without any additional styling. This is probably not what you want and would rather have your app look more professional using Google’s Material Design. By comparison, SwiftUI apps are more opinionated based on Apple’s Human Interface Guidelines. It may be more work to customize your UI to fit your app’s branding, but sticking with the defaults allows the UI to automatically adjust to the device. For example, a TabView would display on the bottom of iOS devices, while for iPads it would display either toward the top or on the side in an expanded format. Apple also takes care of centering the content and applying a certain amount of padding for you, so the UI looks cleaner.</p><figure><img alt="A larger graph showing the base components in Jetpack Compose to build a responsive app with navigation buttons" src="https://cdn-images-1.medium.com/max/567/1*k7YOn1ZbRZOjuQ1g1WEIQQ.png" /><figcaption>The base components in Jetpack Compose to build a responsive app with navigation buttons</figcaption></figure><figure><img alt="A smaller graph showing the base components in SwiftUI to build a responsive app with navigation buttons" src="https://cdn-images-1.medium.com/max/621/1*kkgZd4lQLzKAc4A0ImvBKA.png" /><figcaption>Meanwhile in SwiftUI…</figcaption></figure><p>On Android (and the web to an extent), you need to build a responsive layout manually. A scaffold is a good place to start since it holds the top app bar, bottom navigation bar, and main content together. Starting from the MainActivity, we build a MainLayout to act as the root composable in our app. Before we can create the scaffold, we need to take the screen width into account. Google’s recommendation for navigation is to use a navigation bar for compact screens, a navigation rail for medium screens, and a navigation drawer for expanded screens. For wide screens, the navigation drawer acts as the parent to the scaffold (alongside its side content). So, we need to create 2 separate composables for the drawer and scaffold. Inside the scaffold, we create 3 composables for the top bar, bottom bar, and the main content (which we’ll call the navigation graph for reasons that will be explained shortly). The top bar contains the app name and any globally accessible buttons for the app. As of this writing, the top app bar is still considered experimental in Material 3. The bottom bar holds all the navigation tabs, but only on small screens. The navigation rail we need for medium screens is defined as part of the main app content. Finally, the navigation graph holds all the composables corresponding to each screen, separated by routes, like routing in web apps. (In JC, it’s technically called a NavHost, but I like the name navigation graph more since it better represents how all the screens are connected in the app. XML view apps built with programmatic navigation let you visualize the navigation path between screens, similarly to how storyboards are visualized in UIKit for iOS.) In total, we needed to create 7 composables to display the equivalent of a TabView in SwiftUI! And it wasn’t easy to decipher this architecture based on what I read from the official Android docs or sample apps. Things like this explain how the Android app ended up with more code than the iOS app.</p><p>At least it wasn’t too hard to test since I could use a foldable to test all 3 screen sizes at once:</p><ul><li>Compact: folded, portrait mode</li><li>Medium: opened, portrait mode</li><li>Expanded: landscape mode (folded or opened)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S-YmOU6LpIDNx9Tw" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eVZGb_ePSQ6YxkHD" /><figcaption>Left to right: compact with a bottom bar &amp; medium width with a navigation rail</figcaption></figure><figure><img alt="Expanded width with a hamburger button to show the navigation drawer" src="https://cdn-images-1.medium.com/max/1024/0*kvqsfW7I09ZOyhwE" /><figcaption>Expanded width with a hamburger button to show the navigation drawer</figcaption></figure><p>Additionally, I can test how the app behaves when the <a href="https://developer.android.com/guide/topics/resources/runtime-changes">configuration changes</a>. Unlike iOS apps, Android apps require additional logic to handle cases where the UI changes, such as rotating the phone, opening or folding the screen, or switching between light and dark mode. By default, the app will recreate itself to render the UI appropriately. This causes all data stored within the current screen (known as an activity) to be wiped and reinitialized. There are several ways to prevent this. One is to persist the data on the device using libraries like DataStore or Room. If the data should stay in memory, you can store it in a Bundle, which is part of the activity manager’s memory, not the activity itself, right before the activity is destroyed. A higher-level approach is to store data in a ViewModel and follow the same MVVM (Model, View, ViewModel) architecture to separate the data from what’s shown on the UI. The ViewModel will automatically take care of saving data in memory before any configuration changes occur.</p><p>Kotlin is a great language for the reasons explained in part 1. I especially love how you can copy Java code from Stack Overflow and have Android Studio automatically convert it to Kotlin. I also love how there’s an option to convert a Java file to Kotlin to modernize a codebase. (Though nowadays, you can accomplish this with AI.) However, testing and maintaining Android code requires more effort compared to other platforms. Google loves deprecating SDKs regularly. (Need I remind you about the <a href="https://killedbygoogle.com/">Google Graveyard</a>?) This is a problem since Android code requires compatibility with older SDKs due to the nature of the Android ecosystem. I have an OCD with warnings in IDEs and try to resolve as many of them as possible, even if this increases the diffs in PRs. Xcode is fairly tame with warnings unless you install a separate linter, but I find Android Studio projects to be the toughest to stay warning-free. Testing Android apps thoroughly requires you to test with multiple device types, manufacturers, and Android versions. I’ve had instances where an Android app would crash, but only on a specific SDK. Android versions before and after would work just fine.</p><figure><img alt="All the warnings detected in Android Studio" src="https://cdn-images-1.medium.com/max/805/1*I-k3Cyu6ZjRHURdh-4qZWg.png" /><figcaption>All the warnings detected in Android Studio</figcaption></figure><p>Signing Android apps is a simpler process compared to iOS, but there are still a couple of gotchas. There are two file formats: APK and AAB (aka app bundle). APKs are the traditional way to build Android apps and can be installed directly on devices. These are still useful for testing apps on devices and are required for certain app stores. But to publish your app on the Play Store, Google requires apps to be submitted as AABs. App bundles automatically generate APKs that are optimized for specific devices, resulting in smaller app sizes and faster installs. APKs are generated by running <strong>gradle assemble&lt;Build Variant&gt;</strong>, while AABs are generated by running <strong>gradle bundle&lt;Build Variant&gt;</strong>. With APKs, apps are signed using a signing key. Keys are managed using Java’s Keystore. A default keystore is automatically created when you install Android Studio for running apps locally. But a separate release keystore needs to be created to sign apps with the right amount of security. Google recommends setting the expiration time for keystores to 25–30 years, so renewing them isn’t as much of a necessity compared to certs and profiles on iOS.</p><figure><img alt="Signing an app with Play App Signing" src="https://cdn-images-1.medium.com/max/1024/0*x-PZQDOnob0ESRfw.png" /><figcaption>Signing an app with Play App Signing, <a href="https://developer.android.com/studio/publish/app-signing#app-signing-google-play">source</a></figcaption></figure><p>One downside to publishing APKs is that the same signing key must be used to submit new versions of your app. If you lose the key, you won’t be able to update your app anymore. With app bundles, you sign your app using an upload key, which is also managed by the Keystore. When you upload your app to the Play Store, Google initiates <a href="https://developer.android.com/studio/publish/app-signing#app-signing-google-play">Play App Signing</a>, which involves validating the AAB, generating optimized APKs, and signing these APKs using their signing key. Now Google owns the signing key. If you lose your upload key, you can request a new key on the Google Play Console without losing your ability to update your app. Knowing these different keystores is important since each one has a different SHA fingerprint. Certain features, like OAuth or deep links, require entering the SHA1 or SHA256 of the keystore. And the debug, upload, and signing keystores must be entered separately. You can find Google’s fingerprints for their signing key on the Google Play Console.</p><figure><img alt="All the certificate fingerprints for Google’s signing key" src="https://cdn-images-1.medium.com/max/1024/1*bmM6ecRVpqqb2JqOlu5QPA.png" /><figcaption>All the certificate fingerprints for Google’s signing key</figcaption></figure><p>Side note: When updating your app, the version code must increase. The version name doesn’t matter aside from distinguishing versions on the Play Store. The max version code you can submit is 2,100,000,000. So hopefully, you have checks and balances in place to make sure a disgruntled team member doesn’t upload an app with this max value. 😉</p><p>Another thing to consider is that all release builds are minified using R8 and ProGuard. R8 is Google’s app optimizer to minify and obfuscate builds. ProGuard is an open-source tool that controls which resources are minified. Xcode and various web tools handle the minification process for you, but Android apps require a little more work to ensure the final build doesn’t crash due to aggressive minification. This is often a step developers forget since these issues don’t pop up on debug builds. But this is why it’s important to test a release build before it goes into production! When I first uploaded EZ Recipes to the Play Store, I saw all the pre-release reports crash on launch. Unfortunately, the crash logs were obfuscated, so I couldn’t tell what caused the crash.</p><blockquote>Exception java.lang.NullPointerException: Parameter specified as non-null is null: method u3.c.a, parameter &lt;this&gt;<br> at com.abhiek.ezrecipes.utils.StringExtensionsKt.a (StringExtensionsKt.java:3)<br> at com.abhiek.ezrecipes.ui.recipe.RecipeTitleKt.RecipeTitle (RecipeTitleKt.java:157)<br> at com.abhiek.ezrecipes.ui.recipe.RecipeKt.Recipe (RecipeKt.java:620)<br> at …</blockquote><p>I got confused since I never got a crash while testing the app on the emulator, but I eventually realized that I could run a release build locally by temporarily adding the keystore credentials to build.gradle.kts.</p><pre>android {<br>    ...<br>    signingConfigs {<br>        create(&quot;release&quot;) {<br>            storeFile = file(&quot;${project.rootDir}/../../keystore.jks&quot;)<br>            storePassword = &quot;***&quot;<br>            keyAlias = &quot;key1&quot;<br>            keyPassword = &quot;***&quot;<br>        }<br>    }<br><br>    buildTypes {<br>        release {<br>            ...<br>            signingConfig = signingConfigs.getByName(&quot;release&quot;)<br>        }<br>    }<br>    ...<br>}</pre><p>By doing so, I reproduced the crash, but I still wasn’t sure what was causing it. Through searching Stack Overflow, I figured out the reason was that I was minifying data classes that needed to be parsed from API responses. If the class and properties don’t match the JSON received, the app won’t know how to convert them to GSON (Google’s JSON library). I added a keep rule for all the model files in my project, and that fixed the crash, so now my app can be promoted to prod.</p><pre>-keep class com.abhiek.ezrecipes.data.models.** { *; }</pre><p>Since then, I’ve had to add some additional ProGuard rules to fix crashes due to certain dependencies like Retrofit. Even though this step was initially frustrating due to how close I was to a prod release, I’m glad I experienced this with a side project. This is knowledge I can keep handy when I’m building Android apps at work or helping other teams understand why their apps aren’t working in prod.</p><p>As usual, you can view the recipe app in these repos:</p><ul><li>iOS: <a href="https://github.com/Abhiek187/ez-recipes-ios">https://github.com/Abhiek187/ez-recipes-ios</a></li><li>Android: <a href="https://github.com/Abhiek187/ez-recipes-android">https://github.com/Abhiek187/ez-recipes-android</a></li><li>Web: <a href="https://github.com/Abhiek187/ez-recipes-web">https://github.com/Abhiek187/ez-recipes-web</a></li><li>Server: <a href="https://github.com/Abhiek187/ez-recipes-server">https://github.com/Abhiek187/ez-recipes-server</a></li></ul><p>And check out the published apps:</p><ul><li>Android: <a href="https://play.google.com/store/apps/details?id=com.abhiek.ezrecipes">https://play.google.com/store/apps/details?id=com.abhiek.ezrecipes</a></li><li>Web: <a href="https://ez-recipes-web.onrender.com/">https://ez-recipes-web.onrender.com/</a></li><li>Server: <a href="https://ez-recipes-server.onrender.com/">https://ez-recipes-server.onrender.com/</a></li></ul><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da301053c933" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Wrote the Same App Part 4: iOS Exclusive Features]]></title>
            <link>https://medium.com/@Abhiek187/i-wrote-the-same-app-part-4-ios-exclusive-features-952a99745012?source=rss-38566b972440------2</link>
            <guid isPermaLink="false">https://medium.com/p/952a99745012</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[codesign]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Abhishek Chaudhuri]]></dc:creator>
            <pubDate>Sun, 20 Jul 2025 21:35:32 GMT</pubDate>
            <atom:updated>2025-07-20T21:38:03.736Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="EZ Recipes logo" src="https://cdn-images-1.medium.com/max/300/1*UdcU28noobFcm3N2lLyn_w.png" /><figcaption>EZ Recipes logo</figcaption></figure><p>Let’s explore what made developing the EZ Recipes iOS app special. For more context on how the app was built, please check out the previous parts in this series:</p><ul><li><a href="https://medium.com/@Abhiek187/a67d1ef4c5e0">Part 1 — MVP</a></li><li><a href="https://medium.com/@Abhiek187/034f504bf5b4">Part 2 — Post MVP</a></li></ul><p>For all other platforms, feel free to check out these articles:</p><ul><li><a href="https://medium.com/@Abhiek187/da301053c933">Android</a></li><li><a href="https://medium.com/@Abhiek187/i-wrote-the-same-app-part-6-web-exclusive-features-c9c9c134b882">Web</a></li></ul><h3>iOS</h3><p>We’ll start with iOS. Whenever you create a new project in Xcode, a .xcodeproj directory is created. Macs will treat this like a file and allow it to be opened directly via double-clicking. However, if you inspect this on any other platform, like GitHub, it’s just a directory with some metadata. Xcode has multiple of these “fake directories” (XCFrameworks are another example of this), but it’s important to understand what these directories contain for version control.</p><p>One of the most important, and often confusing, files for iOS development is <strong>project.pbxproj</strong> inside the xcodeproj directory:</p><pre>// !$*UTF8*$!<br>{<br> archiveVersion = 1;<br> classes = {<br> };<br> objectVersion = 70;<br> objects = {<br>/* The majority of the file lives in here */<br> };<br> rootObject = F12C1C1F2904951600C3302B /* Project object */;<br>}</pre><p>Xcode automatically manages this file. But unlike the .idea folder in JetBrains IDEs, this file cannot be git ignored since it contains essential information about how to open and build your iOS app. This file is subject to merge conflicts if multiple people are working on the app at once. Any slight corruption will prevent you from opening the project in Xcode. The file must be edited manually using a separate text editor. As a result, many iOS developers treat this file like it’s machine code. But in reality, project.pbxproj is an old-style plist file written in plain text. This is different from regular plist files, which are written in XML. The file’s content resembles JSON and can be converted into valid JSON using the plutil tool in the terminal. It contains a list of objects containing all the metadata for the Xcode project (build settings, dependencies, files on disk, etc.), with comments explaining what each object represents (via the <strong>isa</strong> property). For example, <strong>XCRemoteSwiftPackageReference</strong> objects contain all the SPM dependencies: the alternative to listing them in a Package.swift file:</p><pre>/* Begin XCRemoteSwiftPackageReference section */<br>  5E0405A52DA0CFF300C3B312 /* XCRemoteSwiftPackageReference &quot;AlertToast&quot; */ = {<br>   isa = XCRemoteSwiftPackageReference;<br>   repositoryURL = &quot;https://github.com/elai950/AlertToast.git&quot;;<br>   requirement = {<br>    kind = upToNextMajorVersion;<br>    minimumVersion = 1.3.9;<br>   };<br>  };<br>  F12C1C642904D16600C3302B /* XCRemoteSwiftPackageReference &quot;Alamofire&quot; */ = {<br>   isa = XCRemoteSwiftPackageReference;<br>   repositoryURL = &quot;https://github.com/Alamofire/Alamofire.git&quot;;<br>   requirement = {<br>    kind = upToNextMajorVersion;<br>    minimumVersion = 5.0.0;<br>   };<br>  };<br>  F17A80A32B78764300E811C8 /* XCRemoteSwiftPackageReference &quot;MultiPicker&quot; */ = {<br>   isa = XCRemoteSwiftPackageReference;<br>   repositoryURL = &quot;https://github.com/toastersocks/MultiPicker.git&quot;;<br>   requirement = {<br>    kind = upToNextMajorVersion;<br>    minimumVersion = 1.0.0;<br>   };<br>  };<br>/* End XCRemoteSwiftPackageReference section */<br><br>/* Begin XCSwiftPackageProductDependency section */<br>  5E0405A62DA0CFF300C3B312 /* AlertToast */ = {<br>   isa = XCSwiftPackageProductDependency;<br>   package = 5E0405A52DA0CFF300C3B312 /* XCRemoteSwiftPackageReference &quot;AlertToast&quot; */;<br>   productName = AlertToast;<br>  };<br>  F12C1C652904D16700C3302B /* Alamofire */ = {<br>   isa = XCSwiftPackageProductDependency;<br>   package = F12C1C642904D16600C3302B /* XCRemoteSwiftPackageReference &quot;Alamofire&quot; */;<br>   productName = Alamofire;<br>  };<br>  F17A80A42B78764300E811C8 /* MultiPicker */ = {<br>   isa = XCSwiftPackageProductDependency;<br>   package = F17A80A32B78764300E811C8 /* XCRemoteSwiftPackageReference &quot;MultiPicker&quot; */;<br>   productName = MultiPicker;<br>  };<br>/* End XCSwiftPackageProductDependency section */</pre><p>I once encountered an issue in the pipeline where the app was failing to build, despite it working on my machine. It turns out the issue was that my project file was referencing a file using an absolute path instead of a relative path. It added my full user directory to the Xcode project, which wouldn’t exist in the pipeline or on someone else’s machine. Manually editing the path fixed the issue.</p><pre>/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */<br>  5E5ADA922D7CD3B1001D415C /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {<br>   isa = PBXFileSystemSynchronizedBuildFileExceptionSet;<br>   membershipExceptions = (<br>    PrivacyInfo.xcprivacy,<br>   );<br>   target = F12C1C262904951600C3302B /* EZ Recipes */;<br>  };<br>  5E5ADA942D7CD62A001D415C /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {<br>   isa = PBXFileSystemSynchronizedBuildFileExceptionSet;<br>   membershipExceptions = (<br>    SnapshotHelper.swift,<br>   );<br>   target = F12C1C402904951B00C3302B /* EZ RecipesUITests */;<br>  };<br>/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */<br><br>/* Begin PBXFileSystemSynchronizedRootGroup section */<br>  5E5AD98C2D7CD1B8001D415C /* .github */ = {<br>    isa = PBXFileSystemSynchronizedRootGroup;<br>    explicitFileTypes = {};<br>    explicitFolders = ();<br>    name = .github;<br>    path = ../.github;<br>    sourceTree = &quot;&lt;group&gt;&quot;;<br>  };<br>  5E5AD9B62D7CD24B001D415C /* screenshots */ = {<br>    isa = PBXFileSystemSynchronizedRootGroup;<br>    explicitFileTypes = {};<br>    explicitFolders = ();<br>    name = screenshots;<br>    path = ../screenshots;<br>    sourceTree = &quot;&lt;group&gt;&quot;;<br>  };<br>  5E5AD9CB2D7CD295001D415C /* fastlane */ = {<br>    isa = PBXFileSystemSynchronizedRootGroup;<br>    exceptions = (<br>      5E5ADA942D7CD62A001D415C /* PBXFileSystemSynchronizedBuildFileExceptionSet */,<br>    );<br>    explicitFileTypes = {<br>      Appfile = text.script.ruby;<br>      Fastfile = text.script.ruby;<br>      Matchfile = text.script.ruby;<br>      Pluginfile = text.script.ruby;<br>      Snapfile = text.script.ruby;<br>    }; <br>    explicitFolders = ();<br>    path = fastlane;<br>    sourceTree = &quot;&lt;group&gt;&quot;;<br>  };<br>  5E5AD9CD2D7CD366001D415C /* EZ RecipesUITests */ = {<br>    isa = PBXFileSystemSynchronizedRootGroup;<br>    explicitFileTypes = {};<br>    explicitFolders = ();<br>    path = &quot;EZ RecipesUITests&quot;;<br>    sourceTree = &quot;&lt;group&gt;&quot;;<br>  };<br>  5E5AD9E12D7CD36B001D415C /* EZ RecipesTests */ = {<br>    isa = PBXFileSystemSynchronizedRootGroup;<br>    explicitFileTypes = {};<br>    explicitFolders = ();<br>    path = &quot;EZ RecipesTests&quot;;<br>    sourceTree = &quot;&lt;group&gt;&quot;;<br>  };<br>  5E5ADA482D7CD3B1001D415C /* EZ Recipes */ = {<br>    isa = PBXFileSystemSynchronizedRootGroup;<br>    exceptions = (<br>      5E5ADA922D7CD3B1001D415C /* PBXFileSystemSynchronizedBuildFileExceptionSet */,<br>    );<br>    explicitFileTypes = {};<br>    explicitFolders = ();<br>    path = &quot;EZ Recipes&quot;;<br>    sourceTree = &quot;&lt;group&gt;&quot;;<br>  };<br>/* End PBXFileSystemSynchronizedRootGroup section */</pre><p>When using groups in Xcode, every file will be listed in the pbxproj file. Merge conflicts often arise when multiple people add files to the project. The file gets bloated very quickly. But by converting all the groups to folders, only the folder references (<strong>PBXFileSystemSynchronizedRootGroup</strong>) are included in the project file, and Xcode automatically adds each file on disk to the build process. Any files that shouldn’t be built, like Fastlane or README files, are added to a <strong>PBXFileSystemSynchronizedBuildFileExceptionSet</strong>. When I made this switch in my app, it cut down my project file in half! With all that being said, it can still be difficult to automate changes to this file directly due to the format’s age. Even if you use the built-in plist tools, there isn’t a way to convert the file back to its original format, only the modern plist format.</p><p>Something I enjoyed doing on all platforms, but particularly on iOS, was exploring how the app saved data on the device. iOS provides a few options depending on what kind of data needs to be stored. I used UserDefaults to store simple key-value pairs, SwiftData (formerly Core Data) to store more complex, structured data, and the Keychain to safely encrypt sensitive data like ID tokens. UserDefaults and SwiftData are stored in an app-specific directory, while the Keychain is global to the device. The exact paths vary whether you’re on the simulator, a real device, or in a SwiftUI preview, but if you know the path, you can freely explore the file structure. I was able to inspect each file and learned the following:</p><figure><img alt="Files stored in the iOS simulator." src="https://cdn-images-1.medium.com/max/1024/1*HFktam1x94nRuBf_3_Dv-A.png" /><figcaption>Files stored in the iOS simulator. Application Support contains SwiftData, Caches contains network cache, and Preferences contains UserDefaults.</figcaption></figure><ul><li>UserDefaults is saved as a binary plist. It can’t be read directly, but plist tools can parse it.</li></ul><pre>Dict {<br>    terms = bplist00?(encrypted dictionary here...)<br>    recipesViewed = 10<br>    lastVersionPromptedForReview = 2.0.1<br>}</pre><ul><li>SwiftData is just an SQLite file under the hood. You can use whatever SQLite tools you want to view the tables. Knowing the store path was very important when I was migrating from Core Data to SwiftData, since both save data to different locations by default. Below is an example of me querying SwiftData to get all the recently stored recipes. Apple prefixes tables and column names with Z as a <a href="https://stackoverflow.com/questions/15198685/why-does-core-data-name-the-tables-and-attributes-it-creates-in-sqlite-with-a-z">naming convention</a>. Additional columns are used to create a composite key and track version changes.</li></ul><figure><img alt="Querying SwiftData using SQLite" src="https://cdn-images-1.medium.com/max/572/1*yMZlshuRKQnSg6G1_jmMFA.png" /><figcaption>Querying SwiftData using SQLite</figcaption></figure><ul><li>The Keychain is also an SQLite file, but more encrypted and stored globally on the device instead of per-app. It can only be decrypted using a private key owned by the app, which can take the form of a passcode or biometrics, depending on how you want to secure your data. Through some research, I was able to decode what some of the tables and columns represent and correlate them to the features available in the Mac’s Keychain. This helped me be more comfortable with Apple’s admittedly obtuse Keychain library. I also learned that data isn’t automatically deleted from the Keychain if you uninstall the app. This may be useful to recover data if you later decide to reinstall the app, but it is good to know if your company has strict data retention policies. In the screenshot below, there are 4 main tables where data is stored: <strong>keys</strong> for keys, <strong>cert</strong> for certificates, <strong>genp</strong> for generic passwords, and <strong>inet</strong> for internet passwords.</li></ul><figure><img alt="Querying the Keychain using SQLite" src="https://cdn-images-1.medium.com/max/566/1*nGWDDP5WEvYQNx244U2sOQ.png" /><figcaption>Querying the Keychain using SQLite (the contents aren’t printed since most of it is encrypted)</figcaption></figure><p>Lastly, each platform has its requirements for packaging apps for production. On iOS, all apps must be signed using a provisioning profile, certificate, and private key. Certificates authorize the developer alongside the private key and expire after 3 years, while provisioning profiles authorize the app and expire every year. For personal accounts, there are two types of certificates: <strong>developer</strong> and <strong>distribution</strong>. Developer certs are used for testing apps locally, while distribution certs are used to release apps on the App Store or through TestFlight. These are stored in the Mac’s Keychain. There are 3 types of provisioning profiles (excluding those for enterprise accounts): <strong>developer</strong>, <strong>ad-hoc</strong>, and <strong>app store</strong>. Developer profiles are used for local testing, Ad hoc profiles are used to test on specific devices (such as a QA tester’s device or a remote device farm), and app store profiles are used to publish apps on the App Store or TestFlight. Each profile contains:</p><ul><li>The developer’s certificate (the Who)</li><li>The app ID (the What: a combination of the app’s bundle ID and the developer’s team ID)</li><li>A list of supported devices (the Where: either individual unique device IDs (UDIDs) or all devices for developer and app store profiles)</li><li>An expiration date (the When)</li><li>And the list of entitlements supported by the app (the How)</li></ul><p><em>(Big shoutout to </em><a href="https://developer.apple.com/documentation/technotes/tn3125-inside-code-signing-provisioning-profiles"><em>this technote</em></a><em> from Apple for breaking down provisioning profiles into these categories!)</em></p><figure><img alt="An Apple Development certificate stored in the Keychain" src="https://cdn-images-1.medium.com/max/470/1*W7WbkdmHvk-xqj_5SxsW1A.png" /><figcaption>An Apple Development certificate stored in the Keychain</figcaption></figure><figure><img alt="An Apple Development private key stored in the Keychain" src="https://cdn-images-1.medium.com/max/495/1*WjUBwqqZ53qvaCWIVLc6Lw.png" /><figcaption>An Apple Development private key stored in the Keychain</figcaption></figure><p>Provisioning Profiles are encrypted plist files. Some of it can be decrypted by running <strong>security cms -D -i UUID.mobileprovision</strong>, where UUID is the unique identifier of the profile.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;!DOCTYPE plist PUBLIC &quot;-//Apple//DTD PLIST 1.0//EN&quot; &quot;http://www.apple.com/DTDs/PropertyList-1.0.dtd&quot;&gt;<br>&lt;plist version=&quot;1.0&quot;&gt;<br>&lt;dict&gt;<br> &lt;key&gt;AppIDName&lt;/key&gt;<br> &lt;string&gt;XC com abhiek EZ-Recipes&lt;/string&gt;<br> &lt;key&gt;ApplicationIdentifierPrefix&lt;/key&gt;<br> &lt;array&gt;<br> &lt;string&gt;UF6E5BVT98&lt;/string&gt;<br> &lt;/array&gt;<br> &lt;key&gt;CreationDate&lt;/key&gt;<br> &lt;date&gt;2025-03-14T00:27:56Z&lt;/date&gt;<br> &lt;key&gt;Platform&lt;/key&gt;<br> &lt;array&gt;<br>  &lt;string&gt;iOS&lt;/string&gt;<br>  &lt;string&gt;xrOS&lt;/string&gt;<br>  &lt;string&gt;visionOS&lt;/string&gt;<br> &lt;/array&gt;<br> &lt;key&gt;IsXcodeManaged&lt;/key&gt;<br> &lt;true/&gt;<br> &lt;key&gt;DeveloperCertificates&lt;/key&gt;<br> &lt;array&gt;<br>  &lt;data&gt;...&lt;/data&gt;<br> &lt;/array&gt;<br><br> &lt;key&gt;DER-Encoded-Profile&lt;/key&gt;<br> &lt;data&gt;...&lt;/data&gt;<br>        <br> &lt;key&gt;Entitlements&lt;/key&gt;<br> &lt;dict&gt;<br>    <br>    &lt;key&gt;application-identifier&lt;/key&gt;<br>  &lt;string&gt;UF6E5BVT98.com.abhiek.EZ-Recipes&lt;/string&gt;<br>    <br>    &lt;key&gt;keychain-access-groups&lt;/key&gt;<br>  &lt;array&gt;<br>    &lt;string&gt;UF6E5BVT98.*&lt;/string&gt;<br>  &lt;/array&gt;<br>    <br>    &lt;key&gt;get-task-allow&lt;/key&gt;<br>  &lt;true/&gt;<br>    <br>    &lt;key&gt;com.apple.developer.team-identifier&lt;/key&gt;<br>  &lt;string&gt;UF6E5BVT98&lt;/string&gt;<br><br> &lt;/dict&gt;<br> &lt;key&gt;ExpirationDate&lt;/key&gt;<br> &lt;date&gt;2026-03-14T00:27:56Z&lt;/date&gt;<br> &lt;key&gt;Name&lt;/key&gt;<br> &lt;string&gt;iOS Team Provisioning Profile: com.abhiek.EZ-Recipes&lt;/string&gt;<br> &lt;key&gt;ProvisionedDevices&lt;/key&gt;<br> &lt;array&gt;<br>  &lt;string&gt;...&lt;/string&gt;<br> &lt;/array&gt;<br> &lt;key&gt;TeamIdentifier&lt;/key&gt;<br> &lt;array&gt;<br>  &lt;string&gt;UF6E5BVT98&lt;/string&gt;<br> &lt;/array&gt;<br> &lt;key&gt;TeamName&lt;/key&gt;<br> &lt;string&gt;Abhishek Chaudhuri&lt;/string&gt;<br> &lt;key&gt;TimeToLive&lt;/key&gt;<br> &lt;integer&gt;365&lt;/integer&gt;<br> &lt;key&gt;UUID&lt;/key&gt;<br> &lt;string&gt;f1a84b34-fb8d-488d-b145-c5a0f49bc54b&lt;/string&gt;<br> &lt;key&gt;Version&lt;/key&gt;<br> &lt;integer&gt;1&lt;/integer&gt;<br>&lt;/dict&gt;<br>&lt;/plist&gt;</pre><p>Unlike certificates, provisioning profiles aren’t stored in the Keychain. When you drag the profile into Xcode, it will be saved under a Provisioning Profiles directory. Certificates and provisioning profiles aren’t required to run apps on the simulator. They’re only required to test on physical devices, but an Apple Developer membership is required to generate certs and profiles for distribution. Generally, you would specify the cert and profile needed for each environment and only allow certain team members or the pipeline to sign the app. By default, Xcode will automatically generate a developer cert and profile when you first run the app. If you try running the app on a different Mac, the old certificate is revoked, and a new one is generated. This prevents you from running any developer apps installed on your phone until you rebuild them on the new Mac. Fastlane helps to <a href="https://docs.fastlane.tools/actions/match/">centralize all your certs and profiles</a> so you can reuse and automatically renew them for all your apps. Once your app is signed, it becomes an IPA, can be tested on TestFlight, and then promoted to the App Store.</p><p>As usual, you can view the recipe app in these repos:</p><ul><li>iOS: <a href="https://github.com/Abhiek187/ez-recipes-ios">https://github.com/Abhiek187/ez-recipes-ios</a></li><li>Android: <a href="https://github.com/Abhiek187/ez-recipes-android">https://github.com/Abhiek187/ez-recipes-android</a></li><li>Web: <a href="https://github.com/Abhiek187/ez-recipes-web">https://github.com/Abhiek187/ez-recipes-web</a></li><li>Server: <a href="https://github.com/Abhiek187/ez-recipes-server">https://github.com/Abhiek187/ez-recipes-server</a></li></ul><p>And check out the published apps:</p><ul><li>Android: <a href="https://play.google.com/store/apps/details?id=com.abhiek.ezrecipes">https://play.google.com/store/apps/details?id=com.abhiek.ezrecipes</a></li><li>Web: <a href="https://ez-recipes-web.onrender.com/">https://ez-recipes-web.onrender.com/</a></li><li>Server: <a href="https://ez-recipes-server.onrender.com/">https://ez-recipes-server.onrender.com/</a></li></ul><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=952a99745012" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Wrote the Same App Part 3: Platform Differences]]></title>
            <link>https://medium.com/@Abhiek187/i-wrote-the-same-app-part-3-platform-differences-4242c250b1f3?source=rss-38566b972440------2</link>
            <guid isPermaLink="false">https://medium.com/p/4242c250b1f3</guid>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[android-studio]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Abhishek Chaudhuri]]></dc:creator>
            <pubDate>Sat, 19 Jul 2025 21:03:40 GMT</pubDate>
            <atom:updated>2025-09-21T21:43:55.552Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="EZ Recipes logo" src="https://cdn-images-1.medium.com/max/300/1*UdcU28noobFcm3N2lLyn_w.png" /><figcaption>EZ Recipes logo</figcaption></figure><p>In the previous part, we completed building EZ Recipes on iOS, Android, and the web. This part will delve into some of the differences when building on each platform.</p><p>For more context on how the app was built, please check out the previous parts in this series:</p><ul><li><a href="https://medium.com/@Abhiek187/a67d1ef4c5e0">Part 1 — MVP</a></li><li><a href="https://medium.com/@Abhiek187/034f504bf5b4">Part 2 — Post MVP</a></li></ul><h3>IDEs</h3><figure><img alt="Left to right: Xcode, Android Studio, Visual Studio Code" src="https://cdn-images-1.medium.com/max/1024/1*91XuOd_x-caoOSR57c4Oaw.png" /><figcaption>Left to right: Xcode, Android Studio, Visual Studio Code</figcaption></figure><p>Let’s start with the IDE. Xcode and Android Studio are the de facto IDEs for iOS and Android development. Web apps can be built using any text editor, though VS Code is the most popular option. iOS development can only be done on a Mac. While Swift code can be run on any OS, Xcode and iOS libraries are only compatible with Macs. Even if you use cross-platform frameworks like React Native or Flutter, you’ll eventually need a Mac to sign and build your app for the App Store. If you only need the Mac for development, a good, affordable option is to get a Mac Mini with any accessories and monitors of your choice (since Apple-branded products tend to cost more).</p><p>Mobile development requires more resources compared to web development. Not only do you need a text editor, but you also need to install a simulator to run mobile apps on a device (unless you’re exclusively testing on a physical device). Xcode installs several simulators at once per iOS version. Android Studio, on the other hand, requires you to create the simulator (called the emulator) by hand. Since there are many more Android devices, there are more ways to customize the device for testing.</p><p>iOS simulators generally consume fewer resources compared to Android emulators. Simulators utilize some of the same resources used on your Mac to simulate iOS devices, such as networking settings and the Keychain. Emulators are full virtual machines running Android. All the settings are isolated from the host device. This includes networking, so there’s a special IP address 10.0.2.2 that proxies to your machine’s localhost 127.0.0.1 for testing local servers. Another thing to keep in mind for iOS development is that the iOS, Xcode, and macOS versions are tightly coupled. So, when one gets updated, they all need to be updated to maintain compatibility with each other.</p><p>Meanwhile, with web development, the code runs directly in the browser. A dev server can run in the background to automatically refresh (or hot reload) the content as the code changes. Swift and Kotlin code must be compiled before the newly updated code can be run. To alleviate this, SwiftUI and Jetpack Compose support previews to render views or composables in real time. The IDEs build the app in the background. Multiple previews can be generated to render the UI under different conditions, such as on different screen sizes, portrait vs. landscape, or light vs. dark mode. For web apps, testing these different configurations is more manual.</p><figure><img alt="Previews on different device types" src="https://cdn-images-1.medium.com/max/570/1*WO_K4BQSH-uGTTB0_s0k8g.png" /><figcaption>Previews on different device types</figcaption></figure><figure><img alt="Previews showing light vs. dark mode" src="https://cdn-images-1.medium.com/max/576/1*bkx318qbH_5bPRrQrAg2zg.png" /><figcaption>Previews showing light vs. dark mode</figcaption></figure><figure><img alt="Previews showing portrait vs. landscape mode" src="https://cdn-images-1.medium.com/max/1000/1*RMmZUxzuxJ9MLNJYS_7nWg.png" /><figcaption>Previews showing portrait vs. landscape mode</figcaption></figure><h3>CLI</h3><p>Being familiar with the command line is paramount to web development since it’s required to run apps without installing extensions. Knowing the command line is a good skill for Android developers as well, since there are several tools like ADB (Android debugger) to interact with Android devices (which are also built on Linux). Gradle commands can also be executed on the command line. However, none of this is required to run or build Android apps since Android Studio has GUI tools to help with that. As for Xcode, there’s no inline terminal built into the IDE. Any work on the CLI requires context switching away from Xcode. Xcode has a CLI tool called xcodebuild, but it’s more complex compared to NPM or Gradle. Many junior iOS developers don’t end up using the command line that much since Xcode takes care of all the heavy lifting for them, even committing to a Git repo. That being said, knowing how to build, test, and run apps in the CLI is important to automate these tasks in CI/CD pipelines.</p><h3>Dependencies</h3><p>All three platforms handle dependencies differently. Web dependencies are handled using NPM. Packages are listed in package.json and installed on disk in the node_modules directory. Web apps start very bare, so many dependencies need to be installed to implement all the necessary features for a website. There are also dev dependencies that are only needed for local development, such as linting or testing. Angular is an opinionated framework, so it provides most of the libraries needed for my recipe app. For something lightweight like React, it’s up to the developer to choose the tools they need to install.</p><p>Gradle dependencies are defined in a build.gradle file. Gradle files can be written using either Groovy or Kotlin. I chose to use Kotlin since it’s the same language used for the main app and supports Intellisense once everything is built. Like with web apps, many dependencies will need to be installed and updated over the lifespan of an app. Gradle is more complex than NPM since it can fully customize the build process for an Android app as well as any libraries or submodules. The downside is that the syntax can be inconsistent for different tasks, and it can be hard to troubleshoot since many tasks are run under the hood.</p><p>iOS apps don’t require as many dependencies compared to the other platforms. Apple provides most functionality using built-in libraries like Foundation. A simple import for each library is all that is needed to get access to all the methods in Swift. For third-party libraries, there are a couple of options iOS developers can choose from. Swift Package Manager (SPM) is the recommended tool since it’s native to Swift. One caveat is that listing dependencies is different for iOS apps compared to regular Swift libraries. Swift libraries list the dependencies inside a Package.swift file and build tasks are executed using the Swift CLI. This integrates better with CI/CD pipelines.</p><figure><img alt="Swift Package Manager in Xcode" src="https://cdn-images-1.medium.com/max/1015/1*_iATYb-qyJ6m1tNvqfJdrA.png" /><figcaption>Swift Package Manager in Xcode</figcaption></figure><p>In iOS apps, dependencies are listed within Xcode’s GUI and fetched using xcodebuild. This generates a lock file called Package.resolved, but this shouldn’t be edited directly since it lists sub-dependencies as well. I use GitHub’s Dependabot tool to automatically update dependencies in my projects, but it doesn’t currently support SPM in iOS projects. Xcode provides an option to update packages to their latest versions, but I couldn’t find an equivalent command in the CLI. Swift packages are fetched directly from GitHub using tagged versions, so a script would need to be created to get the latest version and update the Xcode project file while ensuring the app can still be built.</p><p>Another option besides SPM is CocoaPods. CocoaPods uses Ruby to fetch all the dependencies and uses a similar style to Gradle for customizing the build process. This was the main way to handle dependencies before SPM, but now it’s not recommended for newer projects. First, all pods will be <a href="https://blog.cocoapods.org/CocoaPods-Specs-Repo/">read-only by the end of 2026</a>, effectively ending development for CocoaPods. Second, it transforms your Xcode project into a workspace, which requires opening a separate file and running pod install to ensure the project stays in sync with all the latest changes. This extra effort makes maintaining pods more cumbersome than simply listing dependencies using SPM. For closed-source libraries, a third option is to package the library as an XCFramework. This is a fat binary that contains all the compiled code across different architectures, such as ARM or x86. All apps on the App Store must be compiled for ARM since that’s only supported on mobile devices. However, if you’re on an Intel Mac and want to run the app in the simulator, it needs to be built using x86. The XCFramework takes care of selecting the right architecture depending on the build destination and automatically strips unnecessary architectures from the final app build. Due to its closed-source nature, there’s no way to look at the underlying code outside of header files. It’s also more difficult to keep track of the version of an XCFramework, and new versions must be installed manually.</p><h3>Debugging</h3><p>All three platforms support debugging using breakpoints. I found Xcode the most user-friendly when it comes to creating breakpoints since all you have to do is click the line numbers to add breakpoints and run the app. On Android Studio and VS Code, you have to run a special debugger to enable the breakpoints. While it’s not hard to do once you’re familiar with the process, a new developer may not be aware that these tools exist. They may be tempted to add a bunch of print statements instead. Debugging on the browser involves adding debugger statements, but these can litter your codebase, whereas breakpoints are exclusive to just the IDE.</p><p>That being said, I find the actual debugging process is most obtuse on Xcode. Most other editors show all the variables within the scope of the breakpoint, allowing you to analyze whether each variable is set properly. However, in Xcode, the debugger is powered by LLVM. It’s a powerful tool, but it has its syntax for inspecting variables. Most of the time, you could just “po” a variable name to view its value. But this doesn’t work all the time. Furthermore, Xcode’s debugger cannot view all variables in scope at a glance. The variable tree it provides is limited and doesn’t properly output all variable types since many of Swift’s types are more complex under the hood than traditional C primitives.</p><p>In the example below, I put a breakpoint in a function that logs network calls. When I try to inspect urlRequest in the bottom left, I don’t see any of the public properties, such as httpMethod or url. I have to use the <strong>po</strong> (print object) command in the lldb console in the bottom right to inspect these variables (while taking into account optional values).</p><figure><img alt="Debugging a logging function in Xcode" src="https://cdn-images-1.medium.com/max/1024/1*dshpMsAcwube5GqMddLyGQ.png" /><figcaption>Debugging a logging function in Xcode</figcaption></figure><p>The dev tools are valuable for debugging web apps. They allow developers to view the source code, run JavaScript, view logs, edit CSS styling, and view network calls, among other things. Cross-platform tools do provide their dev tools for mobile, but they don’t provide the same functionality as web apps. For native development, inspecting apps can be done within Xcode and Android Studio, but is again limited. Since the code is compiled, there isn’t a direct mapping from the source code to what’s displayed on screen. Even with hot reloading, the code must be compiled again to show up on the mobile app, making it more sluggish compared to web apps. SwiftUI and Jetpack Compose’s previews do help with adjusting the UI in real-time, but won’t fully match the app’s behavior on physical devices.</p><p>Logs can be viewed when running simulators in Xcode and Android Studio; however, they’re harder to retrieve when you’re testing apps on physical devices. These logs are stored on the device, and external tools must be used to retrieve these logs. If your device happens to be connected to a PC, you can use the Console app for iOS or ADB on Android to view the logs as you run the app. However, what happens if a regular user encounters a bug in your app? Ideally, you should be able to determine the root cause and reproduce the issue. It’s a pain to ask your users to connect their devices, reproduce the bug themselves, and email the logs to you. Crash reports can be retrieved from the app stores, but many bugs may not result in a crash, just a degraded UX. You can configure the app to stream logs to a server or report issues by sending the log files, but this is dependent on the user having a stable network connection, which isn’t guaranteed for mobile apps. For EZ Recipes, while I don’t have a direct way to retrieve the logs on users’ devices, I can view all the network logs from my server. This helps me search for error logs and understand what caused the issue. To respect the user’s privacy, I don’t log PII and redact any sensitive information that gets passed to an API call, such as the user’s password or refresh token.</p><h3>AI</h3><figure><img alt="Clockwise from the top left: ChatGPT, GitHub Copilot, Gemini" src="https://cdn-images-1.medium.com/max/799/1*S2Kj0Jllipm4Biz2-EGdWw.png" /><figcaption>Clockwise from the top left: ChatGPT, GitHub Copilot, Gemini</figcaption></figure><p>When all else fails, all IDEs provide AI tools to assist with development. VS Code offers many extensions to work with the AI tool of your choice, such as GitHub Copilot, Gemini, or Amazon Q. Android Studio comes built-in with Google’s own Gemini. And Xcode recently added support for ChatGPT within Xcode as of version 26. All these tools allow you to specify the context to better understand your code for each prompt. Apple has actually taken it a step further and prompt-engineered Xcode’s Coding Assistant to ask clarifying questions before writing any code. This helps to make sure the AI has enough context to answer the user’s prompt. You can learn more about the system prompts used from <a href="https://peterfriese.dev/blog/2025/reveng-xcode-coding-intelligence/">this blog post</a>.</p><p>From my experience, ChatGPT has been the most reliable AI tool for providing detailed troubleshooting tips for any problems I’ve encountered. It’s not perfect; half the time, it ends up hallucinating when you get deep into a conversation, but it’s been a great supplement to Google or Stack Overflow when I encounter an issue that’s not easily searchable. At the very least, it has helped me learn new things about web and mobile development that the official documentation doesn’t explain too well. When I used Gemini in Android Studio, I found it harder to share the exact context I needed for my prompt, especially since Android code tends to be more verbose. This causes the AI to make a lot of assumptions about my code that tend not to work as often compared to the same prompt in ChatGPT. Until recently, the way Android Studio displayed the output was very choppy, the code wasn’t formatted well, and some text wouldn’t wrap properly. I also noticed that Gemini would repeat the same mannerisms for every response (such as saying Ok, at the start), whereas ChatGPT would be more spontaneous with its responses to give it a little more personality. Of course, your mileage may vary, and I’m sure you can address many of these issues with fine-tuned prompt engineering. But at the end of the day, I enjoy solving problems on my own, so I try to rely on my critical thinking first before consulting the AI Gods.</p><p>There are many more differences between iOS, Android, and web development, but I’ll save those for the next few parts. Feel free to jump ahead to whatever platform you’re most interested in learning about:</p><ul><li><a href="https://medium.com/@Abhiek187/i-wrote-the-same-app-part-4-ios-exclusive-features-952a99745012">iOS</a></li><li><a href="https://medium.com/@Abhiek187/da301053c933">Android</a></li><li><a href="https://medium.com/@Abhiek187/i-wrote-the-same-app-part-6-web-exclusive-features-c9c9c134b882">Web</a></li></ul><p>As always, you can view the recipe app in these repos:</p><ul><li>iOS: <a href="https://github.com/Abhiek187/ez-recipes-ios">https://github.com/Abhiek187/ez-recipes-ios</a></li><li>Android: <a href="https://github.com/Abhiek187/ez-recipes-android">https://github.com/Abhiek187/ez-recipes-android</a></li><li>Web: <a href="https://github.com/Abhiek187/ez-recipes-web">https://github.com/Abhiek187/ez-recipes-web</a></li><li>Server: <a href="https://github.com/Abhiek187/ez-recipes-server">https://github.com/Abhiek187/ez-recipes-server</a></li></ul><p>And check out the published apps:</p><ul><li>Android: <a href="https://play.google.com/store/apps/details?id=com.abhiek.ezrecipes">https://play.google.com/store/apps/details?id=com.abhiek.ezrecipes</a></li><li>Web: <a href="https://ez-recipes-web.onrender.com/">https://ez-recipes-web.onrender.com/</a></li><li>Server: <a href="https://ez-recipes-server.onrender.com/">https://ez-recipes-server.onrender.com/</a></li></ul><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4242c250b1f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Wrote the Same App Part 2: Post MVP & Results]]></title>
            <link>https://medium.com/@Abhiek187/i-wrote-the-same-app-part-2-post-mvp-results-034f504bf5b4?source=rss-38566b972440------2</link>
            <guid isPermaLink="false">https://medium.com/p/034f504bf5b4</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[full-text-search]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Abhishek Chaudhuri]]></dc:creator>
            <pubDate>Sat, 19 Jul 2025 21:02:18 GMT</pubDate>
            <atom:updated>2025-12-27T18:45:37.270Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="EZ Recipes logo" src="https://cdn-images-1.medium.com/max/300/1*UdcU28noobFcm3N2lLyn_w.png" /><figcaption>EZ Recipes logo</figcaption></figure><p>In the <a href="https://medium.com/@Abhiek187/a67d1ef4c5e0">previous part</a>, we built the MVP for my recipe app called EZ Recipes. Now, we’re going to polish it and add some enhancements.</p><h3>Post MVP</h3><p>Creating the MVP for all the recipe apps took around 3–4 months, which is normal for most MVPs. (Keep in mind that I created these apps before ChatGPT was released in late 2022.) After taking some breaks, I was ready to start adding more features to the app based on user stories.</p><p>I added more information about each recipe, such as its spice level, dietary restrictions, and cuisine type. Since this recipe app is designed to be beginner-friendly, I added a glossary page with various cooking terms chefs should be aware of. On the web app, I can highlight if these terms are present in the recipe instructions for quick reference.</p><figure><img alt="A glossary page with cooking-related terms" src="https://cdn-images-1.medium.com/max/1024/1*Y-fkoxnchlj_2tS4McQ6ng.png" /><figcaption>A glossary page with cooking-related terms</figcaption></figure><p>An important feature I added for the mobile apps was a review prompt. You’ve probably used apps where, after some time, it would ask if you wanted to rate and optionally write a review. There are standard libraries for iOS and Android that allow you to do this. In fact, your app may get rejected if it prompts for a review outside the intended methods to prevent potential spam. It doesn’t require many lines of code and is highly recommended for apps of any size. Even for a personal project, if it blows up one day, you’d want to collect as much information as (legally &amp; ethically) possible to determine if your users are satisfied with the app. Generally, you should request a review after the user has used the app for a certain amount of time or after completing a significant flow, instead of immediately on launch. Users are more likely to review an app positively in this case. For my app, I trigger a review prompt after the user has viewed at least 5 recipes. I track these metrics separately for each app version to account for any differences between updates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SFdE923kcN1uAPli" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I7E4YsRFwhUsZ3Ib" /><figcaption>Review prompts on iOS &amp; Android, respectively</figcaption></figure><p>In addition, I utilized MongoDB to save all the recipe info and perform additional queries. MongoDB was a good fit for my data since it’s already in JSON and allows us to store nested information in each document (i.e., the recipe instructions) with a generous free tier of 0.5 GB. It gives me the freedom to update the schema whenever I update the app. It also provides us with full-text search (something Firebase doesn’t offer). Full-text search gives us the ability to search for recipes by various properties using an intuitive search box. Most importantly, querying MongoDB saves us from using up spoonacular’s daily quota, allowing more usage of the app within all the free tiers. spoonacular is only called when the “Find Me a Recipe” and “Show Me Another Recipe” buttons are clicked.</p><figure><img alt="Searching for pasta with chicken with various filters applied" src="https://cdn-images-1.medium.com/max/1024/1*RYKmy_N2Q-nz7lAnBAsSCw.png" /><figcaption>Searching for pasta with chicken with various filters applied</figcaption></figure><p>Later, I wanted to incorporate user accounts to save recipes and sync them across platforms. I went with Firebase as my authentication provider. Even though I opted out of using Cloud Firestore, I heard that Firebase Auth was a good option compared to other providers. I used Firebase a little bit when I was learning mobile development, but never utilized it in one of my projects, so it was again a good learning experience. Their free tier supports up to 50k monthly active users, which was plenty for a side project. Integrating Firebase was surprisingly tricky since there were a couple of options to choose from. I could use FirebaseUI for a prebuilt login UI, but despite it still being prominently featured in their docs, it hasn’t been maintained in years and has some glaring bugs. The Firebase client-side SDK was another option to manually call Firebase after building a login screen. However, I decided to use their server-side SDK for a few reasons:</p><ul><li>The client SDKs require storing a config file containing information about your project, including an API key. Even though the Firebase team has stated that this is not meant to be a secret (instead serving as a unique identifier for the project), I didn’t want to run into any issues with the automated security tools I have baked into these repos. They’ll almost certainly raise red flags if they see something called an “API key” in plaintext.</li><li>By not including Firebase, this reduces the build size of all the clients, resulting in faster installs/updates.</li><li>Putting Firebase on the server allows us to create an abstraction layer for authentication between the client and server. I mentioned earlier that the server is designed to be a BFF or a black box between the client and all the underlying services. All the client cares about is whether it can authenticate a user by providing their login credentials or authorizing them with a JWT (JSON Web Token). It doesn’t matter <em>how</em> the server handles the authentication. By providing a standard API contract for signing up and logging in, the OpenAPI spec and the client code can remain largely unchanged if something needs to be modified about Firebase itself. Or if, for some reason, Google decides Firebase would be a great addition to <a href="https://killedbygoogle.com/">their graveyard</a>, I can swap to a different auth provider without changing the established API contracts, thus reducing the amount of refactoring required.</li></ul><figure><img alt="The OpenAPI spec for all the account APIs" src="https://cdn-images-1.medium.com/max/1024/1*2qjsvv7E8oUOP3ACqM3Hfw.png" /><figcaption>The OpenAPI spec for all the account APIs</figcaption></figure><ul><li>I wanted full control over the types of auth flows the app supports and how each user maps to a MongoDB user. Since MongoDB is my primary database, I wanted to store account-specific information for each user. I can use the unique identifier (UID) provided by Firebase to uniquely identify each user in MongoDB (instead of using their default _id). I don’t need to store any other login credentials since Firebase will take care of that automatically. The server is already connected to MongoDB, so the client doesn’t need to make an additional API call to save or retrieve their profile data.</li></ul><figure><img alt="MongoDB documents for chef accounts" src="https://cdn-images-1.medium.com/max/1024/1*QW5SuqkVVjnNgGbtR6iACw.png" /><figcaption>MongoDB documents for chef accounts</figcaption></figure><p>The server-side implementation of Firebase involved using a combination of their <a href="https://firebase.google.com/docs/admin/setup">admin SDK</a> and the <a href="https://firebase.google.com/docs/reference/rest/auth">Identity Toolkit API</a> to perform certain operations, like logging in or sending a verification email. After implementing all the required APIs, I was able to create all the login forms so users could perform CRUD (create, read, update, delete) operations on their accounts. I added sequence diagrams in the <a href="https://github.com/Abhiek187/ez-recipes-server?tab=readme-ov-file#sequence-diagrams">server’s README</a> that go over all the CRUD operations step-by-step. To improve the UX, I made sure the keyboards on mobile matched the content type, navigation was accessible, the password’s visibility could be toggled, and all apps supported autofill to more easily generate and save their credentials. Deep linking was useful here since I required users to verify their emails. They would click a button in a confirmation email and be sent right back to the app. Since I know many users wouldn’t be comfortable or would go through the trouble of creating an account, I made sure this was optional, so the rest of the app was still usable. However, I still emphasized the benefits should they wish to sign up.</p><figure><img alt="A typical sign-in flow with autofill" src="https://cdn-images-1.medium.com/max/350/1*oFA76bAgHMJolVM6M3s2rA.gif" /><figcaption>A typical sign-in flow with autofill</figcaption></figure><p>Both deep linking and autofill require code signing on iOS, so I just added the required entitlements and apple-app-site-association config. When I added this functionality to the Android app, I had to give the reviewers test credentials so they could access the rest of the app. Alternatively, I could’ve integrated Google sign-in, but I would’ve needed custom credentials anyway if I published the iOS app. These credentials could theoretically be used for integration tests, but I decided not to use them since I didn’t want to go through the trouble of hiding the password just for tests.</p><p>Besides all the front-end updates, I learned a lot about best practices for maintaining the back end. For one thing, security is key! All input must be validated since the client can theoretically pass any data that’s valid JSON. Even if the client does some validations on their end, the server should follow a zero-trust model for extra protection. Express’s <a href="https://www.npmjs.com/package/helmet">helmet</a> library allows the server to send most of the necessary security headers to limit which endpoints the client can connect to and protect against certain attacks like XSS. To protect users from abusing the server, rate limits are applied to limit the number of API calls that can be made per timeframe. I aligned this with spoonacular’s limits as an extra safeguard from reaching their quotas.</p><p>Structured logging was also important to help monitor and troubleshoot any issues that came up during development or in production. It’s not something you might think of when building a personal project, but when you’re in a situation where you need to quickly resolve a prod issue, you’ll wish you had the tools needed to troubleshoot the bug sooner. This is a valuable skill to have in your professional career. There’s also the art of knowing how much to log. It’s harder to search for specific logs if they’re too verbose. But it’s also important <strong>not</strong> to log PII (personally identifiable information), such as passwords or API keys. In each repo, I apply a mask to hide sensitive information in all logs. Something very helpful to log was the User-Agent header. This gave me a good way to distinguish each client so I know which calls came from dev, prod, or a 3rd party calling my APIs, even down to which version of the app they were running.</p><blockquote>[Incoming Request] Sun Jul 13 2025 01:24:30 GMT+0000 (Coordinated Universal Time) | Method: POST | URL: /api/chefs/login | Headers: {“user-agent”:”EZ Recipes/3.0.1 (com.abhiek.ezrecipes; build:12; Android 15) okhttp/4.12.0&quot;} | Data: {“email”:”abhishek.chaudhuri@rutgers.edu”,”password”:”██”}</blockquote><blockquote>[Axios Request] Sun Jul 13 2025 01:24:30 GMT+0000 (Coordinated Universal Time) | Method: POST | URL: https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword | Headers: {“Accept”:”application/json, text/plain, */*”} | Data: {“email”:”abhishek.chaudhuri@rutgers.edu”,”password”:”██”,”returnSecureToken”:true}</blockquote><blockquote>[Axios Response] Sun Jul 13 2025 01:24:30 GMT+0000 (Coordinated Universal Time) | Method: POST | URL: https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword | Status: 200</blockquote><p>Speaking of security, a key feature of the server was implementing the auth middleware to validate all Firebase tokens. If no token is present, it responds with a 401. If the token is valid according to the Firebase Admin SDK, we continue the request and save a reference to the token and UID. If the token validation fails, we check to see if the token has expired. Besides checking the expiration date on the token itself, I also had to consider if the public key was valid. This is the kid (key ID) claim in the token’s header and is supposed to match one of Google’s <a href="https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com">public keys</a>. However, Google regularly rotates these keys. If a user hasn’t touched the app in a while and still has an ID token saved to their device, this key error may return instead of the normal token expiration error. In either case, I can retrieve the UID in the token to get the corresponding refresh token encrypted in MongoDB. If the refresh is successful, we can proceed and return the new token to the client. Otherwise, we return a 401 error. After much testing and refinement across multiple devices, this was a sufficient utility to ensure the user could stay authenticated in the app. Below is a preview of the middleware, but you can find the full source code <a href="https://github.com/Abhiek187/ez-recipes-server/blob/main/middleware/auth.ts">here</a>:</p><pre>const auth = async (req: Request, res: Response, next: NextFunction) =&gt; {<br>  // Validate the ID token from Firebase<br>  const authHeader = req.headers.authorization;<br>  const token = authHeader?.startsWith(&quot;Bearer &quot;)<br>    ? authHeader.split(&quot;Bearer &quot;)[1]<br>    : authHeader;<br>  const isResettingPassword =<br>    [&quot;/api/chefs&quot;, &quot;/api/chefs/&quot;].includes(req.originalUrl) &amp;&amp;<br>    req.method === &quot;PATCH&quot; &amp;&amp;<br>    req.body?.type === &quot;password&quot; &amp;&amp;<br>    req.body?.password === undefined;<br>  const isViewingRecipe =<br>    req.originalUrl.startsWith(&quot;/api/recipes/&quot;) &amp;&amp;<br>    req.params.id !== undefined &amp;&amp;<br>    req.method === &quot;PATCH&quot; &amp;&amp;<br>    typeof req.body?.view === &quot;boolean&quot;;<br><br>  if (token === undefined) {<br>    // Skip validation for certain requests<br>    if (isResettingPassword || isViewingRecipe) {<br>      next();<br>    } else {<br>      res<br>        .status(401)<br>        .json({ error: &quot;Missing the Firebase ID token from the request&quot; });<br>    }<br><br>    return;<br>  }<br><br>  try {<br>    const uid = await FirebaseAdmin.instance.validateToken(token);<br>    saveTokenAndContinue(res, next, uid, token);<br>  } catch (err) {<br>    const error = err as FirebaseAuthError;<br><br>    // If the token is expired, try refreshing it (revoked tokens can&#39;t be refreshed)<br>    // The token could also be expired if the kid claim is invalid<br>    // (but don&#39;t check for auth/argument-error)<br>    if (<br>      error.code === `auth/${AuthClientErrorCode.ID_TOKEN_EXPIRED.code}` ||<br>      error.message?.includes(&quot;expired&quot;)<br>    ) {<br>      try {<br>        // Need to decode the token ourself since Firebase won&#39;t accept expired tokens<br>        // Assuming the rest of the token is valid, and a new token will be generated anyway<br>        const { sub: uid } = jwtDecode(token);<br>        if (uid === undefined) {<br>          throw new Error(&quot;UID not found in the token&quot;);<br>        }<br><br>        const refreshToken = await getRefreshToken(uid);<br>        if (refreshToken === null) {<br>          throw new Error(`Couldn&#39;t find a refresh token for user: ${uid}`);<br>        }<br><br>        // newUid should === uid, but better to be safe than sorry<br>        const {<br>          id_token: newIdToken,<br>          refresh_token: newRefreshToken,<br>          user_id: newUid,<br>        } = await FirebaseApi.instance.refreshIdToken(refreshToken);<br><br>        await saveRefreshToken(newUid, newRefreshToken);<br>        saveTokenAndContinue(res, next, newUid, newIdToken);<br>        return;<br>      } catch (error2) {<br>        console.error(`Failed to refresh the ID token: ${error2}`);<br>      }<br>    }<br><br>    res<br>      .status(401)<br>      .json({ error: `Invalid Firebase token provided: ${error}` });<br>  }<br>};</pre><p>On MongoDB Atlas, I’m able to create a dashboard with charts showcasing various stats about my app, such as the total number of recipes, the distribution of spice levels or dietary restrictions, or how many recipes lack a fiber measurement. This is a great tool for someone with a data analyst or business intelligence background to extract useful information about their app. Some of these metrics could serve as KPIs (key performance indicators) to determine if your product is meeting your goals. I like receiving monthly emails about my dashboard, but you can fine-tune the alerts to get notified about milestones or unusual behavior. One thing I like to check from these charts is if any cuisines or meal types aren’t captured in the client apps. spoonacular documents some of the possible values, but there are several more I’ve seen from recipes that aren’t documented. This involves updating the OpenAPI spec to mention these types and referencing them in the client apps so they appear on the recipe page and as a filter option in the search form.</p><figure><img alt="A dashboard showing charts &amp; analytics from EZ Recipes" src="https://cdn-images-1.medium.com/max/959/1*2MEplIYFT6E3UzytNKNX7g.png" /><figcaption>A preview of my Atlas Charts dashboard</figcaption></figure><h3>Results</h3><p>Once all the apps were created with feature parity, I compared how many lines of code each app had. I cloned a fresh copy of each repo and switched to the latest 3.x tags to make sure we’re comparing the same feature set. Then I ran the following commands to count the number of lines in he main code files (navigating a few directories down to exclude any build folders):</p><pre># iOS<br>find . -name &#39;*.swift&#39; | xargs wc -l<br># Web<br>find . -name &quot;*.ts&quot; -o -name &quot;*.scss&quot; -o -name &quot;*.html&quot; | xargs wc -l<br># Android<br>find . -name &#39;*.kt&#39; | xargs wc -l</pre><p>The totals were 7789 on iOS, 10,758 on web (+38%), and 13,097 on Android (+68%). However, we need to consider all the imports, whitespace, and comments present in each file. The whitespace and comments don’t add anything to the final app, and the imports are just the result of different compilation systems. We should also exclude test files and focus on the core logic inside these classes. Using these newly adjusted commands:</p><pre># iOS<br>find . -name &quot;*.swift&quot; -print0 | xargs -0 cat | grep -vE &#39;^\s*(import|package|//|$)&#39; | wc -l<br># Web<br>find . \( -name &quot;*.ts&quot; ! -name &quot;*.spec.ts&quot; -o -name &quot;*.scss&quot; -o -name &quot;*.html&quot; \) -print0 | xargs -0 cat | grep -vE &#39;^\s*(import|//|&lt;!--|/\*|\*/|$)&#39; | wc -l<br># Android<br>find . -name &quot;*.kt&quot; -print0 | xargs -0 cat | grep -vE &#39;^\s*(import|package|//|$)&#39; | wc -l</pre><p>I get 3866 for iOS, 5970 for web (+54%), and 7561 for Android (+96%). We nearly halved the codebase, but the relative differences increased between each platform! If you’re curious, the server is 2271 lines of code. This is reasonable for a side project, but the code size for apps built by companies can be somewhere in the tens of thousands, hundreds of thousands, or even millions, depending on the scale and complexity.</p><figure><img alt="A chart to visualize the difference in code size for all platforms" src="https://cdn-images-1.medium.com/max/752/1*48v214cRf8NX9SUBEZOPRw.png" /><figcaption>A chart to visualize the difference in code size for all platforms</figcaption></figure><p>Let’s also compare the app builds. I’m going to compare unsigned .app and .apk files since I’m not able to sign iOS builds without an Apple Developer account. The iOS app is 3.2 MB and the Android app is 2.5 MB. Granted, these are not the final sizes users would install from the app stores. In Google Play, the app’s install size is around 2 MB, so I’m assuming a similar reduction would apply to the iOS app to optimize for different device types. The web app is different since TypeScript is interpreted, so the final build consists of minified HTML, CSS, JS, and assets instead of machine code. The minified code is 1.3 MB, and the assets are 11.8 MB (mostly from screenshots for the PWA), so the total size of the build directory is about 13.1 MB.</p><p>Now that the EZ Recipes app has been built, in the <a href="https://medium.com/@Abhiek187/4242c250b1f3">next few parts</a>, I want to compare the developer experience across all platforms. This should give some insight into the final results seen above. You can view the recipe app in these repos:</p><ul><li>iOS: <a href="https://github.com/Abhiek187/ez-recipes-ios">https://github.com/Abhiek187/ez-recipes-ios</a></li><li>Android: <a href="https://github.com/Abhiek187/ez-recipes-android">https://github.com/Abhiek187/ez-recipes-android</a></li><li>Web: <a href="https://github.com/Abhiek187/ez-recipes-web">https://github.com/Abhiek187/ez-recipes-web</a></li><li>Server: <a href="https://github.com/Abhiek187/ez-recipes-server">https://github.com/Abhiek187/ez-recipes-server</a></li></ul><p>And check out the published apps:</p><ul><li>Android: <a href="https://play.google.com/store/apps/details?id=com.abhiek.ezrecipes">https://play.google.com/store/apps/details?id=com.abhiek.ezrecipes</a></li><li>Web: <a href="https://ez-recipes-web.onrender.com/">https://ez-recipes-web.onrender.com/</a></li><li>Server: <a href="https://ez-recipes-server.onrender.com/">https://ez-recipes-server.onrender.com/</a></li></ul><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=034f504bf5b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Wrote the Same App on iOS, Android, and the Web — Here Were the Results]]></title>
            <link>https://medium.com/@Abhiek187/i-wrote-the-same-app-on-ios-android-and-the-web-here-were-the-results-a67d1ef4c5e0?source=rss-38566b972440------2</link>
            <guid isPermaLink="false">https://medium.com/p/a67d1ef4c5e0</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[recipe]]></category>
            <category><![CDATA[mvp]]></category>
            <dc:creator><![CDATA[Abhishek Chaudhuri]]></dc:creator>
            <pubDate>Sat, 19 Jul 2025 20:59:58 GMT</pubDate>
            <atom:updated>2025-07-19T21:02:46.056Z</atom:updated>
            <content:encoded><![CDATA[<h3>I Wrote the Same App on iOS, Android, and the Web — Here Were the Results</h3><figure><img alt="EZ Recipes logo" src="https://cdn-images-1.medium.com/max/300/1*UdcU28noobFcm3N2lLyn_w.png" /><figcaption>EZ Recipes logo</figcaption></figure><h3>Introduction</h3><p>I enjoy building apps, whether they are on the web or mobile. I connect well with consumers when I build a product they directly use, rather than a back-end service. I develop as my main source of income, but I enjoy coding on the side as well and sharing my projects on GitHub.</p><p>In 2022, I was looking for new project ideas and came across <a href="https://github.com/Gear61/Software-Project-Ideas">a repo</a> full of great options. I decided to try a <a href="https://github.com/Gear61/Software-Project-Ideas/blob/main/Low%20Effort%20Recipes%20Finder.md">Low Effort Recipes Finder</a> since I was (and still am) trying to learn how to cook to save money and improve my health. I called it EZ Recipes. One of my goals when building a project is to create a product that I could see myself using regularly. I can build a recipe app that suggests recipes that are quick and simple enough for me to cook, and refer to them whenever I want to make them again in the future. Having both a web and mobile version of the app would be useful since I can browse more recipes on the web, save them, and then refer to them on my phone or tablet when I’m in the kitchen.</p><p>Besides building a useful product, another goal of mine is to learn something new that I can apply to my current role or other projects. Ultimately, the exact tech stack doesn’t matter to the end user. Most frameworks can build similar features. What matters is that you’re providing value to the customer. Since I’m used to building apps using React, UIKit, and XML Views, for this project, I decided to use Angular, SwiftUI, and Jetpack Compose. SwiftUI and Compose are like React in that they’re declarative frameworks to define your UI. They re-render whenever you update states and can run additional logic whenever the component loads, unmounts, or changes state. Angular is a bit different since the state is defined in classes and the UI is defined via templates with their markup syntax. Change detection is normally done with zone.js; however, modern Angular is leaning away from zone.js and following more of a React approach. States are defined using signal() with built-in change detection depending on where the signals are used. I opted out of using cross-platform tools like React Native or Flutter since I wanted full control over the native code to help with debugging.</p><figure><img alt="A very high-level architecture diagram of my project" src="https://cdn-images-1.medium.com/max/626/0*hFIiurm0TuBs0U2n.png" /><figcaption>A very high-level architecture diagram of my project. For the MVP, we can ignore MongoDB &amp; Firebase.</figcaption></figure><p>Since these projects are for fun and not for profit, I try to save money where possible when choosing the tools to use (kind of like my <a href="https://medium.com/@Abhiek187/how-i-built-an-aws-app-without-spending-a-penny-fb40bc431cba">AWS app</a>). To get all the recipe information, I used <a href="https://spoonacular.com/food-api">spoonacular</a>. Spoonacular has an API to get a simple, random recipe with lots of information, which is essential for the MVP (minimum viable product). The free tier is limited but will suffice for a personal project. Plus, if we do go over the free tier, if we don’t provide a credit card, we won’t be charged for the extra usage. Instead, we’ll get a 429 error for Too Many Requests.</p><p>To use the spoonacular API, we need to pass an API key. To do this securely, we need a backend. Secrets should not be kept on the front end since they will ultimately appear in the final source code, which is readily available through browsers or decompilation software. A server allows us to follow a BFF (backend-for-frontend) pattern. The frontend can make black-box API requests to get the desired items, while the server handles the more complex logic of translating the underlying API responses to more UI-friendly responses. For the server, I opted to use Node.js since it was simple to implement and allowed me to get more comfortable with backend development. As I kept building upon this app, I was able to incorporate additional ways to secure and monitor the backend. This way, I can make sure everything is working as expected and troubleshoot any bugs.</p><p>These apps were built using Swift, Kotlin, and TypeScript. All three languages feature strong typing with type inference (so you don’t need to explicitly declare the variable type), null safety, and all the object-oriented syntax you’d expect from most other languages. The main difference is that Swift and Kotlin are compiled languages, while TypeScript is interpreted. Swift compiles to the machine’s assembly architecture (like C), while Kotlin compiles to bytecode using the JVM (like Java).</p><p>As I built this app, I documented the journey on GitHub and structured my progress through mini-sprints. I used GitHub’s project feature to create a Kanban board to organize features to work on in each repo. This was a great way to break up features into smaller, more manageable tasks and keep track of the app’s progress.</p><figure><img alt="A Kanban board from GitHub with to do, in progress, and done columns" src="https://cdn-images-1.medium.com/max/1024/1*AYfr3K7nogMuy4NOxCAI4g.png" /><figcaption>The EZ Recipes project dashboard on GitHub</figcaption></figure><h3>MVP</h3><h4>Web &amp; Server</h4><p>The first step was to build the MVP. At a minimum, the user should be able to open the app and press a button to view a random recipe. That’s it! We don’t need any fancy features like search, accounts, or AI at this stage. It should be simple enough for users to understand and can be released as a standalone product.</p><p>I first created the server in Node.js and Express to get recipes from spoonacular. The API key is kept hidden as an environment variable. When I originally built this app, I deployed the website and server on Heroku. However, once they removed the free tier, I switched to <a href="https://render.com/">Render</a> since it provides 750 free instance hours per month. It also auto-sleeps inactive services to save on hours, in exchange for slower cold boots. This was also the case for Heroku, and for a personal project, I was willing to compromise. No configuration files were required, and deployments happened automatically once the code got merged into the main branch. I can also control and monitor the services directly from their UI. The only settings I had to configure were the Dockerfiles and secrets. For the web app, I additionally configured the build commands, build folder, and the Content Security Policy header. I also set NODE_VERSION to <strong>lts</strong> to make sure the Node version is up to date and compatible with Angular.</p><p>Anyway, the tangent was to show that I needed to set up CORS in the server since both that and the web app will be hosted on different domains. A simple “Access-Control-Allow-Origin: *” response header will suffice for the MVP, but later, I limited the domains that can access my server. (Or better yet, just use the <a href="https://www.npmjs.com/package/cors">cors</a> middleware in Node.js!) It’s common knowledge to me now, but when I was first learning about web development, I had no idea why I couldn’t make API calls directly from the browser. I followed a tutorial to deploy a proxy server that could handle these requests, but once I learned <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS">how CORS worked</a> and I had full control of a server, I was amazed at how easy it was to understand the different headers. Of course, this only applies to the browser since CORS does not affect Postman or mobile apps. By the end of the day, I had a working prototype of the MVP:</p><figure><img alt="A recipe shown as a block of text" src="https://cdn-images-1.medium.com/max/975/1*Jzbp48gFVOkyINVXE7w_DQ.png" /><figcaption>The first ever build of EZ Recipes: a wall of JSON!</figcaption></figure><p>Yes, it looks very primitive now, but this is the foundation needed to eventually create a friendly UI around this API.</p><p>You might’ve noticed that I was using the Edamam API instead of spoonacular. That’s because I initially tried their API to fetch recipes. But then I decided to switch to spoonacular since Edamam didn’t directly show the steps required to make a recipe, arguably the most important part. This was another great learning experience since it taught me the importance of a BFF. The client doesn’t care how the data is gotten. It just needs the required fields to render the UI. The BFF should define a schema that satisfies the client’s needs, agnostic of any API. Then the BFF can worry about mapping the backend’s schema to the client’s schema. This way, if the backend changes, the client isn’t affected. The BFF just needs to modify the mapping logic.</p><p>Soon, the UI started to look like this:</p><figure><img alt="A recipe page without any styling" src="https://cdn-images-1.medium.com/max/975/1*QmNBuO7fr42diWnVcfs3Kg.png" /><figcaption>Look Ma, no CSS!</figcaption></figure><p>Now we need some CSS magic to make the site look pretty. In Angular, I can utilize Angular Material to follow Google’s Material Design system:</p><figure><img alt="A recipe page on desktop with styling" src="https://cdn-images-1.medium.com/max/975/1*nArYMIasbNNKiJiSufY2QA.png" /><figcaption>The final MVP build on desktop</figcaption></figure><figure><img alt="A recipe page on mobile with styling" src="https://cdn-images-1.medium.com/max/351/1*jOXNBeeYJjrdaUljouWljw.png" /><figcaption>The final MVP build on mobile</figcaption></figure><p>Starting with the web app first allowed me to run the server locally and test the responsiveness of the UI once I needed to translate it for mobile devices. Along the way, I wrote unit tests to make sure all the UI elements were displayed correctly. I used GitHub Actions to run a pipeline to test, build, and deploy each of the apps.</p><p>On the server, I also decided to publish an <a href="https://ez-recipes-server.onrender.com/">OpenAPI spec</a> so clients can learn how to consume the APIs (pun not intended). I originally published this on SwaggerHub, but later learned how to deploy my instance using <a href="https://www.npmjs.com/package/swagger-ui-express">swagger-ui-express</a>. As more endpoints were created, I split up the spec file by domain to make it easier to maintain.</p><figure><img alt="The OpenAPI spec for the EZ Recipes server" src="https://cdn-images-1.medium.com/max/1024/1*NGHJkhTTsFdXOSbGWEaAFA.png" /><figcaption>The OpenAPI spec for the EZ Recipes server</figcaption></figure><h4>iOS &amp; Android</h4><p>For the mobile apps, I needed to create an app icon and a splash screen. I’m not an artist, so I quickly colored a stock image of food to make it stand out. (That’s the image you saw at the very beginning. 😉) Then I used an online app icon generator to generate all the required icon sizes for iOS and Android. As a bonus, I generated all the assets needed to turn the web app into a PWA (progressive web app).</p><p>I tried to follow a similar pattern in both apps, where I would separate the view and models via an intermediary. Whether you call this a controller or a ViewModel, it serves to separate the UI logic from the business logic. On iOS, I used Alamofire to handle network requests, and on Android, I used Retrofit. Both require different ways to set up the API calls. I also made sure to add unit tests as I built the app. Mobile apps also support integration testing (called UI testing on iOS and instrumentation testing on Android), where you run the app on an actual device and test if the UI works as expected. This is also available on web apps using tools like Cypress or Playwright, but doesn’t usually come bundled with front-end frameworks.</p><p>One thing I wanted to emphasize while building all the apps was making sure it was responsive on all screen sizes. I figured some chefs may want to view the recipes from a tablet to see more of each recipe at a time. I designed the mobile app like I did with the web app, so it takes up more screen real estate if available. For example, I can display the recipe name and nutritional info side-by-side if the screen is wide enough. It’s also good to account for wider screens in case the user simply switches to landscape mode. (A lot of apps tend to lock to portrait mode since it’s how most people browse their phone, but I didn’t want to limit the user for a better UX and more accessible experience across devices.)</p><p>Another feature I wanted to include in the mobile apps was deep links (also known as universal links on iOS and app links on Android). Deep links allow users to open the appropriate screen on a mobile app from a webpage. In my case, if a user wants to browse a recipe on my site on mobile, the browser can ask the user to open the respective screen on the mobile app if it’s installed. This requires setting up an apple-app-site-association and assetlinks.json file in the web app, referencing the domain from the mobile app, and adding the logic to handle the deep link. Since I have full control over the web and mobile app, I can easily add these requirements. These files will also be useful once I add autofill to the login flow.</p><h4>apple-app-site-association:</h4><pre>{<br>  &quot;applinks&quot;: {<br>    &quot;details&quot;: [<br>      {<br>        &quot;appIDs&quot;: [<br>          &quot;UF6E5BVT98.com.abhiek.EZ-Recipes&quot;<br>        ],<br>        &quot;components&quot;: [<br>          {<br>            &quot;/&quot;: &quot;/recipe/*&quot;,<br>            &quot;comment&quot;: &quot;Maps the recipe pages on the web app to the recipe views on the iOS app&quot;<br>          },<br>          {<br>            &quot;/&quot;: &quot;/profile&quot;,<br>            &quot;?&quot;: {<br>              &quot;action&quot;: &quot;*&quot;<br>            },<br>            &quot;comment&quot;: &quot;Maps a continue action on the profile page to a profile action on the iOS app&quot;<br>          }<br>        ]<br>      }<br>    ]<br>  },<br>  &quot;webcredentials&quot;: {<br>    &quot;apps&quot;: [<br>      &quot;UF6E5BVT98.com.abhiek.EZ-Recipes&quot;<br>    ]<br>  }<br>}</pre><h4>assetlinks.json:</h4><pre>[<br>  {<br>    &quot;relation&quot;: [<br>      &quot;delegate_permission/common.handle_all_urls&quot;,<br>      &quot;delegate_permission/common.get_login_creds&quot;<br>    ],<br>    &quot;target&quot;: {<br>      &quot;namespace&quot;: &quot;android_app&quot;,<br>      &quot;package_name&quot;: &quot;com.abhiek.ezrecipes&quot;,<br>      &quot;sha256_cert_fingerprints&quot;: [<br>        &quot;F1:99:EE:D8:6E:DB:E5:2B:08:6E:82:10:D1:F5:5B:2B:C6:68:7E:4F:45:EB:F5:BC:35:78:4A:A8:76:7C:DE:E9&quot;,<br>        &quot;66:E1:DD:94:BF:CF:2E:24:AB:5E:CD:CB:30:2A:78:B4:29:88:9A:99:18:B9:03:89:5D:C5:FE:B0:CB:1A:DE:88&quot;<br>      ]<br>    }<br>  },<br>  {<br>    &quot;relation&quot;: [&quot;delegate_permission/common.get_login_creds&quot;],<br>    &quot;target&quot;: {<br>      &quot;namespace&quot;: &quot;web&quot;,<br>      &quot;site&quot;: &quot;https://ez-recipes-web.onrender.com&quot;<br>    }<br>  }<br>]</pre><figure><img alt="Opening a recipe directly in the app using a deep link" src="https://cdn-images-1.medium.com/max/540/1*ETB7z90vUjodjYmT9XCWSQ.gif" /><figcaption>Opening a recipe directly in the app using a deep link. (Note that deep links don’t work if you paste the URL directly in the browser.)</figcaption></figure><p>Mobile app pipelines require a little more work compared to websites and servers. The iOS pipeline must run on macOS, which GitHub Actions thankfully provides for free, albeit with fewer concurrent runners. Android apps don’t have to run on Macs, but they can provide hardware acceleration for faster boot and test times. Later on, I learned how to apply <a href="https://github.blog/changelog/2024-04-02-github-actions-hardware-accelerated-android-virtualization-now-available/">hardware acceleration on Linux</a> for quicker and more reliable testing. I used <a href="https://fastlane.tools/">Fastlane</a> to create the build, test, and deploy scripts. They’re essentially glorified shell scripts written in Ruby for better readability. Fastlane is generally more popular on iOS since Xcode’s CLI can get complicated depending on how the project is organized. Most Android scripts are handled by Gradle, so the commands themselves are simpler, but they can still benefit from automated deployments to Google Play. Fastlane can also automate taking screenshots of the app using existing integration tests. This is great since screenshots are required for your app listing, and as your app gets updated, so will your screenshots. However, integration tests can slow down the pipeline greatly and can result in flaky tests. As I kept building the app, I found ways to optimize the build times, but I’d imagine for large apps that it’s preferred to run integration tests in a separate pipeline, so they don’t block all deployments to the lower environments.</p><p>Below is a sample of the Fastfiles on iOS &amp; Android to run tests and take screenshots:</p><pre>default_platform(:ios)<br><br>platform :ios do<br>  APP_SCHEME = &quot;EZ Recipes&quot;<br>  <br>  before_all do<br>    # Only run in GitHub Actions<br>    if ENV[&quot;CI&quot;]<br>      # Set the Xcode version before running each lane: /usr/local/bin/xcodes installed VERSION<br>      # xcodes(version: &quot;16.1&quot;, # required for Swift 6<br>      #        select_for_current_build_only: true)<br>    end<br>  end<br>  <br>  desc &quot;Run tests on a specified device&quot;<br>  lane :test do |options|<br>    # Swift package CI recommendations: https://developer.apple.com/documentation/xcode/building-swift-packages-or-apps-that-use-them-in-continuous-integration-workflows<br>    # Resolve package dependencies: xcodebuild -resolvePackageDependencies -scheme EZ\ Recipes -project ./EZ\ Recipes.xcodeproj -disableAutomaticPackageResolution<br>    # Show build settings: xcodebuild -showBuildSettings -scheme EZ\ Recipes -project ./EZ\ Recipes.xcodeproj -disableAutomaticPackageResolution<br>    # Disable &#39;Slide to Type&#39; on each simulator: /usr/libexec/PlistBuddy -c &quot;Add :KeyboardContinuousPathEnabled bool false&quot; ~/Library/Developer/CoreSimulator/Devices/84CA0B87-356F-4160-A3E7-5AC636BEF880/data/Library/Preferences/com.apple.keyboard.ContinuousPath.plist &gt;/dev/null 2&gt;&amp;1<br>    # Clean, build project, &amp; run unit and UI tests on all simulators: set -o pipefail &amp;&amp; env NSUnbufferedIO=YES TEST_RUNNER_CI=true xcodebuild -scheme EZ\ Recipes -project ./EZ\ Recipes.xcodeproj -derivedDataPath ~/Library/Developer/Xcode/DerivedData/EZ_Recipes-cuhmoxzpybdazjcsljkgfvxmyeud -destination &#39;platform=iOS Simulator,id=ACCE5FA5-142E-4DDB-89D5-18BD949644EC&#39; -destination &#39;platform=iOS Simulator,id=AD55AFA8-4014-406B-996D-58BD6548F72A&#39; -destination &#39;platform=iOS Simulator,id=DDD5015F-9C9F-434F-9454-3748C749A432&#39; clean build test | tee &#39;~/Library/Logs/scan/EZ Recipes-EZ Recipes.log&#39; | xcbeautify --renderer github-actions<br>    run_tests(scheme: APP_SCHEME,<br>              device: options[:device],<br>              # skip_testing: [&quot;EZ RecipesUITests&quot;], # in case GitHub Actions is acting naughty (TestTarget[/TestClass[/TestMethod]])<br>              clean: true,<br>              xcodebuild_formatter: &quot;xcbeautify --renderer github-actions&quot;,<br>              output_types: &quot;junit&quot;,<br>              disable_package_automatic_updates: true,<br>              # TEST_RUNNER_ stripped from env var, must appear before xcodebuild<br>              xcodebuild_command: &quot;env NSUnbufferedIO=YES TEST_RUNNER_CI=#{ENV[&#39;GITHUB_ACTIONS&#39;]} xcodebuild&quot;)<br>  end<br>  <br>  desc &quot;Generate screenshots for the App Store&quot;<br>  lane :screenshots do<br>    # Resolve package dependencies: xcodebuild -resolvePackageDependencies -scheme EZ\ Recipes -project ./EZ\ Recipes.xcodeproj<br>    # Show build settings: xcodebuild -showBuildSettings -scheme EZ\ Recipes -project ./EZ\ Recipes.xcodeproj<br>    # For each device<br>    # Wait for the simulator to fully boot: xcrun simctl bootstatus ACCE5FA5-142E-4DDB-89D5-18BD949644EC -b &amp;&gt; /dev/null<br>    # Override the status bar: xcrun simctl status_bar ACCE5FA5-142E-4DDB-89D5-18BD949644EC override --time 2007-01-09T09:41:00-05:00 --dataNetwork wifi --wifiMode active --wifiBars 3 --cellularMode active --operatorName &#39;&#39; --cellularBars 4 --batteryState charged --batteryLevel 100 &amp;&gt; /dev/null<br>    # Clean, build, test the app, &amp; take screenshots on all devices: set -o pipefail &amp;&amp; xcodebuild -scheme EZ\ RecipesUITests -project ./EZ\ Recipes.xcodeproj -derivedDataPath /var/folders/w4/jz5wfy_511g5r2q6t6qm3nc9hk7wqj/T/snapshot_derived20230102-59844-z0fp12 -destination &#39;platform=iOS Simulator,name=iPhone 8,OS=16.1&#39; -destination &#39;platform=iOS Simulator,name=iPhone 13 Pro Max,OS=16.1&#39; -destination &#39;platform=iOS Simulator,name=iPad Pro (12.9-inch) (6th generation),OS=16.1&#39; FASTLANE_SNAPSHOT=YES FASTLANE_LANGUAGE=en-US clean build test | tee ~/Library/Logs/snapshot/EZ\ RecipesUITests-EZ\ RecipesUITests.log | xcbeautify<br>    # Clear status bar override: xcrun simctl status_bar ACCE5FA5-142E-4DDB-89D5-18BD949644EC clear &amp;&gt; /dev/null<br>    capture_screenshots<br>    frame_screenshots<br>  end<br>end</pre><pre>default_platform(:android)<br><br>platform :android do<br>  desc &quot;Run unit tests&quot;<br>  lane :test do<br>    # Runs: gradlew test -p .<br>    gradle(task: &quot;test&quot;)<br>  end<br><br>  desc &quot;Generate screenshots for the Play Store&quot;<br>  lane :screenshots do<br>    # Clean build: gradlew clean -p .<br>    gradle(task: &quot;clean&quot;)<br>    # Create app APK: gradlew assembleDebug -p .<br>    build_android_app(<br>        task: &quot;assemble&quot;,<br>        build_type: &quot;Debug&quot;<br>    )<br>    # Create tests APK: gradlew assembleAndroidTest -p .<br>    build_android_app(<br>        task: &quot;assemble&quot;,<br>        build_type: &quot;AndroidTest&quot;<br>    )<br>    # Clear screenshots on the device: adb -s emulator-5554 shell rm -rf /sdcard/Android/data/com.abhiek.ezrecipes/files/screengrab/en-US/images/screenshots<br>    # Install app APK: adb -s emulator-5554 install -t -r app/build/outputs/apk/debug/app-debug.apk<br>    # Install tests APK: adb -s emulator-5554 install -t -r app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk<br>    # Grant permission to change the device&#39;s locale: adb -s emulator-5554 shell pm grant com.abhiek.ezrecipes android.permission.CHANGE_CONFIGURATION<br>    # Grant permission to write to external storage: adb -s emulator-5554 shell pm grant com.abhiek.ezrecipes android.permission.WRITE_EXTERNAL_STORAGE<br>    # Grant permission to read from external storage: adb -s emulator-5554 shell pm grant com.abhiek.ezrecipes android.permission.READ_EXTERNAL_STORAGE<br>    # Grant permission to clean the status bar (by accessing system services): adb -s emulator-5554 shell pm grant com.abhiek.ezrecipes android.permission.DUMP<br>    # Enable Demo Mode for the Android System UI: adb -s emulator-5554 shell settings put global sysui_demo_allowed 1<br>    # Stop existing app &amp; test processes: adb -s emulator-5554 shell am force-stop com.abhiek.ezrecipes[.test]<br>    # Run instrumented tests for each locale: adb -s emulator-5554 shell am instrument --no-window-animation -w -e testLocale en-US --no-hidden-api-checks -e appendTimestamp false -e class com.abhiek.ezrecipes.EZRecipesInstrumentedTest com.abhiek.ezrecipes.test/androidx.test.runner.AndroidJUnitRunner<br>    # Get captured screenshots from external storage: adb -s emulator-5554 pull /sdcard/Android/data/com.abhiek.ezrecipes/files/screengrab/en-US/images/screenshots /tmp/d20230107-31863-xk272<br>    # Get screenshots from internal storage (using run-as for root access): adb -s emulator-5554 shell run-as com.abhiek.ezrecipes &quot;tar -cC /data/data/com.abhiek.ezrecipes/app_screengrab/en-US/images screenshots&quot; | tar -xv -f- -C /tmp/d20230108-32165-9dm6e7<br>    capture_android_screenshots<br>    frame_screenshots<br>  end<br>end</pre><p>When it came time to deploy the mobile apps…I only did it for Android. A Google Play developer account costs a one-time fee of $25, after which you’re free to distribute as many apps as you’d like. An Apple Developer account, on the other hand, costs $99 per year. If you don’t pay this fee, all your apps will be removed from the App Store. Unless you’re running a business or doing iOS development professionally, I feel like this is a steep cost compared to the competition. I’ve published iOS apps before, so I’m familiar with the process, but for longevity, I didn’t want to keep paying this fee. I added most of the configuration needed to deploy to the App Store, but stopped as soon as Xcode asked me to create an Apple Developer account.</p><figure><img alt="An error was encountered: Team is not enrolled in the Apple Developer Program. Distribution requires enrollment in the Apple Developer Program. Visit https://developer.apple.com/account to enroll." src="https://cdn-images-1.medium.com/max/975/1*WiOWO1BUsef-fwk9l3ea7g.png" /><figcaption>A signing error if you’re not enrolled in the Apple Developer Program</figcaption></figure><p>This is also why I opted out of using Xcode Cloud: Apple’s CI/CD service. It’s tied to an Apple Developer account, whereas Fastlane is free, open source, and can handle all the CI/CD operations I need for my app. I also couldn’t test universal links since that requires having entitlements, which are included when you sign the app, which I can’t do without an Apple Developer membership. As a compromise for testing purposes, I can simulate what would happen if the user deep-linked into the app by modifying the startup code.</p><p>In general, the deployment process for the mobile apps involves updating the version, creating release notes, creating a new signed build, uploading the app to an internal test track (such as TestFlight on iOS), and finally promoting the app to production. The credentials for signing the app need to be kept secure, so I only run the scripts locally instead of on GitHub Actions. The internal track is important to test the release build before it’s ready for production in case any last-minute bugs pop up.</p><p>That concludes the MVP, but in <a href="https://medium.com/@Abhiek187/034f504bf5b4">part 2</a>, we’ll add more features to EZ Recipes and compare the final code size. You can view the recipe app in these repos:</p><ul><li>iOS: <a href="https://github.com/Abhiek187/ez-recipes-ios">https://github.com/Abhiek187/ez-recipes-ios</a></li><li>Android: <a href="https://github.com/Abhiek187/ez-recipes-android">https://github.com/Abhiek187/ez-recipes-android</a></li><li>Web: <a href="https://github.com/Abhiek187/ez-recipes-web">https://github.com/Abhiek187/ez-recipes-web</a></li><li>Server: <a href="https://github.com/Abhiek187/ez-recipes-server">https://github.com/Abhiek187/ez-recipes-server</a></li></ul><p>And check out the published apps:</p><ul><li>Android: <a href="https://play.google.com/store/apps/details?id=com.abhiek.ezrecipes">https://play.google.com/store/apps/details?id=com.abhiek.ezrecipes</a></li><li>Web: <a href="https://ez-recipes-web.onrender.com/">https://ez-recipes-web.onrender.com/</a></li><li>Server: <a href="https://ez-recipes-server.onrender.com/">https://ez-recipes-server.onrender.com/</a></li></ul><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a67d1ef4c5e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cognito — Passwordless Auth using Passkeys]]></title>
            <link>https://medium.com/@Abhiek187/cognito-passwordless-auth-using-passkeys-ccfa4a6175e5?source=rss-38566b972440------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccfa4a6175e5</guid>
            <category><![CDATA[passkey]]></category>
            <category><![CDATA[biometrics]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[cognito]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Abhishek Chaudhuri]]></dc:creator>
            <pubDate>Tue, 17 Dec 2024 01:32:57 GMT</pubDate>
            <atom:updated>2026-05-09T12:40:21.996Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cognito — Passwordless Auth using Passkeys</h3><figure><img alt="AWS logo with passkeys symbol" src="https://cdn-images-1.medium.com/max/1024/1*I8udJXNKzdR2DPonQ8ywAg.png" /></figure><p><em>This is a continuation of my </em><a href="https://medium.com/@Abhiek187/how-i-built-an-aws-app-without-spending-a-penny-cognito-1477025fc255"><em>first article on Cognito</em></a><em> with new updates since that was published.</em></p><p>In the zero-cost AWS app I built, I used Cognito to handle user authentication with user pools. Since then, AWS has updated the service to include new features and revamped its free tier. (I was surprised it wasn’t brought up that much at re:Invent.) Usually, I would edit these articles to include any new information, but these changes were so significant that I decided to create a follow-up to my last post on Cognito.</p><p>There are now 3 tiers to choose from when creating a user pool: Lite, Essentials, and Plus. All user pools created before 11/22/24 default to the Lite tier, while new ones will default to the Essentials tier. The Lite tier provides the barebones needed to authenticate users. The Essentials tier adds support for new passwordless auth methods using email codes and passkeys. It also enables more customization options with the managed login page. Finally, the Plus tier bundles all the advanced security features Cognito provided before, at a slightly cheaper rate. Both Lite and Essentials have free tiers, but they’ve been reduced from 50k MAUs (monthly active users) to 10k MAUs. Now for a side project, 10k is still reasonable, but it may impact users who relied on the higher free tier. Since the free tier is available for both, I decided to upgrade my user pool to the Essentials tier. In addition, I wanted to explore the new managed login page (formerly called the hosted UI) and the new passwordless options. I find passkeys more convenient from a UX perspective than magic links or one-time codes, so I’ll be focusing on them for the rest of this article.</p><p>But first…</p><h3>What are Passkeys?</h3><p>Passkeys are an alternative to passwords designed to be resistant to phishing. Instead of remembering something you know, like a password, passkeys leverage something you have (security keys) or something you are (biometrics) to authenticate users. These are harder to phish since the attacker would need the physical key or biometric data (face/fingerprint) of the user to sign in. And they don’t require any MFA (multi-factor authentication).</p><p>Passkeys operate on public-key cryptography. Instead of storing sensitive data on the server (even if hashed like passwords), the server stores a public key and the client stores a private key. If the server gets compromised, the attacker would get the public key, but wouldn’t be able to use the passkey without the private key. When the user wants to sign in:</p><ol><li>The client requests a challenge from the server.</li><li>The server generates a random challenge.</li><li>The client responds to the challenge by signing it with the private key.</li><li>The server validates the signature using the public key and authenticates the user.</li></ol><p>The client protects the private key by requiring biometrics or a security key. So to clear a misconception, your face itself isn’t the passkey. It’s just used to access a randomly generated private key stored on the device (often using dedicated hardware).</p><p>You can have multiple passkeys associated with an account by signing in with different devices or using both biometrics and security keys. This is recommended since passkeys are harder to recover than passwords since they’re tied to a specific device. Passkeys can be synced using password managers so they can work across multiple devices, but this requires the private key to be stored encrypted in the cloud. (This is how, for instance, Apple allows you to share and sync passkeys through iCloud.) Some people may prefer security keys for this very reason, so the private key can’t be stored remotely and remains under full ownership of the user.</p><h3>Implementing Passkeys</h3><p>We’ll modify the web app created in my previous articles to support adding, viewing, and deleting passkeys. To recap, we created 3 resources associated with Cognito: a user pool, a user pool domain, and a user pool client.</p><pre>Resources:<br>  CognitoUserPool:<br>    Type: AWS::Cognito::UserPool<br>    Properties:<br>      Policies:<br>        # Default password policy: 8 chars w/ 1 num, special char, uppercase &amp; lowercase letter<br>        SignInPolicy:<br>          AllowedFirstAuthFactors:<br>            - PASSWORD<br>            - WEB_AUTHN<br>      UserPoolTier: ESSENTIALS<br>      # Parameters based on https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions<br>      WebAuthnRelyingPartyID: !Sub &quot;https://${AuthDomain}.auth.${AWS::Region}.amazoncognito.com&quot;<br>      WebAuthnUserVerification: required</pre><p>For the user pool, we’ll add a sign-in policy to allow users to sign in using a password or a passkey. (Cognito refers to passkeys as WebAuthn. Both mean the same thing in this context.) We’ll specify the tier as Essentials and add the required WebAuthn parameters. Relying party ID is the domain where the passkeys will be used. This is our user pool domain. Even with the UI changes below, the URL will stay the same. User verification is a flag that tells the authenticator whether the user is required to authenticate to use the passkey. This can be either “required” or “preferred”. Preferred means the authenticator will ask for verification, but won’t fail if verification isn’t provided. But for better security, users should be required to authenticate before using their passkeys. This is already built-in for biometrics. For security keys, this is the difference between just tapping the button vs. entering an additional PIN.</p><pre>Resources:<br>  CognitoUserPoolClient:<br>    Properties:<br>      ExplicitAuthFlows:<br>        - ALLOW_REFRESH_TOKEN_AUTH<br>        # Choose alternatives to SRP, such as passkeys<br>        - ALLOW_USER_AUTH<br>        - ALLOW_USER_SRP_AUTH # SRP = Secure Remote Password</pre><p>For the user pool client, all we need to change is the explicit auth flows. ALLOW_USER_AUTH will allow the user to choose either a password or passkey on the login page.</p><pre>Resources:<br>  # Use Cognito managed login for authentication<br>  CognitoUserPoolDomain:<br>    Type: AWS::Cognito::UserPoolDomain<br>    Properties:<br>      Domain: !Ref AuthDomain # .auth.[region].amazoncognito.com<br>      ManagedLoginVersion: 2 # 1 = hosted UI (classic), 2 = managed login (new)<br>      UserPoolId: !Ref CognitoUserPool<br>  CognitoManagedLoginBranding:<br>    Type: AWS::Cognito::ManagedLoginBranding<br>    Properties:<br>      ClientId: !Ref CognitoUserPoolClient<br>      ReturnMergedResources: true<br>      UseCognitoProvidedValues: true # use the default managed login UI<br>      UserPoolId: !Ref CognitoUserPool</pre><p>Finally, a few changes need to be made to the user pool domain. Cognito previously had the hosted UI for a login page. But now there’s a revamped managed login page we can use. (It’s recommended to update anyway even if you’re not planning to use passkeys since AWS may deprecate the hosted UI in the future.) To enable this, we set ManagedLoginVersion to 2. If you try to deploy this now, you’ll get the following error upon opening the login page:</p><figure><img alt="Login pages unavailable, please contact an administrator" src="https://cdn-images-1.medium.com/max/445/1*bejXpmjfHsnOoRBa--hC1g.png" /><figcaption>Error if managed login branding isn’t specified</figcaption></figure><p>It’s a vague error, but unfortunately, you are the administrator that needs to fix this. 😅 Thankfully, the solution is to specify a managed login branding resource. We will connect this to the client and user pool and use the default UI provided by Cognito. You can use the AWS console to customize the UI further, and then copy the configuration to the CloudFormation template. The final result will look like this:</p><figure><img alt="The newer default Cognito managed login page" src="https://cdn-images-1.medium.com/max/1024/1*hzjrQ5wpTOkkVuSv9ps9MQ.png" /><figcaption>The newer default Cognito managed login page</figcaption></figure><p>I’ll give the AWS team credit that this looks much nicer compared to the old hosted UI:</p><figure><img alt="The older default Cognito hosted UI" src="https://cdn-images-1.medium.com/max/553/0*kfVtIjL82qrC0JSR.png" /><figcaption>The older default Cognito hosted UI</figcaption></figure><p>We don’t need to change anything on the web app to view the new sign-in experience.</p><p>Let’s start by creating an account. Before we can create our passkey, we will still need to enter our email and password and verify our email. Ideally, passkeys should replace passwords entirely, but they’re not as fully standardized as passwords. The password can act as a backup in case the user can’t recover their passkey.</p><figure><img alt="Add passkey prompt" src="https://cdn-images-1.medium.com/max/612/1*nQ5dX6_3PF4fSy-TFPtI2A.png" /><figcaption>Add passkey prompt</figcaption></figure><p>Once verified, the user can add a passkey if they want, but it’s not required. We will provide another way for users to add a passkey after they’re signed in.</p><p>Speaking of which, after providing their email, they can choose to sign in using their password or a passkey:</p><figure><img alt="Sign in with password or passkey" src="https://cdn-images-1.medium.com/max/598/1*HIGdSeA4mjnaWeMVYzks5g.png" /><figcaption>Sign in with password or passkey</figcaption></figure><p>By choosing a passkey, the user will be prompted to verify their biometrics or security key. Then they will be redirected to the web app.</p><p>To add a passkey, navigate to <strong>https://[MY-DOMAIN-NAME].auth.[REGION].amazoncognito.com/passkeys/add?client_id=[CLIENT-ID]&amp;redirect_uri=[WEB-APP-ORIGIN]</strong>. The client_id and redirect_uri are the same query parameters used in the OAuth authorize request. This will open the same page above. Adding a passkey will trigger the operating system to prompt for biometrics or a security key, and save the passkey wherever the user chooses. Upon redirecting to the web app, a <strong>result</strong> query parameter will be added. If result=success, the operation succeeded. Otherwise, it failed. From my testing, I’ve seen error results of application_error and invalid_session, but there may be more.</p><p>To view and delete passkeys, we’ll need to call some Cognito APIs, like how we deleted accounts. To view passkeys, call <a href="https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListWebAuthnCredentials.html">ListWebAuthnCredentials</a>. To delete passkeys, call <a href="https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteWebAuthnCredential.html">DeleteWebAuthnCredential</a>. (Remember that the <strong>aws.cognito.signin.user.admin</strong> scope is required to call these APIs.) Viewing passkeys requires an access token. This returns a list of passkeys with metadata about how they were created (for example, whether the passkey is tied to a device via biometrics or cross-platform via a security key). In the example below, I created a passkey on my desktop saved to Google Password Manager, and created another one on my iPhone saved to the iCloud Keychain.</p><figure><img alt="Sample profile screen showcasing all the passkeys" src="https://cdn-images-1.medium.com/max/1024/1*BwtjQcDUmkW1Ho6xICTnGA.png" /><figcaption>Sample profile screen showcasing all the passkeys</figcaption></figure><p>Deleting a passkey requires both the access token and the credential ID from the list response. This will delete the public key from Cognito, but you will also need to manually delete the passkey from your device.</p><h3>Conclusion</h3><p>Passkeys are a good alternative to passwords since they’re more secure and can make signing in quicker and easier. At this point, it’s good to provide users the option to either use a password or a passkey to sign in, depending on their preferences.</p><p>Cognito’s recent updates are a great step toward modernizing the service. Though the reduced free tier is unfortunate, the new UI is nice and I’m glad they’re embracing passkeys as another way to authenticate users. And I didn’t need to spend a penny to get all this set up, so that’s a win in my book!</p><p>As usual, you can view the full source code at <a href="https://github.com/Abhiek187/aws-shop">https://github.com/Abhiek187/aws-shop</a>. Thanks for reading!</p><p>P.S. If you like this and want to learn more, check out <a href="https://medium.com/@Abhiek187/how-passkeys-work-behind-the-scenes-f3daa6dd78b9">this article</a> where I go into more depth about how passkeys work behind the scenes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccfa4a6175e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>