<?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 Francisco Moretti on Medium]]></title>
        <description><![CDATA[Stories by Francisco Moretti on Medium]]></description>
        <link>https://medium.com/@franciscomoretti?source=rss-ab3e94b2ac9a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WkA5hC_HF7dS1yU2Cy2evA.png</url>
            <title>Stories by Francisco Moretti on Medium</title>
            <link>https://medium.com/@franciscomoretti?source=rss-ab3e94b2ac9a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 03:11:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@franciscomoretti/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[Add follow-up questions to your AI chat app]]></title>
            <link>https://medium.com/@franciscomoretti/add-follow-up-questions-to-your-ai-chat-app-13931bd7cfc9?source=rss-ab3e94b2ac9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/13931bd7cfc9</guid>
            <category><![CDATA[vercel-ai-sdk]]></category>
            <category><![CDATA[ai-chatbot]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Francisco Moretti]]></dc:creator>
            <pubDate>Mon, 22 Sep 2025 14:30:23 GMT</pubDate>
            <atom:updated>2025-09-22T14:30:23.073Z</atom:updated>
            <content:encoded><![CDATA[<p>Follow-up questions keep users engaged in your AI app. They provide natural conversation starters when users hit a dead end. This guide shows you how to build them using <a href="https://ai-sdk.dev/">AI SDK</a>’s streaming data parts feature.</p><p>You’ll see code that streams suggestions as they’re generated, thanks to the partial object streaming feature. The result feels smooth and professional.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iFOQ1yN8U1XJzyMi4ILYSw.png" /></figure><h3>Set up the backend suggestion generator</h3><p>Create a function that takes your conversation history and asks the AI model to generate relevant follow-up questions. This function uses structured output to return an array of short, actionable questions.</p><pre>import { streamObject, type ModelMessage } from &#39;ai&#39;<br>import { z } from &#39;zod&#39;<br><br>const DEFAULT_FOLLOWUP_SUGGESTIONS_MODEL = &#39;google/gemini-2.5-flash-lite&#39;<br><br>function generateFollowupSuggestions(modelMessages: ModelMessage[]) {<br>  const maxQuestionCount = 5<br>  const minQuestionCount = 3<br>  const maxCharactersPerQuestion = 80<br>  return streamObject({<br>    model: DEFAULT_FOLLOWUP_SUGGESTIONS_MODEL,<br>    messages: [<br>      ...modelMessages,<br>      {<br>        role: &#39;user&#39;,<br>        content: `What question should I ask next? Return an array of suggested questions (minimum ${minQuestionCount}, maximum ${maxQuestionCount}). Each question should be no more than ${maxCharactersPerQuestion} characters.`,<br>      },<br>    ],<br>    schema: z.object({<br>      suggestions: z.array(z.string()).min(minQuestionCount).max(maxQuestionCount),<br>    }),<br>  })<br>}</pre><p>These constraints are important. You want 3–5 questions maximum, each under 80 characters. For model selection, use a fast, inexpensive model here. Suggestions don’t need your most powerful model, and users shouldn’t have to wait for them.</p><h3>Stream suggestions to the frontend</h3><p>Build a streaming function that sends suggestions to your frontend as they’re generated. This uses AI SDK’s custom data parts feature to create type-safe parts. By reading from the partialObjectStream, we get a smooth user experience where suggestions appear in real-time, not in a batch after completion. By using the same id in the data, each time it writes a new chunk, it will replace the previous one.</p><p>Here’s the streaming function that writes suggestions as they’re created:</p><pre>async function streamFollowupSuggestions({<br>  followupSuggestionsResult,<br>  writer,<br>}: {<br>  followupSuggestionsResult: ReturnType&lt;typeof generateFollowupSuggestions&gt;<br>  writer: StreamWriter<br>}) {<br>  const dataPartId = crypto.randomUUID()<br><br>  for await (const chunk of followupSuggestionsResult.partialObjectStream) {<br>    writer.write({<br>      id: dataPartId,<br>      type: &#39;data-followupSuggestions&#39;,<br>      data: {<br>        suggestions: chunk.suggestions?.filter((suggestion) =&gt; suggestion !== undefined) ?? [],<br>      },<br>    })<br>  }<br>}</pre><p>You need to define the data type for your suggestions. Add this to the file that has your ChatMessage definition:</p><pre>type FollowupSuggestions = {<br>  suggestions: string[]<br>}<br><br>export type CustomUIDataTypes = {<br>  // ... your existing types<br>  followupSuggestions: FollowupSuggestions<br>}<br>export type ChatMessage = UIMessage&lt;MessageMetadata, CustomUIDataTypes, ChatTools&gt;</pre><h3>Create the UI components</h3><p>Build React components that display the suggestions and handle user clicks. The components need to integrate with your existing chat state management and trigger new messages when users select a suggestion.</p><p>Create a new file components/followup-suggestions.tsx:</p><pre>&#39;use client&#39;<br><br>import type { ChatMessage } from &#39;@/lib/ai/types&#39;<br>import { useCallback } from &#39;react&#39;<br>import { Button } from &#39;./ui/button&#39;<br>import { Separator } from &#39;./ui/separator&#39;<br>export function FollowUpSuggestions({<br>  message,<br>  sendMessage,<br>}: {<br>  message: ChatMessage<br>  sendMessage: UseChatHelpers&lt;ChatMessage&gt;[&#39;sendMessage&#39;]<br>}) {<br>  const suggestions = message.parts.find((p) =&gt; p.type === &#39;data-followupSuggestions&#39;)?.data<br>    .suggestions<br>  const handleClick = useCallback(<br>    (suggestion: string) =&gt; {<br>      sendMessage({ text: suggestion })<br>    },<br>    [sendMessage]<br>  )<br>  if (!suggestions || suggestions.length === 0) return null<br>  return (<br>    &lt;div className={&#39;mb-2 mt-3 flex flex-col gap-2&#39;}&gt;<br>      &lt;div className=&quot;text-base font-medium&quot;&gt;Related&lt;/div&gt;<br>      &lt;div className=&quot;flex flex-wrap items-center gap-y-1&quot;&gt;<br>        {suggestions.map((s, i) =&gt; (<br>          &lt;div key={s} className=&quot;flex w-full flex-col&quot;&gt;<br>            &lt;button<br>              type=&quot;button&quot;<br>              onClick={() =&gt; handleClick(s)}<br>              className=&quot;w-full cursor-pointer py-2 text-left text-foreground hover:text-primary&quot;<br>            &gt;<br>              {s}<br>            &lt;/button&gt;<br>            {i &lt; suggestions.length - 1 &amp;&amp; &lt;hr className=&quot;h-px w-full border-0 bg-border&quot; /&gt;}<br>          &lt;/div&gt;<br>        ))}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>This component handles click interactions by creating a new message and sending it through your chat system. It preserves the current model selection and tool settings.</p><p>The component works with AI SDK’s message parts system. It finds the right part by type and renders the suggestions.</p><p>Finally, add the component to your assistant message. This shows follow-up suggestions after each AI response.</p><pre>import { FollowUpSuggestions } from &#39;./followup-suggestions&#39;<br><br>const AssistantMessage = ({<br>  message,<br>  sendMessage,<br>}: {<br>  message: ChatMessage<br>  sendMessage: UseChatHelpers&lt;ChatMessage&gt;[&#39;sendMessage&#39;]<br>}) =&gt; {<br>  return (<br>    &lt;div className=&quot;relative flex flex-col gap-2&quot;&gt;<br>      {/* ... render other parts of the message */}<br>      &lt;FollowUpSuggestions message={message} sendMessage={sendMessage} /&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><h3>Integrate with your chat API</h3><p>Connect everything in your chat route handler. After streaming the main AI response, generate and stream follow-up suggestions using the complete conversation context. This happens automatically without blocking the main response.</p><p>Update your chat POST handler by adding the generateFollowupSuggestions and streamFollowupSuggestions functions. The key changes are in the execute function:</p><pre>const stream = createUIMessageStream&lt;ChatMessage&gt;({<br>  execute: async ({ writer: dataStream }) =&gt; {<br>    const result = streamText({<br>      model: mainModel,<br>      messages: modelMessages,<br>    })<br><br><br>dataStream.merge(result.toUIMessageStream())<br>    // Wait for the main response to complete<br>    await result.consumeStream()<br>    const response = await result.response<br>    const responseMessages = response.messages<br>    // Generate and stream follow-up suggestions<br>    const followupSuggestionsResult = generateFollowupSuggestions([<br>      ...contextForLLM,<br>      ...responseMessages,<br>    ])<br>    await streamFollowupSuggestions({<br>      followupSuggestionsResult,<br>      writer: dataStream,<br>    })<br>  },<br>})</pre><p>You must await the response first to let the main AI response finish streaming. Then you get the complete response messages and use them as context for generating suggestions.</p><p>This means users see the AI response first, then suggestions appear afterward. The suggestions have full context from both the conversation history and the AI’s complete response.</p><p>That’s it. Your follow-up questions will now stream in after each AI response, keeping users engaged and providing natural conversation starters. The entire system works end-to-end with type safety and smooth streaming.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13931bd7cfc9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fix mobile keyboard overlap with dvh (no observers)]]></title>
            <link>https://blog.devgenius.io/fix-mobile-keyboard-overlap-with-visualviewport-dac83e90406b?source=rss-ab3e94b2ac9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/dac83e90406b</guid>
            <category><![CDATA[html]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Francisco Moretti]]></dc:creator>
            <pubDate>Sun, 24 Aug 2025 00:00:22 GMT</pubDate>
            <atom:updated>2025-08-26T08:34:03.086Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>Edited 2025–08–26</em></strong><em>: The previous version recommended syncing </em><em>visualViewport.height to a CSS variable with an observer. That was wrong for this use case. The actual fix in Sparka is to rely on dynamic viewport units (</em><em>dvh). Drop the observer and use Tailwind’s </em><em>h-dvh. See the discussion: </em><a href="https://github.com/FranciscoMoretti/sparka/issues/14"><em>https://github.com/FranciscoMoretti/sparka/issues/14</em></a></blockquote><h3>Introduction</h3><p>Bottom‑pinned chat inputs can get buried when the mobile keyboard opens. Modern browsers expose dynamic viewport units that account for the on‑screen keyboard. Use dvh and keep the layout simple.</p><p>This is used in <a href="https://sparka.ai/">Sparka.ai</a>, you can check the code <a href="https://github.com/FranciscoMoretti/sparka">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7546Q_T9Kz8CiK2p.png" /></figure><h3>The fix</h3><ul><li><strong>Use </strong><strong>h-dvh</strong> (Tailwind) for any full‑height containers.</li><li>No observers, no CSS variables, no JS.</li></ul><pre>// components/chat.tsx (snippet)<br>&lt;div className=&quot;flex h-dvh min-w-0 flex-col&quot;&gt;{/* content */}&lt;/div&gt;</pre><p>If you need a single element to fill the screen:</p><pre>&lt;div className=&quot;h-dvh&quot; /&gt;</pre><h3>Notes</h3><ul><li>dvh reflects the visible viewport height, adjusting when the keyboard shows.</li><li>Works on iOS Safari and Android (recent versions). If you must support very old iOS, feature‑test and fall back to 100vh.</li></ul><h3>Viewport meta</h3><p>If you also want Android/Chromium to resize content with the keyboard, set interactiveWidget: &#39;resizes-content&#39;. This is additive to using dvh.</p><pre>// app/layout.tsx (snippet)<br>export const viewport = {<br>  maximumScale: 1, // Disable auto-zoom on mobile Safari<br>  interactiveWidget: &#39;resizes-content&#39; as const,<br>}</pre><p>Details: <a href="https://developer.chrome.com/docs/web-platform/viewport-meta/#interactive-widget">https://developer.chrome.com/docs/web-platform/viewport-meta/#interactive-widget</a></p><h3>In the wild</h3><p>This is what Sparka.ai ships. For context, see the issue: <a href="https://github.com/FranciscoMoretti/sparka/issues/14">https://github.com/FranciscoMoretti/sparka/issues/14</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dac83e90406b" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/fix-mobile-keyboard-overlap-with-visualviewport-dac83e90406b">Fix mobile keyboard overlap with dvh (no observers)</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Research UIs — Perplexity vs. Manus vs. ChatGPT vs. Gemini]]></title>
            <link>https://levelup.gitconnected.com/deep-research-uis-perplexity-vs-manus-vs-chatgpt-vs-gemini-4740ca01365a?source=rss-ab3e94b2ac9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4740ca01365a</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[vercel-ai-sdk]]></category>
            <dc:creator><![CDATA[Francisco Moretti]]></dc:creator>
            <pubDate>Tue, 29 Apr 2025 18:45:56 GMT</pubDate>
            <atom:updated>2025-04-30T14:27:43.100Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*94czlHXcG-8lcwydyOgPig.png" /></figure><h3>Deep Research UIs — Perplexity vs. Manus vs. ChatGPT vs. Gemini</h3><p>Building chat applications often involves tackling complex user interfaces. This is especially true for <strong>“deep research”</strong> tasks where <strong>information density is high</strong>. Components like <strong>reports</strong>, <strong>research steps</strong>, <strong>sources</strong>, and <strong>source citations</strong> create unique UI challenges. This post looks at how four AI chat tools (<strong>Perplexity</strong>, <strong>Manus</strong>, <strong>ChatGPT</strong>, and <strong>Gemini</strong>) approach these challenges. By checking out their UI decisions and trade-offs, particularly using Vercel’s AI SDK message schema, we can find valuable lessons for designing effective research-focused chat interfaces.</p><h3>Vercel AI SDK UI message schema</h3><p>The <a href="https://sdk.vercel.ai/">Vercel AI SDK</a> provides a structured approach for building chat interfaces through its message schema. Understanding this schema helps us analyze how different research tools implement their interfaces.</p><p>A simplified version of the Vercel AI SDK UI message schema includes:</p><ul><li><strong>UiMessage</strong>: A message in the chat. It represents the entire message unit from either a user or the AI assistant.</li><li><strong>Annotation</strong>: Information tied to a message that can be streamed before the response is written. These are useful for showing intermediate research steps, thinking processes, or source gathering.</li><li><strong>UiMessagePart</strong>: A piece of a message like text, code, or an image. Complex research responses often combine multiple part types to create rich information displays.</li></ul><pre>// Simplified relationship between UiMessage, Annotation, and UiMessagePart<br>// UiMessagePart represents different parts of the message content<br>type TextUIPart = {<br>  type: &#39;text&#39;<br>  text: string<br>}<br>type ToolInvocationUIPart = {<br>  type: &#39;tool-invocation&#39;<br>  toolInvocation: ToolInvocation // Tool invocation is a discriminated union of tool info (results and calls)<br>}<br>// UiMessage represents a complete message unit in the chat<br>type UiMessage = {<br>  id: string<br>  role: &#39;user&#39; | &#39;assistant&#39;<br>  createdAt: Date<br>  parts: Array&lt;<br>    | TextUIPart<br>    | ReasoningUIPart<br>    | ToolInvocationUIPart<br>    | SourceUIPart<br>    | FileUIPart<br>    | StepStartUIPart<br>  &gt; // A message consists of multiple parts. A discriminated union of parts types<br>  annotations?: JSONValue[] // A discriminated union of annotation types<br>}</pre><p>Developers can use these components to create different arrangements of information. Each research tool we look at makes different choices about how to structure and present information using similar underlying components.</p><p>The complexity comes from balancing <em>information density</em> with <em>usability</em>. Research interfaces must present substantial information without overwhelming users. How each tool handles this balance is a core part of our analysis.</p><h3>Perplexity UI breakdown</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o-d0eOtRbapXdr8X.png" /></figure><p><strong>Perplexity</strong> uses a simple approach for research presentation. Their interface emphasizes <strong>readability</strong> while keeping the contextual richness needed for deep research tasks.</p><p>The main answer or “report” appears as a standard message in the chat. It has no special formatting to distinguish it from other messages. This simplifies the UI but might make it harder for users to spot the final answer among regular conversation messages.</p><p>What stands out most about Perplexity is its treatment of <strong>sources</strong>. Sources appear in <strong>many places</strong>:</p><ol><li><strong>Inline citations</strong> within the text (numbered references)</li><li>A <strong>dedicated sources panel</strong> at the top of each research response + available as a “Sources” tab</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>This dual approach gives sources high visual prominence while maintaining the flow of the main content. Implementing this in the Vercel AI SDK schema might use:</p><ul><li>A primary UiMessagePart for the text content</li><li>Annotation components to hold the source references</li><li>Custom styling to visually link inline citations with their corresponding entries</li></ul><h3>Key benefits:</h3><ul><li>Builds <strong>user trust</strong> through clear attribution</li><li>Makes <strong>fact-checking easy</strong> with prominent sources</li><li>Keeps <strong>content flow clean</strong> with numbered references</li></ul><h3>Drawbacks:</h3><ul><li>Interface can become <strong>cluttered</strong> with many sources</li></ul><p>Perplexity also includes <strong>suggested follow-up questions</strong> at the end of responses. They serve as navigation aids and subtle guides toward productive use of the tool.</p><h3>Manus UI breakdown</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nvE3hooEcKcJ25Ku.png" /></figure><p><strong>Manus</strong> takes a different approach to research interfaces. It makes the <strong>research process</strong> itself a central part of the user experience. Their interface splits attention between the research output and the research method.</p><p><strong>“Research Steps</strong>” occupy a significant portion of the screen real estate. This makes the process transparent to users. Unlike interfaces focusing solely on the result, Manus treats the journey as equally important.</p><p>One notable feature is how Manus handles <strong>planning</strong>. The interface displays an explicit research plan but <em>doesn’t pause for user confirmation or feedback</em>. It does ask clarifying questions when needed, though. This can create a smoother experience when it gets things right, but it depends heavily on the quality of the decision making.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w68SIf2uLywbPW3u.png" /></figure><p>Manus generates <strong>multiple documents</strong> during research, providing info about intermediate steps. While informative, this approach can reduce the visual importance of the primary document requested by the user. The final output becomes just one of several documents, not the clear focal point.</p><p>The <strong>2-panel layout</strong> with a “computer view” on the right aims to show how the agent works in real time. This provides transparency but uses significant screen space. Its value diminishes during routine web browsing, which makes up most of the research process.</p><p>Using the Vercel AI SDK schema, this approach might be implemented with:</p><ul><li>Multiple UiMessage components for different document types</li><li>Annotation objects to represent each research step</li><li>A mechanism for Annotation objects representing tool calls to fetch and show the correct &#39;computer view&#39; content for that step</li></ul><h3>Key benefits:</h3><ul><li><strong>Process transparency</strong> builds user trust</li><li><strong>Research journey visibility</strong> helps understanding</li><li><strong>Real-time insights</strong> into AI thinking</li></ul><h3>Drawbacks:</h3><ul><li>Interface feels <strong>busier</strong> and potentially overwhelming</li><li>Requires <strong>complex state management</strong></li></ul><h3>ChatGPT UI breakdown</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dJiZ_lUC0mWB0HDE.png" /></figure><p><strong>ChatGPT</strong> takes a more balanced approach to research interfaces. It focuses on <strong>user control</strong> while keeping a clean presentation. It starts with a <strong>plan as a </strong><strong>TextUIPart</strong> that needs feedback via a normal conversation message. This offers familiarity, practicality, and flexibility.</p><p>Before conducting research, ChatGPT typically presents a <strong>research plan</strong> as a regular text message part and <em>asks for user feedback</em>. This creates a pause point that gives users agency in the research process. They can approve, modify, or redirect the plan before execution starts.</p><p>For <strong>research steps</strong>, ChatGPT initially displays them in an <strong>expandable sheet</strong> that updates in real time. This keeps the research process visible without dominating the interface. Once research finishes, these steps collapse into a compact component within the conversation. This creates a clean history that can be referenced if needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NBIwSB0sYwjcj-zV.png" /></figure><p>The final report appears as a <strong>ToolInvocation</strong> piece of the regular answer, styled like a card. This works well for shorter reports but can become cluttered for longer, more complex responses. The lack of dedicated document viewing capabilities limits the reading experience for extended content.</p><p>Using the Vercel AI SDK schema, this approach might be implemented with:</p><ul><li>A normal text UiMessagePart for the initial plan</li><li>Annotation objects for the research steps that can toggle between expanded and collapsed states</li><li>A ToolInvocation part for the final report content</li></ul><h3>Key benefits:</h3><ul><li><strong>User control</strong> through plan feedback</li><li><strong>Clean interface</strong> maintains familiarity</li><li><strong>Collapsible research steps</strong> reduce clutter</li></ul><h3>Drawbacks:</h3><ul><li>Limited support for <strong>longer reports</strong></li><li>Reading experience <strong>suffers</strong> in standard chat format</li></ul><h3>Gemini UI breakdown</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4wdFjEIB8a3kvFA6.png" /></figure><p><strong>Gemini</strong> offers a distinct approach to research interfaces. It has a strong focus on the <strong>final output</strong> while still providing process transparency. The interface uses a <strong>two-panel design</strong> that separates the conversation from research details.</p><p>The planning approach in Gemini appears as a special UI element (a tool result), though the core content is primarily text with minimal formatting. Plan acceptance is handled through a button that creates a standard message response, rather than specialized UI controls.</p><p>Research progress updates appear in the secondary panel labeled “<strong>Thoughts</strong>”. This provides insight into the ongoing process and creates clear separation between the conversation and the research mechanics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wlwt-iGtPncJ3Jxt.png" /></figure><p>When research completes, Gemini displays the document (report) in the secondary panel. Research steps are positioned below the report content. This creates a hierarchy that <strong>emphasizes results over process</strong>. However, this arrangement requires significant scrolling to review the research steps, making them less accessible than in other interfaces.</p><p>Sources receive some visual emphasis in the Gemini UI but remain integrated within the report. This approach creates a cleaner appearance but may reduce source prominence compared to interfaces like Perplexity that highlight attribution more explicitly.</p><p>Using the Vercel AI SDK schema, this approach might be implemented with:</p><ul><li>A ToolInvocation for the initial plan</li><li>Annotation objects for the &quot;Thoughts&quot; that update during research</li><li>Another ToolInvocation for the final report</li><li>A separate UI component outside the main message thread for displaying both the report and research steps</li></ul><h3>Key benefits:</h3><ul><li><strong>Clear focus</strong> on final output</li><li><strong>Clean conversation</strong>, separate from research details</li><li><strong>Good separation</strong> of conversation and supporting information</li></ul><h3>Drawbacks:</h3><ul><li>Reduced visibility of <strong>research steps</strong> after completion</li><li><strong>Sources less prominent</strong> than other approaches</li><li>Requires managing a <strong>more complex layout</strong></li></ul><h3>Conclusion</h3><p>Comparing these four tools reveals a spectrum of UI strategies for deep research. Perplexity prioritizes source prominence and readability, Manus emphasizes process transparency, ChatGPT balances user control with a clean interface, and Gemini focuses strongly on the final report within a separated layout. Each approach involves trade-offs between information density, process visibility, user control, and interface complexity. Understanding these design choices and their implications offers valuable insights for developers building AI-powered research tools.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4740ca01365a" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/deep-research-uis-perplexity-vs-manus-vs-chatgpt-vs-gemini-4740ca01365a">Deep Research UIs — Perplexity vs. Manus vs. ChatGPT vs. Gemini</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What tests to write for React]]></title>
            <link>https://blog.devgenius.io/what-tests-to-write-for-react-862b100ecddb?source=rss-ab3e94b2ac9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/862b100ecddb</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Francisco Moretti]]></dc:creator>
            <pubDate>Sat, 05 Apr 2025 07:39:29 GMT</pubDate>
            <atom:updated>2025-04-07T14:04:04.586Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WkkfBN9gyLbRKfxpTLbkaQ.jpeg" /></figure><p>This article explores what tests you should be writing for your web applications. Inspired by <a href="https://www.linkedin.com/in/igor-luchenkov/">Igor Luchenkov</a>’s insightful talk at <a href="https://guild.host/react-advanced-london">React Advanced London</a> and drawing on wisdom from industry experts, we’ll look at how testing strategies have evolved from the classic Test Pyramid to the more nuanced Testing Trophy approach.</p><h3>The evolution of testing strategies</h3><p>For years, the dominant testing strategy in software development was <strong>Martin Fowler’s Test Pyramid</strong>. This model suggested having many unit tests at the bottom, fewer integration tests in the middle, and even fewer end-to-end tests at the top.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g61XAcLA6zUrkwLX8OJpmw.jpeg" /><figcaption>Testing Pyramid</figcaption></figure><p>The pyramid made sense when it was created. Back then, running tests through a UI was painfully slow, expensive to set up, and notoriously brittle. A small change in the UI could break dozens of tests, requiring hours of maintenance.</p><p>But times have changed. Modern testing tools have evolved dramatically, making some of the pyramid’s assumptions outdated. This led <strong>Kent C. Dodds to propose an updated model — the Testing Trophy</strong>.</p><p>Inspired by Guillermo Rauch’s tweet:</p><blockquote><strong><em>“Write tests. Not too many. Mostly integration.</em></strong><em>”</em></blockquote><p>The trophy flips the script by placing <strong>integration tests as the largest, most important section</strong>. It also adds a new foundation: static tests. This shift reflects how testing tools and web development have evolved in recent years.</p><h3>Understanding the Testing Trophy</h3><p>The Testing Trophy consists of four distinct layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WkkfBN9gyLbRKfxpTLbkaQ.jpeg" /><figcaption>Testing Trophy</figcaption></figure><p>The types of tests are:</p><ul><li>End-to-End (Full app)</li><li>Integration (Component interactions)</li><li>Unit (Logic in isolation)</li><li>Static (Typing, linting, etc.)</li></ul><h3>Static (The Base)</h3><p>These aren’t traditional tests that run your code. Instead, they check your code without executing it. <strong>TypeScript, ESLint, and Biome</strong> fall into this category. They catch typos, type errors, and enforce coding standards with minimal effort.</p><h3>Unit (The Small Base)</h3><p>Unit tests verify that individual functions work correctly in isolation. They’re fast and focused but don’t tell you if your components work well together.</p><h3>Integration (The Trophy Cup)</h3><p>This is the <strong>largest section of the trophy for good reason</strong>. Integration tests verify that multiple units work together correctly. In web development, this often means testing how components interact without mocking every dependency.</p><h3>End-to-End (The Top)</h3><p>These comprehensive tests simulate real user behavior, often through a browser. They’re the most confidence-inspiring but also the slowest and most complex to maintain.</p><h3>Why integration tests deserve the spotlight</h3><p>In 2016, Guillermo Rauch (creator of Socket.io and founder of Vercel) tweeted a simple yet profound message:</p><blockquote><strong><em>“Write tests. Not too many. Mostly integration.</em></strong><em>”</em></blockquote><p>This wasn’t just a catchy phrase — it’s solid advice backed by practical experience. Integration tests strike the perfect balance between confidence and cost.</p><p>Unit tests are quick to write and run, but they don’t tell you if your components actually work together. End-to-end tests give you the most confidence but are slow and high-maintenance. Integration tests hit the sweet spot:</p><ul><li>They provide <strong>high confidence that your features work</strong></li><li>They run reasonably fast</li><li>They’re <strong>more resilient to refactoring than unit tests</strong></li><li>They catch real issues that users might encounter</li></ul><p>Kent C. Dodds put it brilliantly when he said: “<strong>The more your tests resemble the way your software is used, the more confidence they can give you.</strong>”</p><p>Integration tests mirror how users actually experience your software better than isolated unit tests, making them more valuable for the time invested.</p><h3>Small examples of each test type</h3><h3>Static Tests</h3><pre>// TypeScript will catch this error without running any code<br>function addNumbers(a: number, b: number): number {<br>  return a + b<br>}<br><br>addNumbers(&#39;5&#39;, 10) // Error: Argument of type &#39;string&#39; is not assignable to parameter of type &#39;number&#39;</pre><p>ESLint rules can catch potential bugs:</p><pre>// ESLint no-unused-vars rule<br>function calculateTotal(subtotal, tax) {<br>  const total = subtotal + tax<br>  // Error: &#39;total&#39; is assigned a value but never used<br>}</pre><h3>Unit Tests</h3><p>Using Vitest to test a simple utility function:</p><pre>// utils.js<br>export function formatPrice(amount) {<br>  return `$${amount.toFixed(2)}`<br>}<br><br>// utils.test.js<br>import { test, expect } from &#39;vitest&#39;<br>import { formatPrice } from &#39;./utils&#39;<br>test(&#39;formats the price with dollar sign and two decimal places&#39;, () =&gt; {<br>  expect(formatPrice(10)).toBe(&#39;$10.00&#39;)<br>  expect(formatPrice(10.5)).toBe(&#39;$10.50&#39;)<br>})</pre><h3>Integration Tests</h3><p>Testing a form component with React Testing Library:</p><pre>// LoginForm.test.jsx<br>import { render, screen, fireEvent } from &#39;@testing-library/react&#39;<br>import userEvent from &#39;@testing-library/user-event&#39;<br>import LoginForm from &#39;./LoginForm&#39;<br><br>test(&#39;submits the form with user credentials&#39;, async () =&gt; {<br>  const handleSubmit = vi.fn()<br>  render(&lt;LoginForm onSubmit={handleSubmit} /&gt;)<br>  await userEvent.type(screen.getByLabelText(/email/i), &#39;user@example.com&#39;)<br>  await userEvent.type(screen.getByLabelText(/password/i), &#39;password123&#39;)<br>  await userEvent.click(screen.getByRole(&#39;button&#39;, { name: /log in/i }))<br>  expect(handleSubmit).toHaveBeenCalledWith({<br>    email: &#39;user@example.com&#39;,<br>    password: &#39;password123&#39;,<br>  })<br>})</pre><h3>End-to-End Tests</h3><p>Using Playwright to test the login flow:</p><pre>// login.spec.js<br>import { test, expect } from &#39;@playwright/test&#39;<br><br>test(&#39;user can log in&#39;, async ({ page }) =&gt; {<br>  await page.goto(&#39;/login&#39;)<br>  await page.fill(&#39;input[name=&quot;email&quot;]&#39;, &#39;user@example.com&#39;)<br>  await page.fill(&#39;input[name=&quot;password&quot;]&#39;, &#39;password123&#39;)<br>  await page.click(&#39;button[type=&quot;submit&quot;]&#39;)<br>  // Verify user was redirected to dashboard<br>  await expect(page).toURL(&#39;/dashboard&#39;)<br>  await expect(page.locator(&#39;h1&#39;)).toContainText(&#39;Welcome back&#39;)<br>})</pre><h3>Recommended Frameworks for each test type</h3><h3>Static Testing</h3><ul><li><strong>TypeScript</strong>: Adds type-checking to JavaScript</li><li><strong>ESLint</strong>: Identifies problematic patterns</li><li><strong>Biome</strong>: Modern linter and formatter</li></ul><h3>Unit Testing</h3><ul><li><strong>Vitest</strong>: Fast unit test runner with great React support</li></ul><h3>Integration Testing</h3><ul><li><strong>Vitest</strong>: Fast unit test runner with great React support</li><li><strong>Storybook</strong>: Component workshop for visual testing and development</li></ul><h3>End-to-End Testing</h3><ul><li><strong>Playwright</strong>: Modern E2E testing tool with cross-browser support</li></ul><h3>Balancing your test portfolio for maximum value</h3><p>While the Testing Trophy offers a good template, your ideal test mix depends on your project. Consider these factors when deciding:</p><ol><li><strong>Application complexity</strong>: More complex apps need more integration and E2E tests</li><li><strong>Team size</strong>: Larger teams benefit from more tests as communication overhead increases</li><li><strong>Stability requirements</strong>: Critical systems need more test coverage</li><li><strong>Development phase</strong>: Early-stage products might focus on fewer, high-value tests</li></ol><p>Remember these practical tips:</p><ul><li><strong>Start with static type checking and linting</strong> — they’re the cheapest way to catch errors</li><li><strong>Don’t aim for 100% test coverage</strong>; it often leads to testing implementation details</li><li><strong>Focus on user workflows</strong> rather than implementation details</li><li><strong>If a test is hard to write, it might be telling you something about your code design</strong></li></ul><p>By following the Testing Trophy approach and adjusting for your specific needs, you’ll build a test suite that gives you confidence without slowing down development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=862b100ecddb" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/what-tests-to-write-for-react-862b100ecddb">What tests to write for React</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate Your Job Search: Scraping 400+ LinkedIn Jobs with Python]]></title>
            <link>https://blog.devgenius.io/automate-your-job-search-scraping-400-linkedin-jobs-with-python-1e276eb51f97?source=rss-ab3e94b2ac9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e276eb51f97</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Francisco Moretti]]></dc:creator>
            <pubDate>Mon, 20 Jan 2025 19:49:24 GMT</pubDate>
            <atom:updated>2025-01-21T09:34:07.388Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn how to automate job searching using Python: scrape hundreds of jobs, filter efficiently, and find the perfect role faster.</p><figure><img alt="Post thumbnail" src="https://cdn-images-1.medium.com/max/1024/0*NcLtP4uN9zi4IKo-.jpg" /></figure><p>The average job seeker spends <a href="https://www.linkedin.com/pulse/how-many-hours-per-week-should-one-dedicate-job-search-bob-mcintosh/">11 hours per week searching for jobs</a>, according to LinkedIn. For tech roles, it’s even worse, you’re dealing with hundreds of postings across multiple platforms. When my partner started her job search, she was spending hours daily just scrolling through LinkedIn. There had to be a better way.</p><h4>The Challenge</h4><p>For Web developers, the market is overwhelming. A single search for “Frontend Developer” in London returned 401 results. Each posting requires:</p><ul><li>5 seconds to review the title</li><li>3–4 clicks to view details</li><li>30–60 seconds to scan requirements</li><li>Manual copy-pasting to track interesting roles</li><li>Constant tab switching and back-navigation</li></ul><p>For 401 jobs, that’s hours of pure mechanical work!</p><h4>The Solution: Automation Pipeline</h4><p>I built a three-step automation pipeline that cut the process down to 10 minutes:</p><ol><li>Scrape job data using Python</li><li>Filter in bulk using Google Sheets</li><li>Review only the most promising matches</li></ol><h4>Step 1: Smart Scraping</h4><p>I used <a href="https://github.com/Bunsly/JobSpy">JobSpy</a> as the base and built <a href="https://github.com/FranciscoMoretti/jobsparser">JobsParser</a> to handle:</p><ul><li>CLI</li><li>Rate limiting (to avoid LinkedIn blocks)</li><li>Retry logic for failed requests</li></ul><p>Here’s how to run it:</p><pre>pip install jobsparser</pre><p><strong>**Bonus:**</strong> search manually on LinkedIn the number of results for your search term and use it for the ` — results-wanted` parameter.</p><pre>jobsparser \<br>    --search-term &quot;Frontend Developer&quot; \<br>    --location &quot;London&quot; \<br>    --site linkedin \<br>    --results-wanted 200 \<br>    --distance 25 \<br>    --job-type fulltime</pre><p>If `jobsparser` is not in your path, you can run it as a module directly:</p><pre>python -m jobsparser \<br>    --search-term &quot;Frontend Developer&quot; \<br>    --location &quot;London&quot; \<br>    --site linkedin \<br>    --results-wanted 200 \<br>    --distance 25 \<br>    --job-type fulltime</pre><p>The output is a CSV with rich data:</p><ul><li>Job title and company</li><li>Full description</li><li>Job type and level</li><li>Posted date</li><li>Direct application URL</li></ul><figure><img alt="JobsParser CLI" src="https://cdn-images-1.medium.com/max/1024/0*YA_kPr8a_lFfdd3B.png" /></figure><p><em>JobSpy and JobsParser are also compatible with other job boards like LinkedIn, Indeed, Glassdoor, Google &amp; ZipRecruiter.</em></p><h4>Step 2: Bulk Filtering</h4><p>While pandas seemed obvious (and I’ve given it a fair try), Google Sheets proved more flexible. Here’s my filtering strategy:</p><ol><li><strong>Time Filter</strong>: Last 7 days</li></ol><ul><li>Jobs older than a week have lower response rates</li><li>Fresh postings mean active hiring</li></ul><figure><img alt="Time Filter" src="https://cdn-images-1.medium.com/max/1024/0*zMAG0M3wwNNfs--q.gif" /><figcaption>Time Filter</figcaption></figure><ol><li><strong>Experience Filter</strong>: “job_level” matching your experience:</li></ol><p>For my partner who is looking for her first role, I filtered:</p><ul><li>“Internship”</li><li>“Entry Level”</li><li>“Not Applicable”</li></ul><figure><img alt="Job Level Filter" src="https://cdn-images-1.medium.com/max/1024/0*5JFuu4MJG78Fhx7C.gif" /><figcaption>Experience Filter</figcaption></figure><ol><li><strong>Tech Stack Filter</strong>: “description” contains:</li></ol><ul><li>The word “React”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GAdydeHxW-6J3UsiLH6v0w.gif" /><figcaption>Description Filter</figcaption></figure><p><em>More complex filters can be created to check for multiple technologies.</em></p><p>This cut 401 jobs down to 8 matches!</p><h4>Step 3: Smart Review</h4><p>For the filtered jobs:</p><ol><li>Quick scan of title/company (10 seconds)</li><li>Open promising job_url in new tab</li><li>Check the description in detail.</li></ol><h4>Conclusion</h4><p>I hope this tool helps you make your job search a slightly more enjoyable experience.</p><p>If you have any questions or feedback, please let me know.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e276eb51f97" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/automate-your-job-search-scraping-400-linkedin-jobs-with-python-1e276eb51f97">Automate Your Job Search: Scraping 400+ LinkedIn Jobs with Python</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node.js File Writing Methods — createWriteStream vs writeFileSync]]></title>
            <link>https://medium.com/@franciscomoretti/node-js-file-writing-methods-createwritestream-vs-writefilesync-fab8703d423d?source=rss-ab3e94b2ac9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fab8703d423d</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Francisco Moretti]]></dc:creator>
            <pubDate>Mon, 13 Jan 2025 10:08:18 GMT</pubDate>
            <atom:updated>2025-01-13T10:08:18.321Z</atom:updated>
            <content:encoded><![CDATA[<p>Explore the key differences between Node.js file writing methods — createWriteStream and writeFileSync. Learn when to use each method for optimal performance and better memory management.</p><p>When working with Node.js file system operations, choosing the right method to write files can significantly impact your application’s performance. Let’s explore two common approaches: fs.createWriteStream() and fs.writeFileSync().</p><h4>Key Differences at a Glance</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98610ccc53eff27d5eafbe077394403b/href">https://medium.com/media/98610ccc53eff27d5eafbe077394403b/href</a></iframe><h4>Using createWriteStream</h4><p>The stream-based approach is ideal for handling large files or when you need to write data frequently:</p><pre>const fs = require(&#39;fs&#39;)<br><br>// Content to write<br>const content = &#39;Hello, Node.js file system!&#39;<br><br>// Create a write stream<br>const writeStream = fs.createWriteStream(&#39;example1.txt&#39;)<br><br>// Write to the file<br>writeStream.write(content, &#39;UTF8&#39;)<br><br>// End the stream<br>writeStream.end()<br><br>// Handle finish event<br>writeStream.on(&#39;finish&#39;, () =&gt; {<br>  console.log(&#39;Write completed.&#39;)<br>})<br><br>// Handle error event<br>writeStream.on(&#39;error&#39;, (err) =&gt; {<br>  console.error(&#39;An error occurred:&#39;, err.message)<br>})<br><br>console.log(&#39;Program continues executing immediately.&#39;)</pre><h4>Key Benefits 🎯</h4><ul><li>Non-blocking operation</li><li>Memory efficient for large files</li><li>Automatic backpressure handling</li><li>Ideal for real-time data processing</li></ul><h4>Using writeFileSync</h4><p>For simple, one-off writes with small files, the synchronous approach might be more straightforward:</p><pre>const fs = require(&#39;fs&#39;)<br><br>// Content to write<br>const content = &#39;Hello, Node.js file system!&#39;<br><br>try {<br>  // Write to the file synchronously<br>  fs.writeFileSync(&#39;example2.txt&#39;, content, &#39;UTF8&#39;)<br>  console.log(&#39;Write completed.&#39;)<br>} catch (err) {<br>  console.error(&#39;An error occurred:&#39;, err.message)<br>}<br><br>console.log(&#39;This line waits for the write operation to complete.&#39;)</pre><h4>Key Benefits 🎯</h4><ul><li>Simple error handling with try-catch</li><li>Predictable execution flow</li><li>Perfect for configuration files or small data writes</li><li>No callback management needed</li></ul><h4>When to Use Each Method</h4><h4>Choose createWriteStream when:</h4><ul><li>Working with large files</li><li>Handling real-time data streams</li><li>Memory efficiency is crucial</li><li>Non-blocking operation is required</li></ul><h4>Choose writeFileSync when:</h4><ul><li>Writing small configuration files</li><li>Simple, one-off writes</li><li>Synchronous operation is acceptable</li><li>Working with startup configurations</li></ul><h4>Conclusion</h4><p>Both methods have their place in Node.js development. createWriteStream shines in scenarios involving large files or frequent writes, while writeFileSync is perfect for simple, small file operations. Choose based on your specific use case, considering factors like file size, write frequency, and performance requirements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fab8703d423d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Color Highlighting for Tailwind CSS Variables in VS Code]]></title>
            <link>https://medium.com/@franciscomoretti/color-highlighting-for-tailwind-css-variables-in-vs-code-a773ebf5a2b1?source=rss-ab3e94b2ac9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a773ebf5a2b1</guid>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[shadcn-ui]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <dc:creator><![CDATA[Francisco Moretti]]></dc:creator>
            <pubDate>Fri, 03 Jan 2025 18:01:29 GMT</pubDate>
            <atom:updated>2025-01-03T18:01:29.993Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn how to enable color highlighting for Tailwind CSS variables in VS Code, especially useful when working with Shadcn UI components.</p><p>When working with Tailwind CSS variables in VS Code, having visual color indicators can significantly improve your development workflow. This is particularly useful when working with Shadcn UI components, which heavily rely on CSS variables for theming.</p><h4>The Solution</h4><ol><li>Install the Color Highlight extension by Sergii N from the <a href="https://marketplace.visualstudio.com/items?itemName=naumovs.color-highlight">VS Code Marketplace</a></li><li>Enable HSL color highlighting by adding this to your VS Code settings.json:</li></ol><pre>{<br>  &quot;color-highlight.matchHslWithNoFunction&quot;: true<br>}</pre><h4>Result</h4><p>With this setup, you’ll see color indicators next to your Tailwind CSS variables, making it easier to identify and work with colors in your stylesheets, especially when customizing Shadcn UI themes:</p><figure><img alt="Color highlighting in VS Code" src="https://cdn-images-1.medium.com/max/691/0*zRwFHguuzYzpYdnW.png" /></figure><p>This simple configuration works with both standard CSS colors and HSL values, making your Tailwind CSS and Shadcn UI development experience more visual and intuitive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a773ebf5a2b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js Authentication Best Practices]]></title>
            <link>https://medium.com/@franciscomoretti/next-js-authentication-best-practices-6897dad3a170?source=rss-ab3e94b2ac9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6897dad3a170</guid>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Francisco Moretti]]></dc:creator>
            <pubDate>Wed, 26 Jun 2024 11:31:21 GMT</pubDate>
            <atom:updated>2025-04-01T09:30:34.394Z</atom:updated>
            <content:encoded><![CDATA[<p>&gt; <strong>**IMPORTANT**</strong>: This article contains outdated advice. Next.js has significantly changed its authentication recommendations. Please refer to the <a href="https://www.franciscomoretti.com/blog/modern-nextjs-authentication-best-practices">updated authentication guide</a> for current best practices.</p><p>Explore key Next.js authentication best practices, including middleware vs. page component auth, preserving static rendering, and implementing multi-layered protection.</p><figure><img alt="Post thumbnail" src="https://cdn-images-1.medium.com/max/1024/0*lAEl6uy7NCjZ9VB8.png" /></figure><h4>What is Next.js Authentication?</h4><p>Next.js authentication is the process of verifying user identity in Next.js applications. It ensures that only authorized users can access protected routes and data.</p><p>Authentication in Next.js is crucial for:</p><ol><li>Protecting sensitive user data</li><li>Controlling access to specific features</li><li>Personalizing user experiences</li><li>Maintaining application security</li></ol><p>Understanding Next.js authentication best practices is key to building secure and efficient web applications.</p><h4>Middleware vs. Page Component Authentication</h4><p>Next.js provides two main approaches to authentication: middleware and page component authentication. Let’s explore both:</p><h4>Middleware Authentication</h4><p>Middleware authentication offers several advantages:</p><ul><li>Cleaner structure for managing authentication across routes</li><li>Preserves static rendering capabilities</li><li>Better performance, especially with JSON Web Tokens (JWTs)</li></ul><p>Here’s a simple example of middleware authentication:</p><pre>import type { NextRequest } from &#39;next/server&#39;<br> <br>export function middleware(request: NextRequest) {<br>  const currentUser = request.cookies.get(&#39;currentUser&#39;)?.value<br> <br>  if (currentUser &amp;&amp; !request.nextUrl.pathname.startsWith(&#39;/dashboard&#39;)) {<br>    return Response.redirect(new URL(&#39;/dashboard&#39;, request.url))<br>  }<br> <br>  if (!currentUser &amp;&amp; !request.nextUrl.pathname.startsWith(&#39;/login&#39;)) {<br>    return Response.redirect(new URL(&#39;/login&#39;, request.url))<br>  }<br>}<br> <br>export const config = {<br>  matcher: [&#39;/((?!api|_next/static|_next/image|.*\\.png$).*)&#39;],<br>}</pre><h4>Page Component Authentication</h4><p>Page component authentication has its own benefits:</p><ul><li>Can be implemented directly in the page file</li><li>Offers more flexibility for page-specific auth logic</li></ul><p>Here’s an example of page component authentication:</p><pre>import { redirect } from &#39;next/navigation&#39;;<br>import { checkAuth } from &#39;@/lib/auth&#39;;<br><br>export default async function ProtectedPage() {<br>  const isAuthenticated = await checkAuth();<br>  if (!isAuthenticated) {<br>    redirect(&#39;/login&#39;);<br>  }<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Protected Content&lt;/h1&gt;<br>      {/* Page content here */}<br>    &lt;/div&gt;<br>  );<br>}</pre><blockquote>💡 Tip: Choose middleware for better performance and cleaner code structure, especially for apps with many protected routes.</blockquote><h4>Avoiding Authentication in Layout Components</h4><p>It’s important to avoid implementing authentication checks in layout components. Why? Layout components don’t re-render on client-side navigation, which could leave routes unprotected.</p><h4>Preserving Static Rendering</h4><p>Static rendering is a key performance feature in Next.js. To preserve it:</p><ol><li>Use middleware for authentication when possible</li><li>Don’t add authentication inside specific routes (pages).</li></ol><p>Adding authentication inside a page makes it dynamic. However, many times the extra security layer benefit outweighs the performance improvement.</p><h4>Authentication for Server Actions</h4><p>Server actions are a new feature in Next.js that allow server-side processing directly from client components. When using server actions:</p><ol><li>Implement authentication checks within the server action itself</li><li>Don’t rely solely on page-level or middleware authentication</li></ol><p>Server actions are like API routes. They could be called by an external user by calling the server action URL directly.</p><h4>Proximity Principle</h4><p>The proximity principle suggests keeping authentication checks as close as possible to where data is accessed or used. This means:</p><ol><li>Implementing checks in reusable components that handle sensitive data</li><li>Adding auth logic directly in data fetching functions</li></ol><p>Here’s an example of applying the proximity principle:</p><pre>async function fetchUserData(userId: string) {<br>	const isAuthenticated = await checkAuth();<br>  if (!isAuthenticated) {<br>    throw new Error(&#39;Unauthorized&#39;);<br>  }<br><br>  // Fetch and return user data<br>}</pre><h4>Multi-layered Approach</h4><p>A robust authentication strategy in Next.js involves multiple layers of protection:</p><ol><li>Use middleware or page-level checks as a first line of defense</li><li>Implement additional checks at the page and data access levels</li></ol><p>Here’s a simplified example of a multi-layered approach:</p><pre>// Middleware (first layer)<br>export function middleware(request: NextRequest) {<br>  // Check for auth token<br>}<br><br>// Page component (second layer)<br>export default function ProtectedPage() {<br>  const { user } = useUser(); // Custom hook for user data<br>  if (!user) return &lt;LoadingOrRedirect /&gt;;<br><br>  return &lt;ProtectedContent user={user} /&gt;;<br>}<br><br>// Data fetching (third layer)<br>async function fetchSensitiveData() {<br>  // Check auth and permissions before fetching<br>}</pre><h4>Conclusion</h4><p>Next.js authentication best practices involve a combination of techniques:</p><ol><li>Use middleware for app-wide auth when possible</li><li>Implement page-level checks for specific routes</li><li>Apply the proximity principle for data access</li></ol><h4>References</h4><ul><li><a href="https://www.youtube.com/watch?v=kbCzZzXTjuw&amp;t=23s">Next.js Authentication — Avoid these 4 mistakes (Don’t do auth in layout!)</a></li><li><a href="https://nextjs.org/docs/app/building-your-application/authentication">Authentication — Next.js</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6897dad3a170" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Server Side Rendering Vs Client Side Rendering Waterfall]]></title>
            <link>https://medium.com/@franciscomoretti/server-side-rendering-vs-client-side-rendering-waterfall-48619d52cff0?source=rss-ab3e94b2ac9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/48619d52cff0</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Francisco Moretti]]></dc:creator>
            <pubDate>Thu, 20 Jun 2024 11:16:16 GMT</pubDate>
            <atom:updated>2024-06-20T11:16:16.986Z</atom:updated>
            <content:encoded><![CDATA[<p>Explore the impact of server-side rendering (SSR) and client-side rendering (CSR) on performance, focusing on the waterfall effect in React applications.</p><figure><img alt="Post thumbnail" src="https://cdn-images-1.medium.com/max/1024/0*UoeqKLhEF93kkW_b.png" /></figure><h4>What is Server Side Rendering (SSR)?</h4><p>Server-side rendering (SSR) is a technique where the initial HTML of a web page is generated on the server and sent to the client’s browser. This approach allows for faster initial page loads and better search engine optimization (SEO) since search engines can easily crawl and index the rendered content.</p><h4>What is Client Side Rendering (CSR)?</h4><p>Client-side rendering (CSR) is a technique where the initial HTML of a web page is minimal, and the content is rendered dynamically on the client-side using JavaScript. This approach can provide a more seamless and interactive user experience, but it may result in slower initial page loads and potential SEO challenges.</p><h4>The Waterfall Effect</h4><p>The waterfall effect refers to the sequence of network requests and responses required to load a web page fully. Each request must wait for the previous one to complete, creating a cascading effect similar to a waterfall.</p><figure><img alt="SSR vs CSR waterfall" src="https://cdn-images-1.medium.com/max/874/0*JRi_CIid6RFqK8HK.png" /></figure><h4>Client-Side Rendering Waterfall</h4><p>In a client-side rendered React application, the waterfall effect can be more pronounced due to the multiple round trips required to fetch the necessary JavaScript files and data. Let’s consider an example with a Post component and a child Comment component:</p><ol><li><strong>Initial Markup (without content)</strong>: The browser receives the initial HTML markup, which contains placeholders for the React components.</li><li><strong>Get the </strong><strong>Post JS</strong>: The browser fetches the JavaScript file(s) required to render the Post component.</li><li><strong>Get the </strong><strong>Post content</strong>: Once the Post component is loaded, the browser fetches the data required to render the post content.</li><li><strong>Get the </strong><strong>Comment JS</strong>: The browser fetches the JavaScript file(s) required to render the Comment component.</li><li><strong>Get the </strong><strong>Comment content</strong>: Finally, the browser fetches the data required to render the comment content.</li></ol><p>This process results in a waterfall with five distinct steps, potentially leading to longer load times and a perceived delay in rendering the complete page.</p><h4>Server-Side Rendering Waterfall</h4><p>In contrast, with server-side rendering, the waterfall effect can be significantly reduced. Here’s how it might look for the same Post and Comment components:</p><ol><li><strong>Markup (with content)</strong>: The server generates and sends the initial HTML markup with the rendered content for both the Post and Comment components.</li><li><strong>Get in parallel</strong>:</li></ol><ul><li><strong>The </strong><strong>Post JS</strong>: The browser fetches the JavaScript file(s) required for the Post component.</li><li><strong>The </strong><strong>Comment JS</strong>: The browser fetches the JavaScript file(s) required for the Comment component.</li></ul><p>By rendering the initial content on the server, the waterfall is reduced to just two steps, potentially resulting in faster initial page loads and improved perceived performance.</p><h4>Conclusion</h4><p>The choice between server-side rendering (SSR) and client-side rendering (CSR) in React applications can significantly impact performance, particularly when considering the waterfall effect. SSR generally results in a shorter waterfall and faster initial page loads, while CSR may be easier to achieve, it can have a longer waterfall.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48619d52cff0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RunJS — A JavaScript and TypeScript Local Playground]]></title>
            <link>https://medium.com/@franciscomoretti/runjs-a-javascript-and-typescript-local-playground-83e379935d3a?source=rss-ab3e94b2ac9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/83e379935d3a</guid>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Francisco Moretti]]></dc:creator>
            <pubDate>Fri, 07 Jun 2024 09:24:57 GMT</pubDate>
            <atom:updated>2024-06-07T09:24:57.871Z</atom:updated>
            <content:encoded><![CDATA[<p>RunJS, a local playground for JavaScript and TypeScript. Exploring its features and use cases with code examples.</p><figure><img alt="Post thumbnail" src="https://cdn-images-1.medium.com/max/1024/0*tEBM8NyRhjO8-q1q.png" /></figure><h4>Intro</h4><p>Recently, I got a license from Luke Haas to explore <a href="https://runjs.app/">RunJS</a>, and I’m impressed with some of the features. I’ve been putting it to the test and integrating it into my workflow. It’s worth mentioning that there is a free version with core functionality, and the license gives you lifetime access (with updates for 1 year), which is rare these days. Another thing I love about it is that it’s open source. In this post, I’ll be sharing my experience with RunJS and how it’s helping me in my daily work.</p><h4>What is RunJS?</h4><p>RunJS is a local playground for JavaScript and TypeScript. It allows you to write, execute, and see the results of your code instantly. Unlike IDEs, RunJS has a minimalistic, distraction-free interface perfect for quick experiments and learning.</p><h4>Why Choose RunJS?</h4><ol><li><strong>Minimalistic Interface:</strong> RunJS offers a clean, distraction-free environment. This simplicity helps you focus on your code, making it great for presentations and screen sharing.</li><li><strong>Continuous Code Execution:</strong> RunJS continuously executes your code as you type. This instant feedback loop is invaluable for testing and learning.</li><li><strong>Run JS and TS with no configuration:</strong> RunJS supports both JavaScript and TypeScript out of the box. No need to run node or to setup TS. It simply works.</li></ol><h4>Use cases for RunJS</h4><p>These are some of the use cases that I’ve personally found useful.</p><h4>1. Exploring JS Language Features</h4><p>JavaScript is weird. RunJS helps you understand them by letting you execute code snippets instantly. This is great for trying out language features or understanding tricky parts of JavaScript.</p><figure><img alt="JavaScript is weird demo" src="https://cdn-images-1.medium.com/max/1024/0*QwULg9QbtepbxDBj.png" /></figure><p>Note that it highlights some of these errors to help you avoid the fitfalls of JavaScript.</p><h4>2. Printing the Output of Code Execution</h4><p>RunJS makes it easy to see the output of your code as you type. This feature is perfect for debugging and understanding how your code works.</p><figure><img alt="Runjs output demo" src="https://cdn-images-1.medium.com/max/1024/0*A4cbg1jFK7y0c7gn.gif" /></figure><h4>3. Executing JS/TS Without Creating a File</h4><p>With RunJS, there’s no need to create files or set up a Node environment to run your code. This is ideal for quick experiments or learning sessions.</p><h4>4. Solving LeetCode Problems</h4><p>This is my favorite use case for RunJS. RunJS allows you to print the output of test cases and different parts of the code easily, making debugging and understanding your solution much simpler. The distraction-free interface of RunJS helps a lot here.</p><p>You can code all the function with auto-completion support and error linting. It’s also convenient to see the output of all the test cases at the end and check how they do without having to hit run every time.</p><p>Super helpful for small problems like this one.</p><figure><img alt="alt text" src="https://cdn-images-1.medium.com/max/1024/0*KRB6v9Yaxt6oldrJ.png" /></figure><p>Showing another small one that fits in the screen, but it’s also helpful for complex problems.1</p><figure><img alt="alt text" src="https://cdn-images-1.medium.com/max/1024/0*HcK9mJntlRE9SMqy.png" /></figure><p>Oh and you might have noticed that the last case should be true. Wrong! This is not how array comparison works in JS. Here RunJS is helping you to understand the problem with an error message.</p><figure><img alt="alt text" src="https://cdn-images-1.medium.com/max/867/0*FGEfwf1OZfq2S5rr.png" /></figure><h4>Conclusion</h4><p><a href="https://runjs.app/">RunJS</a> is a nice tool for JavaScript and TypeScript coding. Its simple interface and instant feedback make it perfect for learning, and prototyping. It’s not going to replace your IDE but it can be a great addition to your workflow. By being different, and by keeping things simple, it does better than IDEs for some tasks. In my opinion, is a specialized tool that helps with communication, exploring and focus.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83e379935d3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>