<?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 Fredrik Erasmus on Medium]]></title>
        <description><![CDATA[Stories by Fredrik Erasmus on Medium]]></description>
        <link>https://medium.com/@fredrik_erasmus?source=rss-32d514a8ab9c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xWzLifLuMuP2Mc_hcFSUNA.jpeg</url>
            <title>Stories by Fredrik Erasmus on Medium</title>
            <link>https://medium.com/@fredrik_erasmus?source=rss-32d514a8ab9c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 12:46:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fredrik_erasmus/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[Additional Concepts of Large Language Models]]></title>
            <link>https://medium.com/@fredrik_erasmus/additional-concepts-of-large-language-models-336ca19d3284?source=rss-32d514a8ab9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/336ca19d3284</guid>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Fredrik Erasmus]]></dc:creator>
            <pubDate>Thu, 28 Nov 2024 10:22:43 GMT</pubDate>
            <atom:updated>2024-11-28T10:22:43.640Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NCbZITsSjdpsWJjx" /></figure><h3>Introduction</h3><p>I’ll be honest I’m not sure where I am headed with these Large Language Model posts. As a software engineer that enjoys writing code I do get the sense that having a better understanding of Large Language Models will help me build better applications in the future.</p><p>The reality at present is that Large Language Models (LLMs)have infiltrated our lives. From using ChatGPT for a recipe using a list of ingredients to using tools like GitHub CoPilot and Cursor AI the impact is undeniable. We cannot really go back to working without it.</p><p>I wrote several short posts on some LLM topics:</p><ul><li><strong>My attempt at understanding AI: </strong><a href="https://medium.com/@fredrik_erasmus/my-attempt-at-understanding-ai-fe8f69999ed4?source=your_stories_page-------------------------------------">https://medium.com/@fredrik_erasmus/my-attempt-at-understanding-ai-fe8f69999ed4</a></li><li><strong>What is a neural network architecture: </strong><a href="https://medium.com/@fredrik_erasmus/what-is-a-neural-network-architecture-ae0e700207c2?source=your_stories_page-------------------------------------">https://medium.com/@fredrik_erasmus/what-is-a-neural-network-architecture-ae0e700207c2</a></li><li><strong>Foundational Models: </strong><a href="https://medium.com/@fredrik_erasmus/foundational-models-c51132242fc4?source=your_stories_page-------------------------------------">https://medium.com/@fredrik_erasmus/foundational-models-c51132242fc4</a></li></ul><p>The aim of these posts is an attempt to reflect some level of understanding. The realm of LLMs is intimidating to say the least but you have to start somewhere.</p><p>As a software engineer I can either continue doing things the same way. In particular when it comes to using tools like ChatGPT or CoPilot or Cursor I could just keep writing prompts in the same way. In my case my approach in the beginning was to simply throw content at the LLM and see what happens. You know kinda throwing mud against a barn door and seeing what sticks. But as you discover the nature of an LLM you begin to realise there are nuances. For instance an LLM can do many things but it cannot reason like a human. An LLM simply attempts to respond to your prompts with the next set of tokens. Understanding this shapes the way you approach your prompts. But it also begs the question — what else can I learn about LLMs to improve my software engineering skills.</p><h3><strong>Key Concepts</strong></h3><p>Prompts and tokens are two fundamental concepts. A prompt is a piece of text you write with an instruction to the LLM. The way you structure the prompt is also very important using concepts like cues, zero-shot and few-shot learning. LLMs like ChatGPT “understand” your language. A token represents a single character, a fraction of a word or an entire phrase. A single token can represent common words and multiple tokens can be used for less common words. Understanding the token count is important if you need to consider an LLM model. The cost of running an LLM is usually determined by the number of tokens the LLM model processes. The context window is the number of tokens you can provide as an input to the model.</p><p>If you look at the <a href="https://platform.openai.com/docs/models/gpt-4o">ChatGPt models</a> you will note that GPT-4o, GPT-4o-mini and o1-preview and o1-mini all have a 128k context length. To be clear the 128k content length refers to the total context length including the input and the output. But exactly how much is 128k tokens?</p><p>The 128k token limit for ChatGPT-4 refers to the total context window, which includes:</p><ol><li>Input tokens: The tokens in the text you send to the model.</li><li>Output tokens: The tokens in the model’s response.</li></ol><h3>How It Works:</h3><ul><li>The context window is the combined size of both the input and output, meaning everything the model “sees” and generates in a single interaction or session.</li><li>If you send a very large input (e.g., 120k tokens), the model has only a small portion of the window left for its response (e.g., 8k tokens).</li><li>Conversely, if your input is smaller, the model can generate a longer output.</li></ul><h3>Key Considerations:</h3><ul><li>Tokens are a unit of text that include words, parts of words, or punctuation. For example, “ChatGPT is awesome!” might count as 5 tokens.</li><li>If the total tokens (input + output) exceed the context window (128k), the model will not process the input fully or generate the desired response, as it cannot “see” beyond that limit.</li></ul><p>This token limit is designed to handle large amounts of text in a single interaction, allowing for longer conversations, document analysis, and other complex tasks.</p><p>If you go to <a href="https://platform.openai.com/tokenizer">the ChatGPT tokenizer</a> you can paste content to get an idea of the number of input tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*TM-qBG7RPWjtsxZKBwFYOg.png" /></figure><p>I used a random Markdown document to test it out. In the example the content of the document contains 1997 tokens and 9516 characters. As you can see there isn’t a 1–1 relationship between the token and character count. Also note how the tokenizer uses the colourful labels to denote the tokens. Understanding the token usage is important because ultimately there are costs involved. The token count means that ChatGPT can respond with roughly 126k tokens in its output. Although in practice it will be less because the response will not need all the tokens.</p><p>At the bottom of <a href="https://platform.openai.com/tokenizer">the ChatGPT tokenizer</a> page there is a link to the <a href="https://github.com/openai/tiktoken">tiktoken repo</a> as well as a link to a JavaScript port of <a href="https://www.npmjs.com/package/tiktoken">TikToken</a>. I tried installing the npm package using Vite but there were dependency issues. So eventually I ended up on <a href="https://github.com/dqbd/tiktokenizer">another repository</a> with a NextJS implementation. I installed Yarn and tried running it but it failed. It appears to require a HuggingFace API key. I registered an account with HuggingFace to get an API key, applied it to the .env but it still did not work. It would have been interesting to see how the tokenizer works in an actual application. I did not want to spend too much time on trying to fix the app so I moved on.</p><p>It did lead me to look at HuggingFace in a different light. I never really knew much about it but a few questions came to mind.</p><h3>What is the difference between a dataset and a model?</h3><p>The basic gist is that a model is a pre-trained machine learning model. It is a computational artefact that performs a specific task like text generation, classification, translation or summarization. Models are built using various architectures such as Transformers and are trained on datasets to learn patterns and representations. A dataset on the other hand are the inputs the models use.</p><p>You’re absolutely on the right track with your conceptual understanding! Let me refine and expand on your explanation to solidify the distinction and interplay between a model and a dataset in the context of machine learning. Conceptually speaking the dataset is used to train the model. The model then uses the data to process and adjust its parameters. This relates back to the hidden layer in an LLM. the hidden layer uses the weights and biases and activation functions. Once the model is trained the output that is generated in response to a prompt, for instance, it uses the relationships learned from the dataset to respond.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=336ca19d3284" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Foundational Models]]></title>
            <link>https://medium.com/@fredrik_erasmus/foundational-models-c51132242fc4?source=rss-32d514a8ab9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c51132242fc4</guid>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Fredrik Erasmus]]></dc:creator>
            <pubDate>Mon, 25 Nov 2024 07:38:23 GMT</pubDate>
            <atom:updated>2024-11-25T07:38:23.199Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*53KxPUU-AEBf4zLr" /></figure><p>A foundational model refers to a specific instance or version of an LLM model. When using ChatGPT you can select a foundational model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*KwMqE2ik8HJb_ziaNSg7oA.png" /></figure><p>Foundational models are trained on large, varied datasets. Input data used from books, websites, forums, images and code repositories. Transformers process input data in chunks called tokens. These tokens pass through attention mechanisms, which allow the model to understand the relationships between words, pixels, or other data points. The model learns to represent the data in high-dimensional spaces, capturing contextual meanings and patterns.</p><p>During training the model performs a task such as predicting the next token. If you think about it ChatGPT simply attempts to predict the next token.</p><p>Once a foundational model is trained, it can be adapted to specific tasks in two primary ways:</p><h3>a. Prompting</h3><ul><li>How It Works: Prompting involves providing a structured input (a “prompt”) that guides the model to perform a specific task.</li><li>Example: In a language model, you can input:<br><em>“Summarize this article in one sentence: [text]”</em><br>The model responds with a summary based on its general knowledge.</li></ul><p>Advantages:</p><ul><li>Requires no additional training (zero-shot learning).</li><li>Can handle a wide variety of tasks by simply adjusting the input format.</li></ul><p>Limitations:</p><ul><li>Might not always produce highly accurate or domain-specific results without further tuning.</li></ul><h3>b. Fine-Tuning</h3><ul><li>How It Works: Fine-tuning involves training the foundational model further on task-specific or domain-specific data.</li><li>Example: A foundational model fine-tuned on medical texts can generate diagnoses or summarize medical papers.</li></ul><p>Advantages:</p><ul><li>Allows the model to specialize, improving performance on a given task.</li><li>Results in models that are more aligned with specific industries, tasks, or user requirements.</li></ul><p>Limitations:</p><ul><li>Requires labeled data for the target task.</li><li>Computationally expensive, though less so than training from scratch.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c51132242fc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is a neural network architecture?]]></title>
            <link>https://medium.com/@fredrik_erasmus/what-is-a-neural-network-architecture-ae0e700207c2?source=rss-32d514a8ab9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae0e700207c2</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Fredrik Erasmus]]></dc:creator>
            <pubDate>Fri, 22 Nov 2024 08:41:44 GMT</pubDate>
            <atom:updated>2024-11-22T08:41:44.757Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yPBlRumvOnkFqv0F" /></figure><p>In its most basic form a Neural Network Architecture uses neurons as its basic unit. Each neuron receives an input signal, which it processes and generates an output from. The neural network is made up of an input layer, a hidden layer and an output layer. The input layer accepts data. The neurons on the input layer do not perform any processing — they simply pass the data onto the next layer. The hidden layer is where the heavy lifting is performed. The hidden layer performs the bulk of the computations — it applies weights and biases and uses activation functions to transform the input data. The output layer produces the final output result from the network.</p><h3>Hidden layers</h3><p>What are hidden layers? Hidden layers are not visible to the user. Hidden layers are responsible for extracting patterns and transforming data from the input layer into a form that can be used by the output layer. They enable the network to model complex, non-linear relationships in the data. Each neuron in a hidden layer takes inputs from the previous layer (either the input layer or another hidden layer). The neuron computes a weighted sum of these inputs, adds a bias term, and applies an activation function to produce an output. The outputs from one hidden layer serve as the inputs for the next layer. Without activation functions, the network would essentially be a linear model, limiting its ability to learn from complex data. Activation functions in the hidden layers introduce non-linearities, allowing the network to solve more complex problems, such as image recognition or language understanding.</p><p>Ever hear the term fine-tuning a model being used? Fine-tuning involves adjusting the model’s parameters (weights and biases) to improve its performance, typically after a pretraining phase or to adapt the model to a specific task.</p><p>The hidden layers are responsible for extracting hierarchical features from the input data.</p><p>Fine-tuning adjusts the weights and biases in these layers to refine how the model represents the data, focusing on features most relevant to the specific task.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae0e700207c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My attempt at understanding AI]]></title>
            <link>https://medium.com/@fredrik_erasmus/my-attempt-at-understanding-ai-fe8f69999ed4?source=rss-32d514a8ab9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe8f69999ed4</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Fredrik Erasmus]]></dc:creator>
            <pubDate>Thu, 21 Nov 2024 10:33:41 GMT</pubDate>
            <atom:updated>2024-11-21T10:33:41.411Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Ne6U9ESV1hrg1eSrkDTvA.png" /></figure><h3>Introduction</h3><p>I have been using generative tools like ChatGPT and Cursor AI for quite some time. Honestly though I never took to understand the finer details. Why would it be beneficial to understand the finer details you ask? Sometimes it takes a small detail to fundamentally alter your view on something. Small details over time are significant in the long term. I found a great GitHub repo recently — <a href="https://github.com/microsoft/generative-ai-with-javascript">Code samples and resources to learn Generative AI with JavaScript</a>. So much of my focus these days seems to target JavaScript from NextJS to Astro to standard web components. My goal is definitely not to focus on the exact mechanics used in Large Language Models (LLM) but instead incorporate it into my development experience using JavaScript. Learning about AI or any of its disciplines does not appeal as much as being able to create interesting applications.</p><h3>Narrow AI (Weak AI) models</h3><p>Before I never really took the time to notice the differences between AI models. AI can be categorised by their capabilities. ChatGPT, for instance, is a Large Language Model that can process and understand language. LLMs such as ChatGPT use large sets of data — the web and all its content. LLMs are still considered as Narrow AI or Weak AI because they cannot perform intellectual tasks performed by humans. LLMs are designed to try and generate the best next response to your prompt. It does not have any reasoning capabilities. It uses its training data to provide a response. Within the Narrow AI realm there are traditional models used to perform narrow or single tasks. They are different from LLMs in that they are not designed to process natural language. Traditional Narrow AI systems like Siri or Alexa are designed to process and generate in a very specific manner. ChatGPT, for instance, is more general purpose as it can generate images from your prompts in addition to generating responses to questions. LLMs do not possess any intelligence as they really are pattern-based generators.</p><p><strong>ChatGPT:</strong> an example of a Large Language Model (LLM) capable of processing and generating human-like text based on vast amounts of training data. It excels in natural language understanding and generation.</p><p><strong>Siri and Alexa</strong>: These are also Narrow AI models, focused on natural language processing for specific tasks such as setting reminders, playing music, or retrieving information. They have narrower scopes compared to broader LLMs but are optimized for real-time user interaction.</p><p><strong>Traditional Narrow AI:</strong> This includes models designed for tasks like image recognition, speech synthesis, recommendation systems, etc., not necessarily involving natural language.</p><h3>General AI</h3><p>I recall waiting in bated breath to see if OpenAI were (or still are) going to release ChatGPT 5. Speculation on social media seemed to suggest OpenAI had achieved General AI in some way. Maybe they have, who knows. It&#39;s good to understand that something like ChatGPT in its current form is still not General AI. General AI is a Hypothetical AI that can perform any intellectual task a human can do. It would have reasoning, problem-solving, and abstract thinking abilities comparable to a human.</p><p><strong>Example:</strong> Not yet achieved but often portrayed in science fiction (e.g., HAL 9000 from <em>*2001: A Space Odyssey*</em>). <a href="https://www.youtube.com/watch?v=ARJ8cAGm6JE">HAL 9000: “I’m sorry Dave, I’m afraid I can’t do that”</a></p><h3>Super AI</h3><p>Would we see a future where AI surpasses human intelligence in all fields? Would a future exist where AI has the ability to include self-awareness and decision-making far beyond human capabilities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe8f69999ed4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[30 Days of NextJS — Part 3: ReactJS to NextJS]]></title>
            <link>https://medium.com/@fredrik_erasmus/30-days-of-nextjs-part-3-reactjs-to-nextjs-7c6e12524b50?source=rss-32d514a8ab9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c6e12524b50</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Fredrik Erasmus]]></dc:creator>
            <pubDate>Tue, 11 Jun 2024 06:02:36 GMT</pubDate>
            <atom:updated>2024-06-11T06:02:36.478Z</atom:updated>
            <content:encoded><![CDATA[<h3>30 Days of NextJS — Part 3: ReactJS to NextJS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wx2dOOHSpr2xTAicH8bgBQ.png" /></figure><h3>Introduction</h3><p>Onto my third day of covering the basics of NextJS. One thing I did not make very clear is whether the days would be consecutive. I decided to simply write it as it comes. Some days I might get to write consecutive days, on other days I might write it several days apart. In either event the point is to try and build momentum as I go in between the busy life. In my previous two posts the majority of the content focused on ReactJS foundations, from understanding SSR (Server Side Rendering) from the NextJS perspective to foundational aspects such as components and state.</p><ul><li><a href="https://medium.com/@fredrik_erasmus/30-days-of-nextjs-part-1-basic-understanding-d6219e2ff270">30 Days of NextJS — Part 1: Basic Understanding</a></li><li><a href="https://medium.com/@fredrik_erasmus/30-days-of-nextjs-day-2-react-fundamentals-12c926165248">30 Days of NextJS — Part 2: React Fundamentals</a></li></ul><p>In the sections that follow I will continue working through the <a href="https://nextjs.org/learn/react-foundations/from-react-to-nextjs">NextJS learning content</a> building on concepts already covered.</p><h3>From React to Next.js</h3><p>Excerpts taken from the <a href="https://nextjs.org/learn/react-foundations/from-react-to-nextjs">NextJS learning content</a>.</p><blockquote><em>In the last few chapters, you were introduced to three essential React concepts: components, props, and state. Having a strong foundation in these will help you get started building React applications.</em></blockquote><p>It is very important to understand React — you have to keep the fundamental building blocks in mind when creating apps.</p><blockquote><em>When it comes to learning React, the best way to learn is to build. You can gradually adopt React by using </em><em>&lt;script&gt; and what you&#39;ve learned so far to add small components to an existing website. However, many developers have found the user and developer experience React enables valuable enough to dive right in and write their whole frontend application in React.</em></blockquote><p>In the last couple of weeks I have tried building a few of my own experimental NextJS apps. The key take away is that you will only truly learn how something works by experiencing it. You cannot “wait for the righ time” to start building apps. Its almost certain that when you write apps the first time versus the 50th time you will have grown in your understanding.</p><blockquote><em>While React excels at building UI, it does take some work to independently build that UI into a fully functioning scalable application. There are also newer React features, like Server and Client Components, that require a framework. The good news is that Next.js handles much of the setup and configuration and has additional features to help you build React applications.</em></blockquote><p>It’s an important point to consider, one that has been covered before. Starting a ReactJS app may be simple enough in the beginning but as the size and complexity of it grows you invariably need bigger pieces of functionality.</p><blockquote><em>Next, we’ll migrate the example from React to Next.js, discuss how Next.js works, and introduce you to the differences between Server and Client Components.</em></blockquote><p>An important part. Next.js is interesting and I experienced it recently. The distinction between client and server code takes some mental shifts. Not all React.js code can run on the server.</p><h3>Installing Next.js</h3><p>In <a href="https://medium.com/@fredrik_erasmus/30-days-of-nextjs-day-2-react-fundamentals-12c926165248">my previous post</a> I setup a React project using Vite containing a package.json. But it&#39;s not a good idea to use the Next.js cli tooling and Vite in one project. Yes I actually tried it but I quickly ran into issues - would not recommend. So for the purposes of learning I am going to create a separate Next.js project and copy the components from the React JS project. Important lesson here is to stick with the CLI tools that work for a specific project type.</p><blockquote><em>When you use Next.js in your project, you do not need to load the react and react-dom scripts from unpkg.com anymore. Instead, you can install these packages locally using npm or your preferred package manager.</em></blockquote><blockquote><em>To do so, create a new file in the same directory as your index.html file, called package.json with an empty object {}.</em></blockquote><p>I found the experience with Vite and the TypeScript setup great and I naively thought Next.js installs TypeScript when running npm install react@latest react-dom@latest next@latest. But it doesn&#39;t. You can see from the package.json it only installs React and Next.js, nothing more.</p><pre>&quot;dependencies&quot;: {<br>    &quot;next&quot;: &quot;^14.2.3&quot;,<br>    &quot;react&quot;: &quot;^18.3.1&quot;,<br>    &quot;react-dom&quot;: &quot;^18.3.1&quot;<br>  },</pre><p>I found that when I renamed components or files with the *.tsx file extension Next.js is clever enough to figure out that you are running TypeScript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*83oA3kLn6WToSSw8iA9Jow.png" /></figure><p>It goes off and initializes a tsconfig.json, as well as adding the additional dev dependencies.</p><h3>Basic Next.js app</h3><p>I ended up with a project structure — hopefully I will uncover better practices as I learn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*4aPU_GRvpX7PgptjrVDTFQ.png" /></figure><p>The page.tsx was interesting because I could not use export function HomePage I had to use export default HomePage. I also added a layout.tsx, again with the export at the bottom.</p><pre>//page.tsx<br>const homePageBasicProps: BasicProps = {<br>  headerTitle: &#39;Develop. Preview. Ship&#39;,<br>  menuItems: [&#39;Home&#39;, &#39;Services&#39;, &#39;About&#39;, &#39;Contact us&#39;],<br>  footerContent: {<br>    company: &#39;React App&#39;,<br>    year: 2024,<br>  },<br>};</pre><pre>function HomePage() {<br>  return (<br>    &lt;&gt;<br>    &lt;Header headerTitle={homePageBasicProps.headerTitle} /&gt;<br>    &lt;Sidebar menuItems={homePageBasicProps.menuItems} /&gt;<br>    &lt;Footer footerContent={homePageBasicProps.footerContent} /&gt;<br>    &lt;/&gt;<br>  )<br>}</pre><pre>export default HomePage;</pre><pre>//layout.tsx</pre><pre>export const metadata = {<br>  title: &#39;Next.js&#39;,<br>  description: &#39;Generated by Next.js&#39;,<br>}</pre><pre>function RootLayout({<br>  children,<br>}: {<br>  children: React.ReactNode<br>}) {<br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;body&gt;{children}&lt;/body&gt;<br>    &lt;/html&gt;<br>  )<br>}</pre><pre>export default RootLayout;</pre><h3>Named exports vs default exports</h3><p>So why does Next.js follow the convention of exporting the components after the declaration? Well it comes down to understanding the difference between named exports and default exports.</p><p>In Next.js, the syntax export default HomePage is used instead of export function HomePage { //react components here } for a few reasons related to how the framework handles routing and file-based routing conventions:</p><ol><li>Routing: Next.js uses a app routing or file-based routing system where each file in the pages or app. With the pages router each file in the directory automatically becomes a route. App routing follows a slightly different approach. The app router is designed with React Server Components in mind. The default export from these files is treated as the component to be rendered for that route. By using export default, Next.js can automatically recognize and use the component without additional configuration.</li><li>Consistency and Convention: The export default syntax is a convention in Next.js that ensures consistency across the application. It simplifies the process of creating new pages and components because developers always know that the default export will be the main component for the page.</li><li>Named Exports for Additional Functions: Using export default for the main component allows you to use named exports for other functions, constants, or variables within the same file. This can be useful for exporting helper functions or configurations related to the page.</li><li>Framework Requirements: Some Next.js features, such as getStaticProps, getServerSideProps, and getInitialProps, are designed to work with default exports. These data-fetching methods expect the page component to be the default export to properly tie the data-fetching logic to the page.</li></ol><p>Here’s an example to illustrate:</p><pre>//pages/index.js<br>// This is the main component for the home page<br>function HomePage() {<br>  return &lt;div&gt;Welcome to the Home Page!&lt;/div&gt;;<br>}</pre><pre>// Default export of the main component<br>export default HomePage;</pre><pre>// Named export for a helper function<br>export function someHelperFunction() {<br>  // Helper function logic<br>}</pre><p>In contrast, if you used export function HomePage, Next.js wouldn&#39;t automatically recognize which component to render for the route, leading to potential routing issues and the need for additional configuration.</p><h3>Named and default exports in Vanilla JS</h3><p>In plain JavaScript, export default and export (used with functions or variables) are both part of the ES6 module system, but they serve different purposes and have distinct technical differences:</p><h4>Exporting Default vs. Named Exports</h4><ul><li>export default: There can be only one default export per module. The default export can be a function, class, object, or any other value. It allows importing this value with any name.</li><li>export (Named Exports): Named exports allow exporting multiple values from a module. Each exported value must be imported using the exact same name.</li></ul><h4>Syntax Differences</h4><p>Default Export</p><pre>// Exporting a function as default<br>export default function() {<br>  console.log(&#39;This is a default exported function&#39;);<br>}<br><br>// Exporting a class as default<br>export default class {<br>  constructor() {<br>    console.log(&#39;This is a default exported class&#39;);<br>  }<br>}</pre><p>Named Export</p><pre>// Exporting multiple named functions<br>export function myFunction1() {<br>  console.log(&#39;This is myFunction1&#39;);<br>}<br><br>export function myFunction2() {<br>  console.log(&#39;This is myFunction2&#39;);<br>}<br><br>// Or using a single export statement<br>export { myFunction1, myFunction2 };</pre><h4>Importing Differences</h4><p>Default Export</p><pre>// Importing a default export<br>import myFunction from &#39;./myModule&#39;; // Any name can be used for the default import<br>myFunction(); // Executes the default exported function</pre><p>Named Export</p><pre>// Importing named exports<br>import { myFunction1, myFunction2 } from &#39;./myModule&#39;;<br>myFunction1(); // Executes myFunction1<br>myFunction2(); // Executes myFunction2<br><br>// You can also rename during import<br>import { myFunction1 as func1 } from &#39;./myModule&#39;;<br>func1(); // Executes myFunction1</pre><h4>Re-Exports</h4><p>Default Export</p><pre>// Re-exporting a default export<br>import myDefaultFunction from &#39;./myModule&#39;;<br>export default myDefaultFunction;</pre><p>Named Export</p><pre>// Re-exporting named exports<br>export { myFunction1, myFunction2 } from &#39;./myModule&#39;;<br><br>// Or using a single export statement<br>import { myFunction1, myFunction2 } from &#39;./myModule&#39;;<br>export { myFunction1, myFunction2 };</pre><h4>Usability and Flexibility</h4><ul><li><em>Default Export</em>: Simplifies the export and import of a single main value from a module, especially useful when a module has one primary functionality or class.</li><li><em>Named Export</em>: Provides more flexibility by allowing multiple exports per module, each identified by name, suitable for modules that offer multiple utilities or components.</li></ul><p>In summary, the main technical difference lies in how each export type is declared, imported, and used. export default is designed for single, primary exports from a module, allowing flexible naming during import, whereas export (with named exports) supports exporting multiple named values from a module, requiring precise names during import.</p><p>A single JavaScript file cannot have more than one export default. The export default syntax is designed to specify a single primary export per module. This is a deliberate design choice in the ES6 module system to make it clear what the main export of the module is.</p><h3>Valid Example (One export default):</h3><pre>// myModule.js<br>// Default export<br>export default function mainFunction() {<br>  console.log(&#39;This is the main function&#39;);<br>}</pre><pre>// Named export<br>export function secondaryFunction() {<br>  console.log(&#39;This is the secondary function&#39;);<br>}</pre><h3>Invalid Example (More than one export default):</h3><pre>// myModule.js<br>// First default export<br>export default function mainFunction1() {<br>  console.log(&#39;This is the first main function&#39;);<br>}</pre><pre>// Second default export - this will cause a syntax error<br>export default function mainFunction2() {<br>  console.log(&#39;This is the second main function&#39;);<br>}</pre><p>Attempting to use more than one export default in a single file will result in a syntax error — SyntaxError: Only one default export allowed per module.</p><h3>Importing:</h3><p>If you have a file with one export default and several named exports, you can import them like this:</p><pre>// Importing from myModule.js<br>import mainFunction from &#39;./myModule&#39;; // Importing the default export<br>import { secondaryFunction } from &#39;./myModule&#39;; // Importing the named export<br><br>mainFunction(); // Output: This is the main function<br>secondaryFunction(); // Output: This is the secondary function</pre><p>The export default mechanism is useful for modules that have a single main responsibility, making it straightforward to import that main functionality. Named exports, on the other hand, allow you to export multiple values from a module and are imported using their exact names.</p><h4>Recap</h4><p>It is important to note the way Next.js uses named and default exports. In a Next.js app your routes use the default export — you cannot have named exports.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c6e12524b50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[30 Days of NextJS — Day 2: React Fundamentals]]></title>
            <link>https://medium.com/@fredrik_erasmus/30-days-of-nextjs-day-2-react-fundamentals-12c926165248?source=rss-32d514a8ab9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/12c926165248</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Fredrik Erasmus]]></dc:creator>
            <pubDate>Tue, 21 May 2024 06:02:06 GMT</pubDate>
            <atom:updated>2024-05-28T06:27:02.562Z</atom:updated>
            <content:encoded><![CDATA[<h3>30 Days of NextJS — Part 2: React Fundamentals</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_v0P7Ok7YIMYv6_1DF7ksw.png" /></figure><h3>Introduction</h3><p>In <a href="https://medium.com/@fredrik_erasmus/30-days-of-nextjs-part-1-basic-understanding-d6219e2ff270">my previous post</a> I discovered the difference between SSR as seen in the Node world versus more conventional approaches as seen with ASP.NET.</p><p>In this post I want to do some more exploring. Specifically, around building NextJS apps. NextJS is a full stack ReactJS framework for building web applications. I have been writing ReactJS code for about 16 months now. Prior to ReactJS I used Angular in many projects for many years. I used .NET almost exclusively for project work. .NET comes with its own sets of related technologies such as ASP.NET Core. To be honest I still have a lot to learn about ReactJS. I have a lot to learn about software development — I guess that is what keeps me going.</p><p>My goal here is to cover NextJS but also ReactJS — like learn about the inner workings of NextJS apps are built. But I also have a keen desire to become a better TypeScript and JavaScript dev.</p><p>In the following sections I will cover some ReactJS basics. The content I am referring comes directly from the <a href="https://nextjs.org/learn/react-foundations">NextJS website</a>. I find I learn best when I can explain something using my own words. My approach is to take my time working through content; often making my own notes. I find going through the process of doing things in a narrative style helps to keep it fresh in my mind for a while longer. We do tend to forget things fairly quickly. I have been reading through some of the learning content available on NextJS. I got to a point in going through the content with a lingering thought. I’m definitely not going to work through everything without writing some of my own code. You know when you whisk through some content, hoping some of it will stick? But if I want to have a longer-lasting and more fulfilling experience it might be better to take the time. I specifically thought about taking some of the examples shown in the learning content with my own adaptations. I think we often forget in learning about programming and code related topics to try and make it a personalized experience. And I’m not going to follow the exact steps in the section on NextJS called <a href="https://nextjs.org/learn/react-foundations/updating-ui-with-javascript">Updating UI with Javascript</a>. I will, however, follow the core concepts.</p><h3>The connection between NextJS and ReactJS</h3><p>The NextJS learning material covers some <a href="https://nextjs.org/learn/react-foundations/updating-ui-with-javascript">basic ReactJS</a>. Fundamentally speaking you cannot really use NextJS effectively without knowing ReactJS. So in the following sections I will be working through the ReactJS foundations as provided on the NextJS resource.</p><blockquote><em>React is a JavaScript library for building interactive user interfaces. By library, we mean React provides helpful functions (APIs) to build UI, but leaves it up to the developer where to use those functions in their application.</em></blockquote><p>What do we mean when we talk about libraries and frameworks? Sometimes developers use the term interchangeably — but for me they are different. A framework typically has a ton more features pre-built for you whereas a library such as ReactJS leaves a lot of features up to you. AngularJS provides routing out of the box whereas ReactJS does not, for instance. You can quite easily run a ReactJS app on a single server-side page without any other dependencies. You can, for instance, use an ASP.NET MVC Razor view with a script tag pointing to your ReactJS application. In such a scenario ReactJS is a library because you are effectively making use of server side routing. If, however, you do decide to use routing with ReactJS it becomes more of an SPA. With an SPA the routing is handled on the client-side by an additional ReactJS package. Routing is not included by default in a standard ReactJS app. You have to add an additional NPM package to make use of routing. Since the routing is handled client side the notion of distinct pages does not exist. You could in theory have your ReactJS running in an ASP.NET Core MVC razor view with client side routing. The notion of a “page” is really just ReactJS’s routing rendering different “views” of your app using the browser’s address bar. In many situations you have to configure your server side routing to let the client side routing take precedence otherwise you might end up with 404&#39;s.</p><p>An illustrative example can be seen in the diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*8rE-QDlL_pKb3Y1Z8Yb7Pw.png" /></figure><blockquote><em>By library, we mean React provides helpful functions (APIs) to build UI, but leaves it up to the developer where to use those functions in their application.</em></blockquote><p>One of the key features of ReactJS is its use of a virtual DOM. Going into the heavy details of how the Virtual DOM works is going to take up a lot of time, and typing. But basically the Virtual DOM is a JavaScript object that mimics the structure of the actual DOM. It is a virtual representation of the UI that React keeps in memory and syncs with the real DOM by applying minimal updates.</p><p>The Virtual DOM improves performance by minimizing the number of direct manipulations to the real DOM, which can be slow and resource intensive. Instead, ReactJS creates a lightweight copy of the actual DOM, allowing it to efficiently determine the minimal number of changes needed to keep the real DOM in sync.</p><blockquote><em>Part of React’s success is that it is relatively unopinionated about the other aspects of building applications. This has resulted in a flourishing ecosystem of third-party tools and solutions, including Next.js.</em></blockquote><blockquote><em>It also means, however, that building a complete React application from the ground up requires some effort. Developers need to spend time configuring tools and reinventing solutions for common application requirements.</em></blockquote><p>In many cases you might start out with a “simple” ReactJS app and you may not think you need additional features at first but as is typical with many software development projects you end up needing more than just “vanilla” ReactJS.</p><blockquote><em>Next.js is a React framework that gives you building blocks to create web applications.</em></blockquote><p>Its an interesting departure point to think of a full stack ReactJS app — it means you actually run JavaScript on the server as well, not just on the client.</p><blockquote><em>By framework, we mean Next.js handles the tooling and configuration needed for React, and provides additional structure, features, and optimizations for your application.</em></blockquote><p>I have seen many label NextJS as opinionated whereas ReactJS itself is less opinionated and allows you more freedom. Its not a bad thing but it is worth noting the way NextJS apps are built follows a particular way of building. Here is an attempted illustration using Markdown syntax.</p><blockquote><em>You can use React to build your UI, then incrementally adopt Next.js features to solve common application requirements such as routing, data fetching, and caching — all while improving the developer and end-user experience.</em></blockquote><p>Alluding to my point earlier about using ReactJS in the starting phase of your project and ultimately needing more than just the basics.</p><blockquote><em>Whether you’re an individual developer or part of a larger team, you can use React and Next.js to build fully interactive, highly dynamic, and performant web applications.</em></blockquote><p>I guess we will see!</p><h3>When you visit a page using your browser</h3><p>When you open a webpage, the content you view in the browser is rendered, but you don’t see the mechanics behind it. The server you connect to using the URL you type into the address bar returns markup (HTML). Your browser uses the DOM (Document Object Model) to translate the HTML sent by the server. The DOM consists of a tree-like structure where elements in the HTML are treated as objects.</p><p>ReactJS is a JavaScript library that allows you to interact with the objects in the DOM. It can manipulate the DOM by selecting, adding, updating, and deleting specific elements. Additionally, ReactJS can change the appearance of objects, such as colour and font-size.</p><p>ReactJS enhances the process by using a Virtual DOM, which is a lightweight copy of the actual DOM. When changes are made, ReactJS updates the Virtual DOM first and then efficiently applies the minimal set of changes to the actual DOM. This approach improves performance and provides a more seamless user experience.</p><h3>An example using Vanilla JS</h3><p>I’m following along with <a href="https://nextjs.org/learn/react-foundations/updating-ui-with-javascript">Updating UI with JavaScript</a>. For my own little exercise I am going to use Vite to create the project. You can check out <a href="https://github.com/thefremus/code-stack">the repo</a>.</p><blockquote><em>Vite (French word for “quick”, pronounced /vit/, like “veet”) is a build tool that aims to provide a faster and leaner development experience for modern web projects.</em></blockquote><p>With the following code you can see the HTML in the DOM is different to the HTML served up because it is being manipulated with JavaScript.</p><pre>&lt;div id=&quot;app&quot;&gt;&lt;/div&gt;<br>    &lt;script type=&quot;text/javascript&quot;&gt;<br>      const app = document.getElementById(&#39;app&#39;);<br>      const header = document.createElement(&#39;h1&#39;);<br> <br>      // Create a new text node for the H1 element<br>      const text = &#39;Develop. Preview. Ship.&#39;;<br>      const headerContent = document.createTextNode(text);<br> <br>      // Append the text to the H1 element<br>      header.appendChild(headerContent);<br> <br>      // Place the H1 element inside the div<br>      app.appendChild(header);      <br>    &lt;/script&gt;</pre><p>The code above is very verbose and in my mind is the main reason client side libraries like ReactJS exist today.</p><blockquote><em>As the size of an app or team grows, it can become increasingly challenging to build applications this way.</em></blockquote><blockquote><em>With this approach, developers spend a lot of time writing instructions to tell the computer how it should do things. But wouldn’t it be nice to describe what you want to show and let the computer figure out how to update the DOM?</em></blockquote><h3>Declarative programming vs imperative programming</h3><p>ReactJS is an example of declarative programming where you focus on what the UI should look like and less on how to achieve it. ReactJS uses a component-based approach to building your UI. When you create a piece of UI with ReactJS you encapsulate both the HTML and JavaScript in a single component like a button, for instance. ReactJS abstracts the manipulation of the DOM with the Virtual DOM. It takes over the role of manipulating the DOM — you can therefore focus on creating components (declarative) and not get bogged down specifying the behaviour of your DOM interactions. The end result is reduced complexity.</p><h3>Let’s do some ReactJS!</h3><p>In the tutorial <a href="https://nextjs.org/learn/react-foundations/getting-started-with-react">Getting Started with ReactJS</a> they use the hosted ReactJS libraries from a CDN. But again I am going to rather use Vite to create the basic ReactJS project for me.</p><p>I run the basic Vite command and follow the prompts. I’ll choose the TypeScript setup.</p><pre>npm create vite@latest</pre><p>I deleted the code in the App.tsx and added the following.</p><pre>function App() {<br>  return (<br>    &lt;h1&gt;<br>      Develop. Preview. Ship<br>    &lt;/h1&gt;<br>  )<br>}</pre><pre>export default App</pre><pre>ReactDOM.createRoot(document.getElementById(&#39;root&#39;)!).render(<br>  &lt;React.StrictMode&gt;<br>    &lt;App /&gt;<br>  &lt;/React.StrictMode&gt;,<br>)</pre><p>The code above uses something called JSX (JavaScript XML). JSX has become so prevalent across many frameworks — BunJS supports it out of the box for example. It provides an HTML-like syntax allowing you to embed JavaScript expressions within braces {}. Its specifically used within ReactJS to build components with the added benefit of being able to pass props. JSX is not valid JavaScript and requires a compiler like Babel.</p><p>With ReactJS and JSX you can declaratively build your UI without having to worry about direct DOM manipulation. It allows you to cut down on a lot of repetitive code.</p><h3>Building on some more foundations</h3><p>An interesting aspect to consider is state, as in application state within a ReactJS app. The UI acts as a piece of state — whenever there is a change in the state of your application ReactJS re-renders the UI. When building UI elements for a ReactJS app you create components. Components will invariably need some form of data to display — or props as they call it. The props or values in your component may change when a user clicks a button or enters information into a form. Understanding components, props and state are core concepts to ReactJS. Where it gets interesting with NextJS is the use of Server and Client components. But before we go there lets cover some additional ground. The whole idea behind ReactJS components is to think of your app as a set of LEGO bricks. The LEGO bricks are the components and when you combine them they form a bigger structure. Each piece of UI is self-contained and can be updated at the component level. The concept of having your UI split into modular components means being able to update or deleting components without affecting the entire application. It makes sense but in practice getting your code modular enough to not affect the entire application takes practice.</p><p>ReactJS components are JavaScript functions that return UI elements (using JSX). Let’s say your ReactJS app consists of a header. Here I am using TypeScript to define an interface.</p><pre>interface HeaderProps {<br>    title: string;<br>}</pre><pre>export const Header = ({title}: HeaderProps) =&gt; {<br>    return (<br>        &lt;h1&gt;<br>        {title}<br>        &lt;/h1&gt;<br>    )<br>}</pre><p>In the NextJS learning material they create a header component and pass it to ReactJS’s render method. In my adaptation I am going to add the header component to the App.tsx.</p><pre>import &#39;./App.css&#39;<br>import { Header } from &#39;./Header&#39;</pre><pre>function App() {<br>  return (<br>    &lt;Header title=&quot;Develop. Preview. Ship&quot; /&gt;<br>  )<br>}</pre><pre>export default App</pre><p>An important point to remember at this point is that all ReactJS component names must be capitalized to distinguish them from plain HTML and JavaScript. For instance &lt;div&gt;&lt;/div&gt; is a standard HTML tag. Custom components have a capitalized first letter.</p><p>Lets contrive the example a bit further. Lets say your page consist of a header, sidebar, and a footer.</p><pre>export interface AppProps {<br>  headerTitle?: string;<br>  menuItems?: string[];<br>  footerContent?: {<br>    company?: string;<br>    year?: number;<br>  };<br>}</pre><pre>function App() {<br>  const [appProps, setApprops] = useState&lt;AppProps&gt;({<br>    headerTitle: &quot;Develop. Preview. Ship&quot;,<br>    menuItems: [&quot;Home&quot;, &quot;Services&quot;, &quot;About&quot;, &quot;Contact us&quot;],<br>    footerContent: {<br>      company: &quot;React App&quot;,<br>      year: 2024,<br>    }<br>  });<br>  const buttonClick = () =&gt; {<br>    const incrementedYear = appProps.footerContent?.year ? appProps.footerContent.year + 1 : 0;<br>    const currentApprops = {...appProps, footerContent: {...appProps.footerContent, year: incrementedYear}};<br>    setApprops(currentApprops);    <br>  }<br>  return (<br>    &lt;&gt;<br>    &lt;Header headerTitle={appProps.headerTitle} /&gt;<br>    &lt;Sidebar menuItems={appProps.menuItems} /&gt;<br>    &lt;Footer footerContent={appProps.footerContent} /&gt;<br>    &lt;button onClick={() =&gt; buttonClick()}&gt;Increase the year&lt;/button&gt;<br>    &lt;/&gt;<br>  )<br>}</pre><pre>export default App</pre><pre>export const Sidebar = ({menuItems}:AppProps) =&gt; {<br>    return(<br>        &lt;div&gt;<br>            &lt;ul&gt;<br>                {menuItems?.map((item, index) =&gt; (<br>                    &lt;li key={index}&gt;{item}&lt;/li&gt;<br>                ))}<br>            &lt;/ul&gt;<br>        &lt;/div&gt;<br>    )<br>}</pre><pre>export const Header = ({headerTitle}: AppProps) =&gt; {<br>    return (<br>        &lt;h1&gt;<br>        {headerTitle}<br>        &lt;/h1&gt;<br>    )<br>}</pre><pre>export const Footer = ({footerContent}:AppProps) =&gt; {<br>    return (<br>        &lt;div&gt;<br>            &lt;p&gt;<br>                &amp;copy; {footerContent?.year} {footerContent?.company}<br>            &lt;/p&gt;<br>        &lt;/div&gt;<br>    )<br>}</pre><p>The code highlights several key aspects related to ReactJS foundations. First the notion of nested components. The Sidebar, Header and Footer are nested in the App component. In the App component I initialize some arbitrary AppProps and pass it down to the nested components. Each of the components then use the AppProps to display certain pieces of information. I also added a button which when clicked increments the year to illustrate the use of state.</p><h3>Closing remarks</h3><p>I covered some ReactJS foundations in particular looking at the key difference between a declarative and imperative approach to developing user interfaces (UIs). I also did some very basic ReactJS to illustrate the use of props as its a building block for creating components in conjunction with state. I put the code from the basic examples <a href="https://github.com/thefremus/code-stack/tree/main/basic-react">on GitHub</a>. Covering the foundations leads onto my continued journey with NextJS! Lets see what comes next!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12c926165248" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[30 Days of NextJS — Part 1: Basic Understanding]]></title>
            <link>https://medium.com/@fredrik_erasmus/30-days-of-nextjs-part-1-basic-understanding-d6219e2ff270?source=rss-32d514a8ab9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6219e2ff270</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Fredrik Erasmus]]></dc:creator>
            <pubDate>Mon, 11 Mar 2024 06:02:12 GMT</pubDate>
            <atom:updated>2024-05-20T13:31:30.401Z</atom:updated>
            <content:encoded><![CDATA[<h3>30 Days of NextJS — Part 1: Basic Understanding</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_v0P7Ok7YIMYv6_1DF7ksw.png" /></figure><h3>Introduction</h3><p>ReactJS 19 is coming. React Server Components (RSC) remains one of the most anticipated (or not) features. ReactJS is becoming a fullstack framework — targeting both server-side and client side. Reading through the ReactJS document, specifically the part from <a href="https://react.dev/learn/start-a-new-react-project#which-features-make-up-the-react-teams-full-stack-architecture-vision">Which features make up the React team’s full-stack architecture vision?</a>.</p><blockquote><em>Next.js’s App Router bundler fully implements the official React Server Components specification. This lets you mix build-time, server-only, and interactive components in a single React tree.</em></blockquote><p>Its worth noting NextJS uses two “different types” of routing — page routing and app routing. Page routing targets Server Side Rendering (SSR) whereas app routing uses React Server Components.</p><p>But what does it all mean if you come from “conventional approaches” to building web applications. In my mind one of the most conventional ways to build ReactJS apps is to use a web framework that loads ReactJS as a script inside your rendered HTML. Once the HTML has rendered ReactJS along with your code will be loaded by the browser. Your ReactJS code might then do other things like do HTTP calls to fetch data.</p><p>Next.js’s SSR renders components to HTML strings on the server using renderToString() and sends them to the client. The client then hydrates the HTML with the same data and state as the server. This requires that the server and the client have the same data and code to render the same components. Next.js’s SSR is faster than client-side rendering for the initial page load, but it also increases the client bundle size and the server load. Next.js’s SSR is the default mode for pages that use getServerSideProps or getInitialProps.</p><h3>How does Server Side Rendering (SSR) differ from “conventional” approaches?</h3><p>You might or might not have heard someone say — “but we already use server side rendering”. Generally the reference is to how conventional web frameworks render content. Using Express JS as an example — a client application such as a web browser would connect to a route rendering an HTML view. The web framework would process the incoming request, sending back the HTML response. The request/response pattern is a very common one not just for web frameworks; sometimes backend applications log requests and responses between applications. Web frameworks such as ExpressJS can also respond to requests with many different response types such as HTML or JSON. With HTML responses the web framework would render the markup using a view engine on the server before sending it back to the client. In many cases the HTML will include renferences to JavaScript. In many cases the JavaScript will have to code to perform AJAX requests using GET/POST verbs. Its important to understand that if the HTML is rendered with a single request by the web framework the JavaScript is only loaded after the HTML is returned to the browser. Once the scripts are loaded it will perform additional HTTP requests.</p><p>I have a basic diagram to illustrate the process of rendering the HTML response from an ExpressJS request, or any other web framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*85yZ0DjRrHUUQAA5n_QtJA.png" /></figure><ol><li>Initial Page Request</li><li>The client sends an HTTP GET request to the server for a specific page.</li><li>The server handles the route, queries the database for necessary data, and renders the HTML including the JavaScript.</li><li>The server responds to the client with the HTML page that includes the JavaScript function.</li><li>JavaScript Execution &amp; API Call:</li><li>The browser renders the HTML and executes the JavaScript function included in the page on load.</li><li>The JavaScript function then makes an API call to the Express server (e.g., to /api/data).</li><li>The server handles the API request, queries the database for the data needed by the API, and responds with the data.</li><li>Dynamic Page Update:</li><li>The JavaScript function receives the API response and processes the data.</li><li>The client’s page is updated dynamically based on the API response data, without needing to refresh the page.</li></ol><h3>How does SSR work?</h3><p>In contrast NextJS (or frameworks using SSR) use JavaScript runtimes to execute code on the server. NodeJS is the most prevalent runtime with others like Deno or BunJS also being able to run JavaScript on the server. Since runtimes use JavaScript on the server they utilize something known as “Universal JavaScript” or “Isomorphic JavaScript”. It means the same code can run on the server and in the browser. ReactJS components can then be rendered on the server before sending the HTML to the client.</p><p>A basic diagram of the process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*bCrvcmJ7bqnFm4WXIBNI9g.png" /></figure><p>A basic overview of the steps:</p><ol><li>On the server: Next.js runs your React components to generate HTML. It also prepares the initial state based on any data fetched during this phase. Next.js provide specific hooks or functions such as getServerSideProps (for Next.js) that run on the server before the page is rendered. These functions can perform any operations needed to fetch data, such as calling a database, accessing a REST API, or performing file operations. The data returned by these functions is then passed as props to your React components, which can use this data to render the initial HTML.</li><li>On the client: The browser receives the HTML and displays the page. after the server-side rendered HTML is sent to the client and displayed by the browser, the JavaScript bundle for the Next.js application (which includes ReactJS among other client-side libraries and application code) is being loaded by the browser in the background.</li><li>Hydration: Once the JavaScript bundle is loaded, Next.js “hydrates” the static HTML, attaching event listeners and enabling the full interactive experience of a React application. During hydration, React “rehydrates” the static content by attaching event listeners to the DOM elements, thereby enabling interactive features such as clicks, form submissions, and any other user interactions that your components are designed to handle. This process effectively turns the static server-rendered HTML into a fully interactive React application in the client’s browser.</li></ol><h3>What are the benefits of SSR?</h3><p>One of the more conventional ways of writing ReactJS would have been to include all the required client side scripts in one or more &lt;script&gt; tags in your web framework&#39;s view engine HTML. The client side code would have been bundled into one or more minified JavaScript files referenced in the HTML. The bundled JavaScript code would also include your custom ReactJS components. When your HTML containing the scripts has finished loading the scripts will need to be loaded or initialized as well. In contrast Server Side Rendering presents the user with a fully formed HTML page without the need to wait for client side scripts to load. The fully formed HTML page makes for better SEO (Search Engine Optimization). Traditionally speaking Single Page Apps (SPA) were terrible for SEO because the content only loaded after the HTML page loaded. Search engine crawlers effectively saw no content. With SSR the content is available. Once the initial page is loaded NextJS starts the hydration process. Hydration is the process where React takes over the static content and turns it into a fully interactive web application in the browser. During hydration, React attaches event listeners to the DOM elements and reconciles the static content with the React components in the JavaScript bundle. This process transforms the static page into a dynamic SPA (Single Page Application) that can handle user interactions, fetch data dynamically, and navigate between pages without reloading. Hydration offers several benefits.</p><ol><li>Seamless User Experience: By starting with server-rendered HTML and then enhancing that with client-side interactivity, Next.js applications can offer a smooth, app-like experience. Users can start interacting with the page even before the JavaScript has fully kicked in, and once hydration is complete, they get the full dynamic capabilities of a React application.</li><li>Performance Optimization: Since the initial view of the page doesn’t rely on JavaScript execution, the perceived performance is significantly improved. Additionally, because the same React components are used on the server and the client, React can efficiently attach event handlers and update the components without needing to redo the initial render.</li><li>Unified Development Model: Developers can write components and logic that work on both the server and the client, simplifying the development process and reducing the need for duplicative code. This isomorphic approach also allows for optimizations like code splitting and lazy loading to be handled more effectively, further improving performance.</li></ol><h3>React Server Components (RSC)</h3><p>NextJS’s app router is built using React Server Components (RSC). I’ll be honest I initially thought RSC and SSR were related but its not quite the same. If you read about <a href="https://nextjs.org/docs/app/building-your-application/routing">routes on NextJS</a> you will notice a key point.</p><blockquote><em>In version 13, Next.js introduced a new App Router built on React Server Components, which supports shared layouts, nested routing, loading states, error handling, and more.</em></blockquote><p>The details around NextJS’s app router and React Server Components are explained <a href="https://nextjs.org/docs/app/building-your-application/rendering/server-components">here</a>. I will uncover the React Server Components rendering in the next post.</p><h3>Final thoughts</h3><p>I have set myself a goal of trying to write NextJS code for the next 30 days. My first day was spent covering the basics of SSR comparing it with conventional approaches. In the days that are coming I am going to delve deeper into NextJS. It is important to write code as well though. I don’t want to fall into the trap of doing too much “fake learning”.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6219e2ff270" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up WSL with VSCode running Bun]]></title>
            <link>https://medium.com/@fredrik_erasmus/setting-up-wsl-with-vscode-running-bun-182436f2b8b2?source=rss-32d514a8ab9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/182436f2b8b2</guid>
            <category><![CDATA[wsl-2]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[bunjs]]></category>
            <category><![CDATA[vscode]]></category>
            <dc:creator><![CDATA[Fredrik Erasmus]]></dc:creator>
            <pubDate>Thu, 08 Feb 2024 08:51:36 GMT</pubDate>
            <atom:updated>2024-02-08T08:51:36.511Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GOb6TiMeqV6UOurMGI3rcw.png" /></figure><h3>Background — BunJS</h3><p>I have been reading and watching a lot about JavaScript frameworks (client and serverside) the last while. I have no specific reason for doing so — I simply want to be better at JavaScript. One of the more interesting parts so far has been the development of <a href="https://bun.sh/">BunJS</a>. Bun is a JavaScript runtime. You can think of it as an alternative to NodeJS, or as the creators call it a drop-in replacement.</p><p>The <a href="https://bun.sh/docs">BunJS docs</a> provide a great intro.</p><blockquote><em>At its core is the Bun runtime, a fast JavaScript runtime designed as a drop-in replacement for Node.js. It’s written in Zig and powered by JavaScriptCore under the hood, dramatically reducing startup times and memory usage.</em></blockquote><p><a href="https://ziglang.org/">Zig</a> is a general purpose programming language comparable to Rust. I’m not going to be looking at Zig or Rust, its just good general knowledge.</p><blockquote><em>​​The bun​ command-line tool also implements a test runner, script runner, and Node.js-compatible package manager, all significantly faster than existing tools and usable in existing Node.js projects with little to no changes necessary.</em></blockquote><p>The NodeJS ecosystem, specifically NPM, has in my mind always been something of a dark place. From security issues due to dependencies to performance related issues; the NodeJS ecosystem has its issues. BunJS is interesting because it is faster at running JavaScript applications compared to NodeJS. Coming from the ASP.NET Core world performance is already baked in to the .NET Core runtime. I would dare to say .NET Core is significantly faster than NodeJS. Performance is not always the number one requirement for using or experiencing frameworks but it does sit in the back of my mind at times. If I am being honest though framework performance would probably not make much of a difference in my world. The code I write will never need the scale of performance needed by apps serving millions of users per day. Focusing on performance is not really that important to me. My main goal here is to become the best JavaScript/TypeScript programmer I can be. I really don’t want to be tied to .NET forever.</p><blockquote><em>JavaScript (or, more formally, ECMAScript) is just a specification for a programming language. Anyone can write a JavaScript engine that ingests a valid JavaScript program and executes it. The two most popular engines in use today are V8 (developed by Google) and JavaScriptCore (developed by Apple). Both are open source.</em></blockquote><p>The key difference between NodeJS and BunJS in my mind is the browsers they target. As far as I know V8 is used in Chrome; or any Chrome-based browser. JavaScriptCore is the engine used in browsers running on iOS and MacOS. Lets also state a fact — the runtimes found in BunJS or NodeJS basically run the engines used in the browser on the server. NodeJS can run most JavaScript used in a browser.</p><blockquote><em>Browsers — Notably, browsers ship with JavaScript runtimes that implement a set of Web-specific APIs that are exposed via the global window object. Any JavaScript code executed by the browser can use these APIs to implement interactive or dynamic behavior in the context of the current webpage.</em></blockquote><p>Something I have noted recently is how fullstack JavaScript frameworks like NextJS, Nuxt etc have a way to detect when a piece of JavaScript code is executable on the server. For instance, a click event for a button might work in the browser but it makes little to no sense on the server.</p><blockquote><em>Similarly, Node.js is a JavaScript runtime that can be used in non-browser environments, like servers. JavaScript programs executed by Node.js have access to a set of Node.js-specific globals like Buffer, process, and __dirname in addition to built-in modules for performing OS-level tasks like reading/writing files (node:fs) and networking (node:net, node:http). Node.js also implements a CommonJS-based module system and resolution algorithm that pre-dates JavaScript’s native module system. Bun is designed as a faster, leaner, more modern replacement for Node.js.</em></blockquote><p>Some interesting points on the design goals of BunJS.</p><blockquote><em>Bun is designed from the ground-up with today’s JavaScript ecosystem in mind. Speed. Bun processes start 4x faster than Node.js TypeScript &amp; JSX support. You can directly execute .jsx, .ts, and .tsx files; Bun’s transpiler converts these to vanilla JavaScript before execution. Web-standard APIs. Bun implements standard Web APIs like fetch, WebSocket, and ReadableStream. Bun is powered by the JavaScriptCore engine, which is developed by Apple for Safari, so some APIs like Headers and URL directly use Safari’s implementation. Node.js compatibility. In addition to supporting Node-style module resolution, Bun aims for full compatibility with built-in Node.js globals (process, Buffer) and modules (path, fs, http, etc.) This is an ongoing effort that is not complete. Refer to the compatibility page for the current status.</em></blockquote><blockquote><em>Bun is more than a runtime. The long-term goal is to be a cohesive, infrastructural toolkit for building apps with JavaScript/TypeScript, including a package manager, transpiler, bundler, script runner, test runner, and more.</em></blockquote><h3>Why BunJS?</h3><p>I mean there is NodeJS — why the extra effort to work with BunJS? Well one of the key selling points is its support for TypeScript without any ceremony. When using NodeJS you have to perform some sort of ceremony to get TypeScript working. A tool such a Vite makes it easier to use TypeScript in your project. Another question could be whether to use TypeScript or not — but lets just say for the time being I’ll be using TypeScript.</p><p>Using BunJS works better on Linux and macOS — the Windows installation is not guaranteed to be stable as stated on the <a href="https://bun.sh/docs/installation">installation guide</a>. So it let me down the path of installing WSL (Windows Subsystem for Linux), specifically <a href="https://learn.microsoft.com/en-us/windows/wsl/tutorials/wsl-vscode">Get started using Visual Studio Code with Windows Subsystem for Linux</a>.</p><h3>WSL meets VSCode</h3><p>From the documentation</p><blockquote><em>Visual Studio Code, along with the WSL extension, enables you to use WSL as your full-time development environment directly from VS Code. You can: develop in a Linux-based environment use Linux-specific toolchains and utilities run and debug your Linux-based applications from the comfort of Windows while maintaining access to productivity tools like Outlook and Office use the VS Code built-in terminal to run your Linux distribution of choice take advantage of VS Code features like Intellisense code completion, linting, debug support, code snippets, and unit testing easily manage your version control with VS Code’s built-in Git support run commands and VS Code extensions directly on your WSL projects edit files in your Linux or mounted Windows filesystem (for example /mnt/c) without worrying about pathing issues, binary compatibility, or other cross-OS challenges</em></blockquote><p>The installation guid for BunJS also recommends using WSL. It would also be great to use VSCode to write JavaScript / TypeScript, transpiled by BunJS.</p><h3>Installing WSL</h3><p>The first step would be to install WSL — <a href="https://learn.microsoft.com/en-us/windows/wsl/install">How to install Linux on Windows with WSL</a>. In the past I used Microsoft Store to install WSL but using a powershell command is great — wsl --install. So you should see something similar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*ZPLUinfQmjqcojNtvTaPpA.png" /></figure><p>By default Ubuntu is installed. I restarted my machine; Windows installed WSL without any further interactions from my side. After seeing the Bash shell the next step would be to get VSCode working with WSL. One of the main goals is to get BunJS running using WSL and VSCode — my expectations are to have some code running in VSCode with the Bun runtime picking up changes as they are made. For the purposes of my JavaScript/TypeScript journey I am going to create a project Code Journal.</p><p>The next step would be to install the <a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.vscode-remote-extensionpack">WSL extensions pack</a>. After installing the extension I noticed immediately the addition of UI elements to VSCode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*FDXD01oV8EbUZX4bFyKxgA.png" /></figure><p>I clicked on the WSL targets to see what happened and it appeared to work. I also noted in the <a href="https://learn.microsoft.com/en-us/windows/wsl/tutorials/wsl-vscode">documentation</a> you can run code . from the bash terminal. I have been using Windows Terminal for quite some time now; typing code . is such a great way to open code in VSCode. The first thing I noted is a message appearing in VSCode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*IpaW_AXujRRF-9ySuUIKQQ.png" /></figure><p>When I ran the code . command I ran it from a folder I created so it was not quite happy with it. It means I have to create a folder mounted on the Linux file system root directory. I created a folder in my /home directory after which VSCode seemed happy.</p><p>Lets install Bun!</p><h3>Installing Bun</h3><p>From the <a href="https://bun.sh/docs/installation">installation guide</a> on the Bun website you can run the same bash commands used for Linux on WSL.</p><p>curl -fsSL https://bun.sh/install | bash</p><p>After running the command I encountered after not reading the documentation properly related to a dependency on unzip.</p><p>error: unzip is required to install bun (see: <a href="https://bun.sh/docs/installation#macos-and-linux)">https://bun.sh/docs/installation#macos-and-linux)</a></p><p>If I took a few moments to read the documentation it quite clearly states you need to install unzip.</p><blockquote><em>Linux users — The unzip package is required to install Bun. Use sudo apt install unzip to install unzip package. Kernel version 5.6 or higher is strongly recommended, but the minimum is 5.1. Use uname -r to check Kernel version.</em></blockquote><p>After installing unzip I was able to install Bun. Now we need to run it!</p><h3>Running Bun</h3><p>Running Bun with the VSCode WSL extension works really well! I followed the <a href="https://bun.sh/docs/quickstart">Quickstart</a> to create a simple web server. I edited code in VSCode running on Windows — after each update to the code I ran bun run start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*-9NP0BPGLvOK0ATMHcRt6Q.png" /></figure><p>Interesting to note -</p><blockquote><em>⚡️ Performance — bun run is roughly 28x faster than npm run (6ms vs 170ms of overhead).</em></blockquote><h3>Next steps</h3><p>If you look at the <a href="https://bun.sh/guides">Guides</a> several interesting bits are listed under the EcoSystem.</p><ul><li>Use React and JSX</li><li>Use EdgeDB with Bun</li><li>Use Prisma with Bun</li><li>Create a Discord bot</li><li>Use Drizzle ORM with Bun</li><li>Run Bun as a daemon with PM2</li><li>Build an app with Nuxt and Bun</li><li>Build an app with Qwik and Bun</li><li>Build an app with Astro and Bun</li><li>Build an app with Remix and Bun</li><li>Run Bun as a daemon with systemd</li><li>Build an app with Next.js and Bun</li><li>Build an app with SvelteKit and Bun</li><li>Build a frontend using Vite and Bun</li><li>Build an app with SolidStart and Bun</li><li>Build an HTTP server using Hono and Bun</li><li>Build an HTTP server using Elysia and Bun</li><li>Containerize a Bun application with Docker</li><li>Build an HTTP server using Express and Bun</li><li>Server-side render (SSR) a React component</li><li>Build an HTTP server using StricJS and Bun</li><li>Read and write data to MongoDB using Mongoose and Bun</li></ul><p>The next steps would be to experiment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=182436f2b8b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[So I recently took it upon myself to use anything but .NET]]></title>
            <link>https://medium.com/@fredrik_erasmus/so-i-recently-took-it-upon-myself-to-use-anything-but-net-b92c18823748?source=rss-32d514a8ab9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b92c18823748</guid>
            <category><![CDATA[personal-growth]]></category>
            <dc:creator><![CDATA[Fredrik Erasmus]]></dc:creator>
            <pubDate>Thu, 17 Aug 2023 07:54:19 GMT</pubDate>
            <atom:updated>2023-08-17T07:54:19.056Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why does .NET feel safe?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DsiIytifLIkwJlrh_4H3iQ.png" /></figure><p>So I recently took it upon myself to use anything but .NET for side projects. Why though? .NET is great — especially ASP.NET Core being cross platform. You no longer have the excuse of not being able to run ASP.NET on Windows servers. The entire .NET ecosystem is great — even though it also has its own fair share of drama if you follow #dotnetdrama. But I wonder sometimes if the drama is really unique to the .NET world. Getting back to the point at hand — why does .NET feel safe and “comfortable”?</p><h3>The ecosystem</h3><p>For starters Visual Studio (not VS Code) makes it really easy to get started. It provides project templates for the most common .NET projects — like ASP.NET Core, Blazor, .NET MAUI, etc. It is worth noting that the .NET Core SDK also provides templates. You can use the .NET Core CLI to generate projects from templates. Visual Studio therefore makes it very easy to get started. And my guess is that Visual Studio is a big reason why .NET feels safe to me. If you have a new project idea it is easy to simply launch a new Visual Studio instance, select a project template and off you go. Visual Studio also provides an excellent development experience. I guess the question in my mind becomes whether or not an IDE such as Visual Studio shields you away from the nuts and bolts underneath it all. The point though is that Visual Studio makes it too easy perhaps? In the past I have found myself falling back to using .NET for little side-projects because it was all I knew. Maybe the familiarity of a technology such as .NET makes it comfortable and safe. You know exactly how things work — you have an expectation of how they are put together. But I do find having used C# for many years now the code always seems to go in a similar vain. The typical patterns of object oriented programming are, dare I say it, repeated again and again. The downside of the .NET way of doing things is the constant same old familiarity — create some classes, add some DI here and there, use this pattern, etc. Note — C# is a constantly evolving language. The .NET ecosystem is also constantly adding new features, improving security and performance, etc. Having a Microsoft-backed product such as .NET is invaluable and does provide solution architects and technology professionals with a certain degree of confidence. For instance, Azure App Services upgrade .NET Core continuously. Its a great developer ecosystem.</p><h3>A different perspective</h3><p>Having thought of all these things I would not imagine using Visual Studio Professional for ReactJS apps. VSCode seems to work better for some reason — it might be the myriad of plugins or the lightweight feel to it. The experience of developing ReactJS apps in VSCode feels a lot different. It also feels weird using Visual Studio for ExpressJS apps — not sure why. It does feel like you have to “figure things out” a bit more when you say write NodeJS apps. Or maybe its just a lack of familiarity from my side using ExpressJS giving off the appearance. I get the impression people favouring .NET over other technologies appear to despise NodeJS — it could the package management (NPM vs Nuget) experience? All I know is experiencing multiple approaches to similar problems will give you a broader insight. So, for instance, how would you do things differently if you were to develop an ASP.NET Core API alongside an ExpressJS API? How would you do things like validation? In the ASP.NET Core world you would use attributes on class properties. The same approach is not applicable in ExpressJS. But again why would you leave the comfy world of .NET where everything is mostly given to you.</p><h3>Some reasons why .NET may seem “safe”.</h3><ol><li><em>Enterprise Adoption:</em> Many large enterprises rely on .NET for their mission-critical applications. It has a long history of stability and support from Microsoft.</li><li><em>Rich Framework:</em> .NET provides a comprehensive framework that caters to various development needs, from web applications to desktop software and mobile apps.</li><li><em>Strong Performance:</em> With the introduction of .NET Core, performance has been a significant focus, making .NET one of the top-performing backend technologies.</li><li><em>Cross-Platform:</em> With .NET Core and its successors, you can build cross-platform applications, making the technology even more versatile.</li><li><em>Support &amp; Longevity:</em> Backed by Microsoft, .NET has robust support, regular updates, and a vast community, ensuring its longevity and relevance in the industry.</li></ol><p>If you have worked in formal corporate environments it does not come as a surprise how .NET almost always is adopted in the enterprise. Its not difficult to see why. In the same breath learning something like NodeJS also provides benefits.</p><h3>Why would you want to diversify your skill set with something like NodeJS?</h3><ol><li><em>Diverse Skillset:</em> Adding Node.js to your skill set makes you a more versatile developer. Understanding different ecosystems helps you to approach problems from various perspectives and gives you more tools to tackle different challenges.</li><li><em>Performance Characteristics:</em> Node.js is known for its non-blocking, event-driven architecture which can be particularly effective for handling numerous simultaneous connections with high throughput. This makes it ideal for building scalable network applications.</li><li><em>JavaScript Everywhere:</em> With Node.js, you’re using JavaScript on both the client-side and server-side. This can lead to more consistent and efficient development, especially if you’re building full-stack applications.</li><li><em>Expanding Opportunities:</em> Many startups and modern web applications prefer the MERN (MongoDB, Express.js, React, Node.js) stack or variations of it. By learning Node.js, you can tap into a new ecosystem and increase your job prospects.</li><li><em>Active Community &amp; Libraries:</em> Node.js has a thriving community, which has led to a plethora of available packages and tools. NPM, the Node.js package manager, is a rich ecosystem of open-source libraries.</li><li><em>Microservices:</em> Node.js is commonly used in microservice architectures. If you’re looking to explore or implement microservices, Node.js could be an excellent platform to use.</li><li><em>Learning Experience:</em> Every time you learn a new programming paradigm or environment, you strengthen your problem-solving skills and improve as a developer.</li><li><em>Modern Web Development:</em> Node.js is at the heart of modern development practices, tools, and frameworks. Understanding it can give you insights into current web development trends.</li></ol><h3>At the end of the day its about loving technology</h3><p>In the last 3–4 months most of my reading on Medium has focused on ReactJS — I tend to not read about .NET often. Its not a slight against .NET. I love technology — I enjoy using technology to solve problems regardless of its flavour. But I do feel for my own personal growth staying in one space, like .NET, would be severely limiting. Its not about professional ambition — its really just about growing as a technology professional. .NET is an example — but I think you can apply it to any other framework or technology platform.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b92c18823748" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A small journey using ChatGPT and MidJourney]]></title>
            <link>https://medium.com/@fredrik_erasmus/a-small-journey-using-chatgpt-and-midjourney-d34106eaebef?source=rss-32d514a8ab9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d34106eaebef</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[midjourney]]></category>
            <dc:creator><![CDATA[Fredrik Erasmus]]></dc:creator>
            <pubDate>Fri, 05 May 2023 12:04:42 GMT</pubDate>
            <atom:updated>2023-05-05T12:04:42.473Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6p4q8fLX2hSlQcg63Tmqjw.png" /></figure><h3>Life as a canvas of potential</h3><p>In the last while — I would say since the end of March 2023 — I started exploring the world of ChatGPT. I am no expert prompt writer but I have become accustomed to the style used to write prompts. ChatGPT thrives on a lot of detailed contextual information, versus shorter prompts with less detailed information. The style suits me because I can immerse myself in it. The way I approach writing prompts is simple — you have an idea in your mind. Getting there will take several attempts. You refine the prompts by starting with something a bit less specific. After several prompts you become more specific, framing the prompts in a manner to get to the results you desire. With enough persistence though you eventually start forming a better and clearer picture of what you wanted. Context is always important, as much as in life, as its uses in ChatGPT.</p><p>Not to be overly philosophical — but one thing I have realised in the last couple of years is nothing worthwhile comes without maintenance. I think sometimes, we as humans, fall into the trap of thinking when you do something as a once off its enough. Its never enough really. A practical example — maintaining a house is one of the most exhausting, and at times painful (not physically) things. The on-going maintenance never stops — the house needs constant attention. The grass will not stop growing after you cut it — you have to routinely cut it, otherwise it becomes a nightmare. Maintaining your house does come with a benefit — you and your family get to live in it. You reap the benefit of living in a house, you get the safety, but you have to constantly maintain it. The parallel between life in is the need for constant maintenance — or the understanding that most things are continuous. Understanding that consistent efforts over time have an exponential effect is very important. Whilst habits are often small in their execution in the present moment they add up over time to bear results.</p><p>Using any technology requires dedication and persistence (maintenance) — results are not magical. Not even with something like ChatGPT. You have to be persistent — be willing to seek progress everyday. If we are persistent enough the results will come eventually. The best prompt experience from ChatGPT comes from using it regularly to understand and maximize its value.</p><p>In the same period I started using ChatGPT I also started with Midjourney. The part I enjoy the most about MidJourney is the mixing and matching of prompts, not knowing what the result will be. I’m not an artist or graphic designer but I do enjoy the process of playing around with the Midjourney prompts. I had a moment and tried to combine the results I got from MidJourney with something I learned from ChatGPT. The idea — to create a very basic HTML template with a theme using the image from MidJourney as a basis. I also ended up using the TailWind CSS library — it was a great learning experience.</p><h3>Using MidJourney as a starting point</h3><p>The idea was simple enough — I wanted to create a header image for an HTML page. I also wanted to use the colours from the generated image as the basis for a theme. Initially, however, I did not intend to use TailWind — I tried winging it with vanilla HTML and CSS but soon realised using a framework for basic things like layouts was going to make my life easier.</p><p>The image I used was generated using MidJourney’s /imagine prompt. I find it quite interesting that MidJourney’s prompts will generate different images even if the command is identical. You can try the prompt below to see what your results are.</p><blockquote><em>Envision a captivating website background or header that embodies the essence of InfiniteCanvas while incorporating the unique elements of digital binary barcode data paper, cryptopunk vector dot matrix art, vibrant colors, metallic gradients, 3D design, intricate detail, algorithmic symmetry, and cinematic lighting. Picture a futuristic landscape where the fluidity of artistic expression converges with the precision of technology. In the foreground, a striking abstract canvas features a dynamic fusion of cryptopunk-inspired vector dot matrix patterns and barcode-like binary data elements. This cutting-edge design is further enhanced by vibrant colors, metallic gradients, and a highly detailed 3D aesthetic that adds depth and dimension to the composition. The landscape is brought to life through algorithmic symmetry, creating an enchanting sense of order amidst the visual complexity. Cinematic lighting casts a soft, ethereal glow across the scene, illuminating the intricate interplay of colors and forms while highlighting the seamless integration of art and technology. — v 5 — ar 16:9</em></blockquote><p>I really like the image MidJourney generated. Its the image I used at the top of the post.</p><p>How can I create a theme with the colors used in the image? Well I would need to extract the colors in some way. I used ChatGPT to generate JavaScript code to extract the colors for the image. Initially it gave me Python code — I know it is a very popular programming language but for my purposes I wanted JavaScript. ChatGPT suggested two npm packages, sharp and skmeans. It then generated the following code.</p><pre>const sharp = require(&#39;sharp&#39;);<br>const skmeans = require(&#39;skmeans&#39;);<br><br>async function extractColors(imagePath, numColors = 5) {<br>  try {<br>    // Read and resize image<br>    const image = await sharp(imagePath).resize({ width: 100 }).raw().toBuffer();<br>    // Convert image data to an array of RGB values<br>    const pixelData = [];<br>    for (let i = 0; i &lt; image.length; i += 3) {<br>      pixelData.push([image[i], image[i + 1], image[i + 2]]);<br>    }<br>    // Perform k-means clustering<br>    const clusters = skmeans(pixelData, numColors);<br>    // Return the color palette (cluster centroids)<br>    return clusters.centroids.map(([r, g, b]) =&gt; [Math.round(r), Math.round(g), Math.round(b)]);<br>  } catch (error) {<br>    console.error(&#39;Error:&#39;, error);<br>  }<br>}<br>const imagePath = &#39;path/to/your/image.jpg&#39;;<br>extractColors(imagePath, 5).then((palette) =&gt; {<br>  console.log(&#39;Color Palette:&#39;);<br>  console.log(palette);<br>});</pre><p>The code above outputs the colours in RGB — I wanted HEX.</p><pre>const sharp = require(&#39;sharp&#39;);<br>const skmeans = require(&#39;skmeans&#39;);<br>function rgbToHex(r, g, b) {<br>  return (<br>    &#39;#&#39; +<br>    [r, g, b]<br>      .map((color) =&gt; {<br>        const hex = color.toString(16);<br>        return hex.length === 1 ? &#39;0&#39; + hex : hex;<br>      })<br>      .join(&#39;&#39;)<br>  );<br>}<br>async function extractColors(imagePath, numColors = 5) {<br>  try {<br>    // Read and resize image<br>    const image = await sharp(imagePath).resize({ width: 100 }).raw().toBuffer();<br>    // Convert image data to an array of RGB values<br>    const pixelData = [];<br>    for (let i = 0; i &lt; image.length; i += 3) {<br>      pixelData.push([image[i], image[i + 1], image[i + 2]]);<br>    }<br>    // Perform k-means clustering<br>    const clusters = skmeans(pixelData, numColors);<br>    // Return the color palette (cluster centroids)<br>    return clusters.centroids.map(([r, g, b]) =&gt; [Math.round(r), Math.round(g), Math.round(b)]);<br>  } catch (error) {<br>    console.error(&#39;Error:&#39;, error);<br>  }<br>}<br>const imagePath = &#39;[your path]&#39;;<br>extractColors(imagePath, 9).then((palette) =&gt; {<br>  console.log(&#39;Color Palette:&#39;);<br>  palette.forEach(color =&gt; {<br>    console.log(rgbToHex(...color));<br>  });<br>});</pre><p>The output from the JavaScript code displays the colors as hexadecimal values. I can the use the colors as a basis for a basic HTML page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/1*0vIw4-RTMotr9XqzdUrs1w.png" /></figure><p>The colors you see are from the image used in the post.</p><h3>Using TailWindCSS for theming</h3><p>Using vanilla HTML/CSS might seem like a good idea at first but I ran into complications quickly. I do not want to necessarily spend time recreating a CSS framework — life is definitely too short. Not even sure how long that would take using ChatGPT. Doing simple things like column layouts becomes difficult when you don’t use a CSS framework. I decided to use TailWindCSS because I was also looking at <a href="https://remix.run/">Remix</a> for some or other reason. To get <a href="https://tailwindui.com/?ref=top">TailWindCSS</a> working in a project you need to have a Node project initialized. TailWindCSS uses NPM. In the little project I created I setup using npm i -y. I added the following NPM packages.</p><ul><li>npm i postcss</li><li>npm i postcss-cli</li></ul><p>I also added TailWindCSS as a dev dependency — npm i tailwindcss. I then created a postcss.config.js file.</p><pre>module.exports = {<br>    plugins: {<br>      tailwindcss: {}<br>    },<br>  };</pre><p>In my package.json I updated the scripts section to execute the CSS compilation.</p><pre>&quot;scripts&quot;: {<br>    &quot;build&quot;: &quot;postcss styles.css -o output.css&quot;,<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<br>  },</pre><p>By default TailWindCSS has a default set of colors — but I wanted to use the colors I generated from the image. So I added a tailwind.config.js file to my project.</p><pre>/** @type {import(&#39;tailwindcss&#39;).Config} */<br>module.exports = {<br>  content: [&#39;theme.html&#39;],<br>  theme: {<br>    extend: {<br>      backgroundImage: (theme) =&gt; ({<br>        &#39;header-bg&#39;: &quot;url(https://medium.com/&#39;[insert%20your%20image%20url%20here]&#39;)&quot;,<br>      }),<br>    },<br>    colors: {<br>        &#39;infinite-dark-blue&#39;: &#39;#010811&#39;,<br>        &#39;infinite-dark-teal&#39;: &#39;#2a525f&#39;,<br>        &#39;infinite-navy&#39;: &#39;#1b394c&#39;,<br>        &#39;infinite-soft-green&#39;: &#39;#9cc8a2&#39;,<br>        &#39;infinite-deep-blue&#39;: &#39;#061525&#39;,<br>        &#39;infinite-aqua&#39;: &#39;#28717e&#39;,<br>        &#39;infinite-dark-navy&#39;: &#39;#0f2438&#39;,<br>        &#39;infinite-turquoise&#39;: &#39;#48a496&#39;,<br>        &#39;infinite-gray&#39;: &#39;#6d6f67&#39;,<br>      },<br>  },<br>  variants: {},<br>  plugins: [],<br>};</pre><p>Getting the color names was an interesting process. I don’t know a lot about TailWindCSS yet — but I do believe it scans your HTML to generate the relevant CSS. So given a configuration file it will generate the color classes for you along with its specific classes, i.e column layouts. I prompted ChatGPT to generate an HTML design using the colors I generated using TailWindCSS. The template it generated at first used the hexadecimal values as class names.</p><pre>&lt;body class=&quot;bg-[#010811] text-[#6d6f67] min-h-screen flex flex-col items-center&quot;&gt;<br>  &lt;header class=&quot;bg-[#2a525f] w-full py-5 text-center&quot;&gt;<br>    &lt;h1 class=&quot;text-[#9cc8a2] font-bold&quot;&gt;InfiniteCanvas&lt;/h1&gt;<br>  &lt;/header&gt;</pre><p>I then prompted it to use the color names instead. Now you can see how it uses the colors from the TailWindCSS configuration.</p><pre>&lt;body class=&quot;bg-infinite-dark-blue text-infinite-gray min-h-screen flex flex-col items-center&quot;&gt;<br>  &lt;header class=&quot;bg-infinite-dark-teal w-full py-5 text-center&quot;&gt;<br>    &lt;h1 class=&quot;text-infinite-soft-green font-bold&quot;&gt;InfiniteCanvas&lt;/h1&gt;<br>  &lt;/header&gt;</pre><p>At this point I have TailWindCSS configured to generate the CSS — if you look at the scripts section of the package.json file it executes the postcss command. It uses style.css to generate output.css. style.css contains TailWindCSS imports.</p><pre>@tailwind base;<br>@tailwind components;<br>@tailwind utilities;</pre><p>I created a file, theme.html, to test the theme with a reference to output.css. The end result looked good! I did, however, add a few classes to the main tag of the page to stretch. I wanted the footer to sit neatly at the bottom.</p><pre>&lt;main class=&quot;container mx-auto py-10 py-5 flex-grow&quot;&gt;<br>    &lt;h2 class=&quot;text-infinite-turquoise font-bold&quot;&gt;My little theme&lt;/h2&gt;<br>    &lt;p class=&quot;text-infinite-gray mt-4&quot;&gt;<br>      Some content here<br>    &lt;/p&gt;<br>  &lt;/main&gt;</pre><p>You can see the results for yourself. I’m no expert designer but I found the design met my expectations. It uses the colors from the image I generated on MidJourney. I also set the background image in the header.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XfDwnTl4-iaTJNjqqfvAJQ.png" /></figure><h3>Some final thoughts</h3><p>Its really interesting what you can come up with when using a tool such as ChatGPT. I was able to ask it to create some JavaScript code to extract the colors from an image for me. I was then also able to get it to generate a basic TailWindCSS layout using the colors from the image as a theme. The interesting exercise for me though was the thought process, or should I say the prompt process. I started off with a basic idea — how do I get the colors from an image. Once I had the colors how do I generate the HTML to use the colors. Even though I initially did not want to use any CSS framework I felt that vanilla HTML/CSS would take require a lot of effort to generate layouts. CSS frameworks are better suited when you need layouts. Also note I am no CSS ninja. The prompting lead me down the road to explore TailWindCSS. With the basics in place I was able to configure TailWindCSS to use the colors generated from the image as a theme. I was also able to use ChatGPT to generate readable color names used the CSS. The end result — a functioning HTML template with a theme using a set of colors from an image.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d34106eaebef" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>